1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSet.h" 79 #include "llvm/ADT/StringSwitch.h" 80 #include "llvm/ADT/Triple.h" 81 #include "llvm/Support/AtomicOrdering.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/ConvertUTF.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/Locale.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/SaveAndRestore.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 #include <bitset> 93 #include <cassert> 94 #include <cctype> 95 #include <cstddef> 96 #include <cstdint> 97 #include <functional> 98 #include <limits> 99 #include <string> 100 #include <tuple> 101 #include <utility> 102 103 using namespace clang; 104 using namespace sema; 105 106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 107 unsigned ByteNo) const { 108 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 109 Context.getTargetInfo()); 110 } 111 112 /// Checks that a call expression's argument count is the desired number. 113 /// This is useful when doing custom type-checking. Returns true on error. 114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 115 unsigned argCount = call->getNumArgs(); 116 if (argCount == desiredArgCount) return false; 117 118 if (argCount < desiredArgCount) 119 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 120 << 0 /*function call*/ << desiredArgCount << argCount 121 << call->getSourceRange(); 122 123 // Highlight all the excess arguments. 124 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 125 call->getArg(argCount - 1)->getEndLoc()); 126 127 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 128 << 0 /*function call*/ << desiredArgCount << argCount 129 << call->getArg(1)->getSourceRange(); 130 } 131 132 /// Check that the first argument to __builtin_annotation is an integer 133 /// and the second argument is a non-wide string literal. 134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 135 if (checkArgCount(S, TheCall, 2)) 136 return true; 137 138 // First argument should be an integer. 139 Expr *ValArg = TheCall->getArg(0); 140 QualType Ty = ValArg->getType(); 141 if (!Ty->isIntegerType()) { 142 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 143 << ValArg->getSourceRange(); 144 return true; 145 } 146 147 // Second argument should be a constant string. 148 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 149 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 150 if (!Literal || !Literal->isAscii()) { 151 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 152 << StrArg->getSourceRange(); 153 return true; 154 } 155 156 TheCall->setType(Ty); 157 return false; 158 } 159 160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 161 // We need at least one argument. 162 if (TheCall->getNumArgs() < 1) { 163 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 164 << 0 << 1 << TheCall->getNumArgs() 165 << TheCall->getCallee()->getSourceRange(); 166 return true; 167 } 168 169 // All arguments should be wide string literals. 170 for (Expr *Arg : TheCall->arguments()) { 171 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 172 if (!Literal || !Literal->isWide()) { 173 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 174 << Arg->getSourceRange(); 175 return true; 176 } 177 } 178 179 return false; 180 } 181 182 /// Check that the argument to __builtin_addressof is a glvalue, and set the 183 /// result type to the corresponding pointer type. 184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 185 if (checkArgCount(S, TheCall, 1)) 186 return true; 187 188 ExprResult Arg(TheCall->getArg(0)); 189 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 190 if (ResultType.isNull()) 191 return true; 192 193 TheCall->setArg(0, Arg.get()); 194 TheCall->setType(ResultType); 195 return false; 196 } 197 198 /// Check the number of arguments and set the result type to 199 /// the argument type. 200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 201 if (checkArgCount(S, TheCall, 1)) 202 return true; 203 204 TheCall->setType(TheCall->getArg(0)->getType()); 205 return false; 206 } 207 208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 210 /// type (but not a function pointer) and that the alignment is a power-of-two. 211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 212 if (checkArgCount(S, TheCall, 2)) 213 return true; 214 215 clang::Expr *Source = TheCall->getArg(0); 216 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 217 218 auto IsValidIntegerType = [](QualType Ty) { 219 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 220 }; 221 QualType SrcTy = Source->getType(); 222 // We should also be able to use it with arrays (but not functions!). 223 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 224 SrcTy = S.Context.getDecayedType(SrcTy); 225 } 226 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 227 SrcTy->isFunctionPointerType()) { 228 // FIXME: this is not quite the right error message since we don't allow 229 // floating point types, or member pointers. 230 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 231 << SrcTy; 232 return true; 233 } 234 235 clang::Expr *AlignOp = TheCall->getArg(1); 236 if (!IsValidIntegerType(AlignOp->getType())) { 237 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 238 << AlignOp->getType(); 239 return true; 240 } 241 Expr::EvalResult AlignResult; 242 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 243 // We can't check validity of alignment if it is value dependent. 244 if (!AlignOp->isValueDependent() && 245 AlignOp->EvaluateAsInt(AlignResult, S.Context, 246 Expr::SE_AllowSideEffects)) { 247 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 248 llvm::APSInt MaxValue( 249 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 250 if (AlignValue < 1) { 251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 252 return true; 253 } 254 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 255 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 256 << toString(MaxValue, 10); 257 return true; 258 } 259 if (!AlignValue.isPowerOf2()) { 260 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 261 return true; 262 } 263 if (AlignValue == 1) { 264 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 265 << IsBooleanAlignBuiltin; 266 } 267 } 268 269 ExprResult SrcArg = S.PerformCopyInitialization( 270 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 271 SourceLocation(), Source); 272 if (SrcArg.isInvalid()) 273 return true; 274 TheCall->setArg(0, SrcArg.get()); 275 ExprResult AlignArg = 276 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 277 S.Context, AlignOp->getType(), false), 278 SourceLocation(), AlignOp); 279 if (AlignArg.isInvalid()) 280 return true; 281 TheCall->setArg(1, AlignArg.get()); 282 // For align_up/align_down, the return type is the same as the (potentially 283 // decayed) argument type including qualifiers. For is_aligned(), the result 284 // is always bool. 285 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 286 return false; 287 } 288 289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 290 unsigned BuiltinID) { 291 if (checkArgCount(S, TheCall, 3)) 292 return true; 293 294 // First two arguments should be integers. 295 for (unsigned I = 0; I < 2; ++I) { 296 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 297 if (Arg.isInvalid()) return true; 298 TheCall->setArg(I, Arg.get()); 299 300 QualType Ty = Arg.get()->getType(); 301 if (!Ty->isIntegerType()) { 302 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 303 << Ty << Arg.get()->getSourceRange(); 304 return true; 305 } 306 } 307 308 // Third argument should be a pointer to a non-const integer. 309 // IRGen correctly handles volatile, restrict, and address spaces, and 310 // the other qualifiers aren't possible. 311 { 312 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 313 if (Arg.isInvalid()) return true; 314 TheCall->setArg(2, Arg.get()); 315 316 QualType Ty = Arg.get()->getType(); 317 const auto *PtrTy = Ty->getAs<PointerType>(); 318 if (!PtrTy || 319 !PtrTy->getPointeeType()->isIntegerType() || 320 PtrTy->getPointeeType().isConstQualified()) { 321 S.Diag(Arg.get()->getBeginLoc(), 322 diag::err_overflow_builtin_must_be_ptr_int) 323 << Ty << Arg.get()->getSourceRange(); 324 return true; 325 } 326 } 327 328 // Disallow signed bit-precise integer args larger than 128 bits to mul 329 // function until we improve backend support. 330 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 331 for (unsigned I = 0; I < 3; ++I) { 332 const auto Arg = TheCall->getArg(I); 333 // Third argument will be a pointer. 334 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 335 if (Ty->isBitIntType() && Ty->isSignedIntegerType() && 336 S.getASTContext().getIntWidth(Ty) > 128) 337 return S.Diag(Arg->getBeginLoc(), 338 diag::err_overflow_builtin_bit_int_max_size) 339 << 128; 340 } 341 } 342 343 return false; 344 } 345 346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 347 if (checkArgCount(S, BuiltinCall, 2)) 348 return true; 349 350 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 351 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 352 Expr *Call = BuiltinCall->getArg(0); 353 Expr *Chain = BuiltinCall->getArg(1); 354 355 if (Call->getStmtClass() != Stmt::CallExprClass) { 356 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 357 << Call->getSourceRange(); 358 return true; 359 } 360 361 auto CE = cast<CallExpr>(Call); 362 if (CE->getCallee()->getType()->isBlockPointerType()) { 363 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 364 << Call->getSourceRange(); 365 return true; 366 } 367 368 const Decl *TargetDecl = CE->getCalleeDecl(); 369 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 370 if (FD->getBuiltinID()) { 371 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 372 << Call->getSourceRange(); 373 return true; 374 } 375 376 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 377 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 378 << Call->getSourceRange(); 379 return true; 380 } 381 382 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 383 if (ChainResult.isInvalid()) 384 return true; 385 if (!ChainResult.get()->getType()->isPointerType()) { 386 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 387 << Chain->getSourceRange(); 388 return true; 389 } 390 391 QualType ReturnTy = CE->getCallReturnType(S.Context); 392 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 393 QualType BuiltinTy = S.Context.getFunctionType( 394 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 395 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 396 397 Builtin = 398 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 399 400 BuiltinCall->setType(CE->getType()); 401 BuiltinCall->setValueKind(CE->getValueKind()); 402 BuiltinCall->setObjectKind(CE->getObjectKind()); 403 BuiltinCall->setCallee(Builtin); 404 BuiltinCall->setArg(1, ChainResult.get()); 405 406 return false; 407 } 408 409 namespace { 410 411 class ScanfDiagnosticFormatHandler 412 : public analyze_format_string::FormatStringHandler { 413 // Accepts the argument index (relative to the first destination index) of the 414 // argument whose size we want. 415 using ComputeSizeFunction = 416 llvm::function_ref<Optional<llvm::APSInt>(unsigned)>; 417 418 // Accepts the argument index (relative to the first destination index), the 419 // destination size, and the source size). 420 using DiagnoseFunction = 421 llvm::function_ref<void(unsigned, unsigned, unsigned)>; 422 423 ComputeSizeFunction ComputeSizeArgument; 424 DiagnoseFunction Diagnose; 425 426 public: 427 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument, 428 DiagnoseFunction Diagnose) 429 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {} 430 431 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 432 const char *StartSpecifier, 433 unsigned specifierLen) override { 434 if (!FS.consumesDataArgument()) 435 return true; 436 437 unsigned NulByte = 0; 438 switch ((FS.getConversionSpecifier().getKind())) { 439 default: 440 return true; 441 case analyze_format_string::ConversionSpecifier::sArg: 442 case analyze_format_string::ConversionSpecifier::ScanListArg: 443 NulByte = 1; 444 break; 445 case analyze_format_string::ConversionSpecifier::cArg: 446 break; 447 } 448 449 auto OptionalFW = FS.getFieldWidth(); 450 if (OptionalFW.getHowSpecified() != 451 analyze_format_string::OptionalAmount::HowSpecified::Constant) 452 return true; 453 454 unsigned SourceSize = OptionalFW.getConstantAmount() + NulByte; 455 456 auto DestSizeAPS = ComputeSizeArgument(FS.getArgIndex()); 457 if (!DestSizeAPS) 458 return true; 459 460 unsigned DestSize = DestSizeAPS->getZExtValue(); 461 462 if (DestSize < SourceSize) 463 Diagnose(FS.getArgIndex(), DestSize, SourceSize); 464 465 return true; 466 } 467 }; 468 469 class EstimateSizeFormatHandler 470 : public analyze_format_string::FormatStringHandler { 471 size_t Size; 472 473 public: 474 EstimateSizeFormatHandler(StringRef Format) 475 : Size(std::min(Format.find(0), Format.size()) + 476 1 /* null byte always written by sprintf */) {} 477 478 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 479 const char *, unsigned SpecifierLen) override { 480 481 const size_t FieldWidth = computeFieldWidth(FS); 482 const size_t Precision = computePrecision(FS); 483 484 // The actual format. 485 switch (FS.getConversionSpecifier().getKind()) { 486 // Just a char. 487 case analyze_format_string::ConversionSpecifier::cArg: 488 case analyze_format_string::ConversionSpecifier::CArg: 489 Size += std::max(FieldWidth, (size_t)1); 490 break; 491 // Just an integer. 492 case analyze_format_string::ConversionSpecifier::dArg: 493 case analyze_format_string::ConversionSpecifier::DArg: 494 case analyze_format_string::ConversionSpecifier::iArg: 495 case analyze_format_string::ConversionSpecifier::oArg: 496 case analyze_format_string::ConversionSpecifier::OArg: 497 case analyze_format_string::ConversionSpecifier::uArg: 498 case analyze_format_string::ConversionSpecifier::UArg: 499 case analyze_format_string::ConversionSpecifier::xArg: 500 case analyze_format_string::ConversionSpecifier::XArg: 501 Size += std::max(FieldWidth, Precision); 502 break; 503 504 // %g style conversion switches between %f or %e style dynamically. 505 // %f always takes less space, so default to it. 506 case analyze_format_string::ConversionSpecifier::gArg: 507 case analyze_format_string::ConversionSpecifier::GArg: 508 509 // Floating point number in the form '[+]ddd.ddd'. 510 case analyze_format_string::ConversionSpecifier::fArg: 511 case analyze_format_string::ConversionSpecifier::FArg: 512 Size += std::max(FieldWidth, 1 /* integer part */ + 513 (Precision ? 1 + Precision 514 : 0) /* period + decimal */); 515 break; 516 517 // Floating point number in the form '[-]d.ddde[+-]dd'. 518 case analyze_format_string::ConversionSpecifier::eArg: 519 case analyze_format_string::ConversionSpecifier::EArg: 520 Size += 521 std::max(FieldWidth, 522 1 /* integer part */ + 523 (Precision ? 1 + Precision : 0) /* period + decimal */ + 524 1 /* e or E letter */ + 2 /* exponent */); 525 break; 526 527 // Floating point number in the form '[-]0xh.hhhhp±dd'. 528 case analyze_format_string::ConversionSpecifier::aArg: 529 case analyze_format_string::ConversionSpecifier::AArg: 530 Size += 531 std::max(FieldWidth, 532 2 /* 0x */ + 1 /* integer part */ + 533 (Precision ? 1 + Precision : 0) /* period + decimal */ + 534 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 535 break; 536 537 // Just a string. 538 case analyze_format_string::ConversionSpecifier::sArg: 539 case analyze_format_string::ConversionSpecifier::SArg: 540 Size += FieldWidth; 541 break; 542 543 // Just a pointer in the form '0xddd'. 544 case analyze_format_string::ConversionSpecifier::pArg: 545 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 546 break; 547 548 // A plain percent. 549 case analyze_format_string::ConversionSpecifier::PercentArg: 550 Size += 1; 551 break; 552 553 default: 554 break; 555 } 556 557 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 558 559 if (FS.hasAlternativeForm()) { 560 switch (FS.getConversionSpecifier().getKind()) { 561 default: 562 break; 563 // Force a leading '0'. 564 case analyze_format_string::ConversionSpecifier::oArg: 565 Size += 1; 566 break; 567 // Force a leading '0x'. 568 case analyze_format_string::ConversionSpecifier::xArg: 569 case analyze_format_string::ConversionSpecifier::XArg: 570 Size += 2; 571 break; 572 // Force a period '.' before decimal, even if precision is 0. 573 case analyze_format_string::ConversionSpecifier::aArg: 574 case analyze_format_string::ConversionSpecifier::AArg: 575 case analyze_format_string::ConversionSpecifier::eArg: 576 case analyze_format_string::ConversionSpecifier::EArg: 577 case analyze_format_string::ConversionSpecifier::fArg: 578 case analyze_format_string::ConversionSpecifier::FArg: 579 case analyze_format_string::ConversionSpecifier::gArg: 580 case analyze_format_string::ConversionSpecifier::GArg: 581 Size += (Precision ? 0 : 1); 582 break; 583 } 584 } 585 assert(SpecifierLen <= Size && "no underflow"); 586 Size -= SpecifierLen; 587 return true; 588 } 589 590 size_t getSizeLowerBound() const { return Size; } 591 592 private: 593 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 594 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 595 size_t FieldWidth = 0; 596 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 597 FieldWidth = FW.getConstantAmount(); 598 return FieldWidth; 599 } 600 601 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 602 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 603 size_t Precision = 0; 604 605 // See man 3 printf for default precision value based on the specifier. 606 switch (FW.getHowSpecified()) { 607 case analyze_format_string::OptionalAmount::NotSpecified: 608 switch (FS.getConversionSpecifier().getKind()) { 609 default: 610 break; 611 case analyze_format_string::ConversionSpecifier::dArg: // %d 612 case analyze_format_string::ConversionSpecifier::DArg: // %D 613 case analyze_format_string::ConversionSpecifier::iArg: // %i 614 Precision = 1; 615 break; 616 case analyze_format_string::ConversionSpecifier::oArg: // %d 617 case analyze_format_string::ConversionSpecifier::OArg: // %D 618 case analyze_format_string::ConversionSpecifier::uArg: // %d 619 case analyze_format_string::ConversionSpecifier::UArg: // %D 620 case analyze_format_string::ConversionSpecifier::xArg: // %d 621 case analyze_format_string::ConversionSpecifier::XArg: // %D 622 Precision = 1; 623 break; 624 case analyze_format_string::ConversionSpecifier::fArg: // %f 625 case analyze_format_string::ConversionSpecifier::FArg: // %F 626 case analyze_format_string::ConversionSpecifier::eArg: // %e 627 case analyze_format_string::ConversionSpecifier::EArg: // %E 628 case analyze_format_string::ConversionSpecifier::gArg: // %g 629 case analyze_format_string::ConversionSpecifier::GArg: // %G 630 Precision = 6; 631 break; 632 case analyze_format_string::ConversionSpecifier::pArg: // %d 633 Precision = 1; 634 break; 635 } 636 break; 637 case analyze_format_string::OptionalAmount::Constant: 638 Precision = FW.getConstantAmount(); 639 break; 640 default: 641 break; 642 } 643 return Precision; 644 } 645 }; 646 647 } // namespace 648 649 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 650 CallExpr *TheCall) { 651 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 652 isConstantEvaluated()) 653 return; 654 655 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 656 if (!BuiltinID) 657 return; 658 659 const TargetInfo &TI = getASTContext().getTargetInfo(); 660 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 661 662 auto ComputeExplicitObjectSizeArgument = 663 [&](unsigned Index) -> Optional<llvm::APSInt> { 664 Expr::EvalResult Result; 665 Expr *SizeArg = TheCall->getArg(Index); 666 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 667 return llvm::None; 668 return Result.Val.getInt(); 669 }; 670 671 auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 672 // If the parameter has a pass_object_size attribute, then we should use its 673 // (potentially) more strict checking mode. Otherwise, conservatively assume 674 // type 0. 675 int BOSType = 0; 676 // This check can fail for variadic functions. 677 if (Index < FD->getNumParams()) { 678 if (const auto *POS = 679 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>()) 680 BOSType = POS->getType(); 681 } 682 683 const Expr *ObjArg = TheCall->getArg(Index); 684 uint64_t Result; 685 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 686 return llvm::None; 687 688 // Get the object size in the target's size_t width. 689 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 690 }; 691 692 auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 693 Expr *ObjArg = TheCall->getArg(Index); 694 uint64_t Result; 695 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext())) 696 return llvm::None; 697 // Add 1 for null byte. 698 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth); 699 }; 700 701 Optional<llvm::APSInt> SourceSize; 702 Optional<llvm::APSInt> DestinationSize; 703 unsigned DiagID = 0; 704 bool IsChkVariant = false; 705 706 auto GetFunctionName = [&]() { 707 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 708 // Skim off the details of whichever builtin was called to produce a better 709 // diagnostic, as it's unlikely that the user wrote the __builtin 710 // explicitly. 711 if (IsChkVariant) { 712 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 713 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 714 } else if (FunctionName.startswith("__builtin_")) { 715 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 716 } 717 return FunctionName; 718 }; 719 720 switch (BuiltinID) { 721 default: 722 return; 723 case Builtin::BI__builtin_strcpy: 724 case Builtin::BIstrcpy: { 725 DiagID = diag::warn_fortify_strlen_overflow; 726 SourceSize = ComputeStrLenArgument(1); 727 DestinationSize = ComputeSizeArgument(0); 728 break; 729 } 730 731 case Builtin::BI__builtin___strcpy_chk: { 732 DiagID = diag::warn_fortify_strlen_overflow; 733 SourceSize = ComputeStrLenArgument(1); 734 DestinationSize = ComputeExplicitObjectSizeArgument(2); 735 IsChkVariant = true; 736 break; 737 } 738 739 case Builtin::BIscanf: 740 case Builtin::BIfscanf: 741 case Builtin::BIsscanf: { 742 unsigned FormatIndex = 1; 743 unsigned DataIndex = 2; 744 if (BuiltinID == Builtin::BIscanf) { 745 FormatIndex = 0; 746 DataIndex = 1; 747 } 748 749 const auto *FormatExpr = 750 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 751 752 const auto *Format = dyn_cast<StringLiteral>(FormatExpr); 753 if (!Format) 754 return; 755 756 if (!Format->isAscii() && !Format->isUTF8()) 757 return; 758 759 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize, 760 unsigned SourceSize) { 761 DiagID = diag::warn_fortify_scanf_overflow; 762 unsigned Index = ArgIndex + DataIndex; 763 StringRef FunctionName = GetFunctionName(); 764 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall, 765 PDiag(DiagID) << FunctionName << (Index + 1) 766 << DestSize << SourceSize); 767 }; 768 769 StringRef FormatStrRef = Format->getString(); 770 auto ShiftedComputeSizeArgument = [&](unsigned Index) { 771 return ComputeSizeArgument(Index + DataIndex); 772 }; 773 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose); 774 const char *FormatBytes = FormatStrRef.data(); 775 const ConstantArrayType *T = 776 Context.getAsConstantArrayType(Format->getType()); 777 assert(T && "String literal not of constant array type!"); 778 size_t TypeSize = T->getSize().getZExtValue(); 779 780 // In case there's a null byte somewhere. 781 size_t StrLen = 782 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 783 784 analyze_format_string::ParseScanfString(H, FormatBytes, 785 FormatBytes + StrLen, getLangOpts(), 786 Context.getTargetInfo()); 787 788 // Unlike the other cases, in this one we have already issued the diagnostic 789 // here, so no need to continue (because unlike the other cases, here the 790 // diagnostic refers to the argument number). 791 return; 792 } 793 794 case Builtin::BIsprintf: 795 case Builtin::BI__builtin___sprintf_chk: { 796 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 797 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 798 799 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 800 801 if (!Format->isAscii() && !Format->isUTF8()) 802 return; 803 804 StringRef FormatStrRef = Format->getString(); 805 EstimateSizeFormatHandler H(FormatStrRef); 806 const char *FormatBytes = FormatStrRef.data(); 807 const ConstantArrayType *T = 808 Context.getAsConstantArrayType(Format->getType()); 809 assert(T && "String literal not of constant array type!"); 810 size_t TypeSize = T->getSize().getZExtValue(); 811 812 // In case there's a null byte somewhere. 813 size_t StrLen = 814 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 815 if (!analyze_format_string::ParsePrintfString( 816 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 817 Context.getTargetInfo(), false)) { 818 DiagID = diag::warn_fortify_source_format_overflow; 819 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 820 .extOrTrunc(SizeTypeWidth); 821 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 822 DestinationSize = ComputeExplicitObjectSizeArgument(2); 823 IsChkVariant = true; 824 } else { 825 DestinationSize = ComputeSizeArgument(0); 826 } 827 break; 828 } 829 } 830 return; 831 } 832 case Builtin::BI__builtin___memcpy_chk: 833 case Builtin::BI__builtin___memmove_chk: 834 case Builtin::BI__builtin___memset_chk: 835 case Builtin::BI__builtin___strlcat_chk: 836 case Builtin::BI__builtin___strlcpy_chk: 837 case Builtin::BI__builtin___strncat_chk: 838 case Builtin::BI__builtin___strncpy_chk: 839 case Builtin::BI__builtin___stpncpy_chk: 840 case Builtin::BI__builtin___memccpy_chk: 841 case Builtin::BI__builtin___mempcpy_chk: { 842 DiagID = diag::warn_builtin_chk_overflow; 843 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2); 844 DestinationSize = 845 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 846 IsChkVariant = true; 847 break; 848 } 849 850 case Builtin::BI__builtin___snprintf_chk: 851 case Builtin::BI__builtin___vsnprintf_chk: { 852 DiagID = diag::warn_builtin_chk_overflow; 853 SourceSize = ComputeExplicitObjectSizeArgument(1); 854 DestinationSize = ComputeExplicitObjectSizeArgument(3); 855 IsChkVariant = true; 856 break; 857 } 858 859 case Builtin::BIstrncat: 860 case Builtin::BI__builtin_strncat: 861 case Builtin::BIstrncpy: 862 case Builtin::BI__builtin_strncpy: 863 case Builtin::BIstpncpy: 864 case Builtin::BI__builtin_stpncpy: { 865 // Whether these functions overflow depends on the runtime strlen of the 866 // string, not just the buffer size, so emitting the "always overflow" 867 // diagnostic isn't quite right. We should still diagnose passing a buffer 868 // size larger than the destination buffer though; this is a runtime abort 869 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 870 DiagID = diag::warn_fortify_source_size_mismatch; 871 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 872 DestinationSize = ComputeSizeArgument(0); 873 break; 874 } 875 876 case Builtin::BImemcpy: 877 case Builtin::BI__builtin_memcpy: 878 case Builtin::BImemmove: 879 case Builtin::BI__builtin_memmove: 880 case Builtin::BImemset: 881 case Builtin::BI__builtin_memset: 882 case Builtin::BImempcpy: 883 case Builtin::BI__builtin_mempcpy: { 884 DiagID = diag::warn_fortify_source_overflow; 885 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 886 DestinationSize = ComputeSizeArgument(0); 887 break; 888 } 889 case Builtin::BIsnprintf: 890 case Builtin::BI__builtin_snprintf: 891 case Builtin::BIvsnprintf: 892 case Builtin::BI__builtin_vsnprintf: { 893 DiagID = diag::warn_fortify_source_size_mismatch; 894 SourceSize = ComputeExplicitObjectSizeArgument(1); 895 DestinationSize = ComputeSizeArgument(0); 896 break; 897 } 898 } 899 900 if (!SourceSize || !DestinationSize || 901 SourceSize.getValue().ule(DestinationSize.getValue())) 902 return; 903 904 StringRef FunctionName = GetFunctionName(); 905 906 SmallString<16> DestinationStr; 907 SmallString<16> SourceStr; 908 DestinationSize->toString(DestinationStr, /*Radix=*/10); 909 SourceSize->toString(SourceStr, /*Radix=*/10); 910 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 911 PDiag(DiagID) 912 << FunctionName << DestinationStr << SourceStr); 913 } 914 915 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 916 Scope::ScopeFlags NeededScopeFlags, 917 unsigned DiagID) { 918 // Scopes aren't available during instantiation. Fortunately, builtin 919 // functions cannot be template args so they cannot be formed through template 920 // instantiation. Therefore checking once during the parse is sufficient. 921 if (SemaRef.inTemplateInstantiation()) 922 return false; 923 924 Scope *S = SemaRef.getCurScope(); 925 while (S && !S->isSEHExceptScope()) 926 S = S->getParent(); 927 if (!S || !(S->getFlags() & NeededScopeFlags)) { 928 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 929 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 930 << DRE->getDecl()->getIdentifier(); 931 return true; 932 } 933 934 return false; 935 } 936 937 static inline bool isBlockPointer(Expr *Arg) { 938 return Arg->getType()->isBlockPointerType(); 939 } 940 941 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 942 /// void*, which is a requirement of device side enqueue. 943 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 944 const BlockPointerType *BPT = 945 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 946 ArrayRef<QualType> Params = 947 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 948 unsigned ArgCounter = 0; 949 bool IllegalParams = false; 950 // Iterate through the block parameters until either one is found that is not 951 // a local void*, or the block is valid. 952 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 953 I != E; ++I, ++ArgCounter) { 954 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 955 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 956 LangAS::opencl_local) { 957 // Get the location of the error. If a block literal has been passed 958 // (BlockExpr) then we can point straight to the offending argument, 959 // else we just point to the variable reference. 960 SourceLocation ErrorLoc; 961 if (isa<BlockExpr>(BlockArg)) { 962 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 963 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 964 } else if (isa<DeclRefExpr>(BlockArg)) { 965 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 966 } 967 S.Diag(ErrorLoc, 968 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 969 IllegalParams = true; 970 } 971 } 972 973 return IllegalParams; 974 } 975 976 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 977 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) { 978 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 979 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 980 return true; 981 } 982 return false; 983 } 984 985 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 986 if (checkArgCount(S, TheCall, 2)) 987 return true; 988 989 if (checkOpenCLSubgroupExt(S, TheCall)) 990 return true; 991 992 // First argument is an ndrange_t type. 993 Expr *NDRangeArg = TheCall->getArg(0); 994 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 995 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 996 << TheCall->getDirectCallee() << "'ndrange_t'"; 997 return true; 998 } 999 1000 Expr *BlockArg = TheCall->getArg(1); 1001 if (!isBlockPointer(BlockArg)) { 1002 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1003 << TheCall->getDirectCallee() << "block"; 1004 return true; 1005 } 1006 return checkOpenCLBlockArgs(S, BlockArg); 1007 } 1008 1009 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 1010 /// get_kernel_work_group_size 1011 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 1012 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 1013 if (checkArgCount(S, TheCall, 1)) 1014 return true; 1015 1016 Expr *BlockArg = TheCall->getArg(0); 1017 if (!isBlockPointer(BlockArg)) { 1018 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1019 << TheCall->getDirectCallee() << "block"; 1020 return true; 1021 } 1022 return checkOpenCLBlockArgs(S, BlockArg); 1023 } 1024 1025 /// Diagnose integer type and any valid implicit conversion to it. 1026 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 1027 const QualType &IntType); 1028 1029 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 1030 unsigned Start, unsigned End) { 1031 bool IllegalParams = false; 1032 for (unsigned I = Start; I <= End; ++I) 1033 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 1034 S.Context.getSizeType()); 1035 return IllegalParams; 1036 } 1037 1038 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 1039 /// 'local void*' parameter of passed block. 1040 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 1041 Expr *BlockArg, 1042 unsigned NumNonVarArgs) { 1043 const BlockPointerType *BPT = 1044 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 1045 unsigned NumBlockParams = 1046 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 1047 unsigned TotalNumArgs = TheCall->getNumArgs(); 1048 1049 // For each argument passed to the block, a corresponding uint needs to 1050 // be passed to describe the size of the local memory. 1051 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 1052 S.Diag(TheCall->getBeginLoc(), 1053 diag::err_opencl_enqueue_kernel_local_size_args); 1054 return true; 1055 } 1056 1057 // Check that the sizes of the local memory are specified by integers. 1058 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 1059 TotalNumArgs - 1); 1060 } 1061 1062 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 1063 /// overload formats specified in Table 6.13.17.1. 1064 /// int enqueue_kernel(queue_t queue, 1065 /// kernel_enqueue_flags_t flags, 1066 /// const ndrange_t ndrange, 1067 /// void (^block)(void)) 1068 /// int enqueue_kernel(queue_t queue, 1069 /// kernel_enqueue_flags_t flags, 1070 /// const ndrange_t ndrange, 1071 /// uint num_events_in_wait_list, 1072 /// clk_event_t *event_wait_list, 1073 /// clk_event_t *event_ret, 1074 /// void (^block)(void)) 1075 /// int enqueue_kernel(queue_t queue, 1076 /// kernel_enqueue_flags_t flags, 1077 /// const ndrange_t ndrange, 1078 /// void (^block)(local void*, ...), 1079 /// uint size0, ...) 1080 /// int enqueue_kernel(queue_t queue, 1081 /// kernel_enqueue_flags_t flags, 1082 /// const ndrange_t ndrange, 1083 /// uint num_events_in_wait_list, 1084 /// clk_event_t *event_wait_list, 1085 /// clk_event_t *event_ret, 1086 /// void (^block)(local void*, ...), 1087 /// uint size0, ...) 1088 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 1089 unsigned NumArgs = TheCall->getNumArgs(); 1090 1091 if (NumArgs < 4) { 1092 S.Diag(TheCall->getBeginLoc(), 1093 diag::err_typecheck_call_too_few_args_at_least) 1094 << 0 << 4 << NumArgs; 1095 return true; 1096 } 1097 1098 Expr *Arg0 = TheCall->getArg(0); 1099 Expr *Arg1 = TheCall->getArg(1); 1100 Expr *Arg2 = TheCall->getArg(2); 1101 Expr *Arg3 = TheCall->getArg(3); 1102 1103 // First argument always needs to be a queue_t type. 1104 if (!Arg0->getType()->isQueueT()) { 1105 S.Diag(TheCall->getArg(0)->getBeginLoc(), 1106 diag::err_opencl_builtin_expected_type) 1107 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 1108 return true; 1109 } 1110 1111 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 1112 if (!Arg1->getType()->isIntegerType()) { 1113 S.Diag(TheCall->getArg(1)->getBeginLoc(), 1114 diag::err_opencl_builtin_expected_type) 1115 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 1116 return true; 1117 } 1118 1119 // Third argument is always an ndrange_t type. 1120 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 1121 S.Diag(TheCall->getArg(2)->getBeginLoc(), 1122 diag::err_opencl_builtin_expected_type) 1123 << TheCall->getDirectCallee() << "'ndrange_t'"; 1124 return true; 1125 } 1126 1127 // With four arguments, there is only one form that the function could be 1128 // called in: no events and no variable arguments. 1129 if (NumArgs == 4) { 1130 // check that the last argument is the right block type. 1131 if (!isBlockPointer(Arg3)) { 1132 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1133 << TheCall->getDirectCallee() << "block"; 1134 return true; 1135 } 1136 // we have a block type, check the prototype 1137 const BlockPointerType *BPT = 1138 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1139 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1140 S.Diag(Arg3->getBeginLoc(), 1141 diag::err_opencl_enqueue_kernel_blocks_no_args); 1142 return true; 1143 } 1144 return false; 1145 } 1146 // we can have block + varargs. 1147 if (isBlockPointer(Arg3)) 1148 return (checkOpenCLBlockArgs(S, Arg3) || 1149 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1150 // last two cases with either exactly 7 args or 7 args and varargs. 1151 if (NumArgs >= 7) { 1152 // check common block argument. 1153 Expr *Arg6 = TheCall->getArg(6); 1154 if (!isBlockPointer(Arg6)) { 1155 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1156 << TheCall->getDirectCallee() << "block"; 1157 return true; 1158 } 1159 if (checkOpenCLBlockArgs(S, Arg6)) 1160 return true; 1161 1162 // Forth argument has to be any integer type. 1163 if (!Arg3->getType()->isIntegerType()) { 1164 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1165 diag::err_opencl_builtin_expected_type) 1166 << TheCall->getDirectCallee() << "integer"; 1167 return true; 1168 } 1169 // check remaining common arguments. 1170 Expr *Arg4 = TheCall->getArg(4); 1171 Expr *Arg5 = TheCall->getArg(5); 1172 1173 // Fifth argument is always passed as a pointer to clk_event_t. 1174 if (!Arg4->isNullPointerConstant(S.Context, 1175 Expr::NPC_ValueDependentIsNotNull) && 1176 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1177 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1178 diag::err_opencl_builtin_expected_type) 1179 << TheCall->getDirectCallee() 1180 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1181 return true; 1182 } 1183 1184 // Sixth argument is always passed as a pointer to clk_event_t. 1185 if (!Arg5->isNullPointerConstant(S.Context, 1186 Expr::NPC_ValueDependentIsNotNull) && 1187 !(Arg5->getType()->isPointerType() && 1188 Arg5->getType()->getPointeeType()->isClkEventT())) { 1189 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1190 diag::err_opencl_builtin_expected_type) 1191 << TheCall->getDirectCallee() 1192 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1193 return true; 1194 } 1195 1196 if (NumArgs == 7) 1197 return false; 1198 1199 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1200 } 1201 1202 // None of the specific case has been detected, give generic error 1203 S.Diag(TheCall->getBeginLoc(), 1204 diag::err_opencl_enqueue_kernel_incorrect_args); 1205 return true; 1206 } 1207 1208 /// Returns OpenCL access qual. 1209 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1210 return D->getAttr<OpenCLAccessAttr>(); 1211 } 1212 1213 /// Returns true if pipe element type is different from the pointer. 1214 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1215 const Expr *Arg0 = Call->getArg(0); 1216 // First argument type should always be pipe. 1217 if (!Arg0->getType()->isPipeType()) { 1218 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1219 << Call->getDirectCallee() << Arg0->getSourceRange(); 1220 return true; 1221 } 1222 OpenCLAccessAttr *AccessQual = 1223 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1224 // Validates the access qualifier is compatible with the call. 1225 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1226 // read_only and write_only, and assumed to be read_only if no qualifier is 1227 // specified. 1228 switch (Call->getDirectCallee()->getBuiltinID()) { 1229 case Builtin::BIread_pipe: 1230 case Builtin::BIreserve_read_pipe: 1231 case Builtin::BIcommit_read_pipe: 1232 case Builtin::BIwork_group_reserve_read_pipe: 1233 case Builtin::BIsub_group_reserve_read_pipe: 1234 case Builtin::BIwork_group_commit_read_pipe: 1235 case Builtin::BIsub_group_commit_read_pipe: 1236 if (!(!AccessQual || AccessQual->isReadOnly())) { 1237 S.Diag(Arg0->getBeginLoc(), 1238 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1239 << "read_only" << Arg0->getSourceRange(); 1240 return true; 1241 } 1242 break; 1243 case Builtin::BIwrite_pipe: 1244 case Builtin::BIreserve_write_pipe: 1245 case Builtin::BIcommit_write_pipe: 1246 case Builtin::BIwork_group_reserve_write_pipe: 1247 case Builtin::BIsub_group_reserve_write_pipe: 1248 case Builtin::BIwork_group_commit_write_pipe: 1249 case Builtin::BIsub_group_commit_write_pipe: 1250 if (!(AccessQual && AccessQual->isWriteOnly())) { 1251 S.Diag(Arg0->getBeginLoc(), 1252 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1253 << "write_only" << Arg0->getSourceRange(); 1254 return true; 1255 } 1256 break; 1257 default: 1258 break; 1259 } 1260 return false; 1261 } 1262 1263 /// Returns true if pipe element type is different from the pointer. 1264 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1265 const Expr *Arg0 = Call->getArg(0); 1266 const Expr *ArgIdx = Call->getArg(Idx); 1267 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1268 const QualType EltTy = PipeTy->getElementType(); 1269 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1270 // The Idx argument should be a pointer and the type of the pointer and 1271 // the type of pipe element should also be the same. 1272 if (!ArgTy || 1273 !S.Context.hasSameType( 1274 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1275 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1276 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1277 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1278 return true; 1279 } 1280 return false; 1281 } 1282 1283 // Performs semantic analysis for the read/write_pipe call. 1284 // \param S Reference to the semantic analyzer. 1285 // \param Call A pointer to the builtin call. 1286 // \return True if a semantic error has been found, false otherwise. 1287 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1288 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1289 // functions have two forms. 1290 switch (Call->getNumArgs()) { 1291 case 2: 1292 if (checkOpenCLPipeArg(S, Call)) 1293 return true; 1294 // The call with 2 arguments should be 1295 // read/write_pipe(pipe T, T*). 1296 // Check packet type T. 1297 if (checkOpenCLPipePacketType(S, Call, 1)) 1298 return true; 1299 break; 1300 1301 case 4: { 1302 if (checkOpenCLPipeArg(S, Call)) 1303 return true; 1304 // The call with 4 arguments should be 1305 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1306 // Check reserve_id_t. 1307 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1308 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1309 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1310 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1311 return true; 1312 } 1313 1314 // Check the index. 1315 const Expr *Arg2 = Call->getArg(2); 1316 if (!Arg2->getType()->isIntegerType() && 1317 !Arg2->getType()->isUnsignedIntegerType()) { 1318 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1319 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1320 << Arg2->getType() << Arg2->getSourceRange(); 1321 return true; 1322 } 1323 1324 // Check packet type T. 1325 if (checkOpenCLPipePacketType(S, Call, 3)) 1326 return true; 1327 } break; 1328 default: 1329 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1330 << Call->getDirectCallee() << Call->getSourceRange(); 1331 return true; 1332 } 1333 1334 return false; 1335 } 1336 1337 // Performs a semantic analysis on the {work_group_/sub_group_ 1338 // /_}reserve_{read/write}_pipe 1339 // \param S Reference to the semantic analyzer. 1340 // \param Call The call to the builtin function to be analyzed. 1341 // \return True if a semantic error was found, false otherwise. 1342 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1343 if (checkArgCount(S, Call, 2)) 1344 return true; 1345 1346 if (checkOpenCLPipeArg(S, Call)) 1347 return true; 1348 1349 // Check the reserve size. 1350 if (!Call->getArg(1)->getType()->isIntegerType() && 1351 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1352 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1353 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1354 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1355 return true; 1356 } 1357 1358 // Since return type of reserve_read/write_pipe built-in function is 1359 // reserve_id_t, which is not defined in the builtin def file , we used int 1360 // as return type and need to override the return type of these functions. 1361 Call->setType(S.Context.OCLReserveIDTy); 1362 1363 return false; 1364 } 1365 1366 // Performs a semantic analysis on {work_group_/sub_group_ 1367 // /_}commit_{read/write}_pipe 1368 // \param S Reference to the semantic analyzer. 1369 // \param Call The call to the builtin function to be analyzed. 1370 // \return True if a semantic error was found, false otherwise. 1371 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1372 if (checkArgCount(S, Call, 2)) 1373 return true; 1374 1375 if (checkOpenCLPipeArg(S, Call)) 1376 return true; 1377 1378 // Check reserve_id_t. 1379 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1380 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1381 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1382 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1383 return true; 1384 } 1385 1386 return false; 1387 } 1388 1389 // Performs a semantic analysis on the call to built-in Pipe 1390 // Query Functions. 1391 // \param S Reference to the semantic analyzer. 1392 // \param Call The call to the builtin function to be analyzed. 1393 // \return True if a semantic error was found, false otherwise. 1394 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1395 if (checkArgCount(S, Call, 1)) 1396 return true; 1397 1398 if (!Call->getArg(0)->getType()->isPipeType()) { 1399 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1400 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1401 return true; 1402 } 1403 1404 return false; 1405 } 1406 1407 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1408 // Performs semantic analysis for the to_global/local/private call. 1409 // \param S Reference to the semantic analyzer. 1410 // \param BuiltinID ID of the builtin function. 1411 // \param Call A pointer to the builtin call. 1412 // \return True if a semantic error has been found, false otherwise. 1413 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1414 CallExpr *Call) { 1415 if (checkArgCount(S, Call, 1)) 1416 return true; 1417 1418 auto RT = Call->getArg(0)->getType(); 1419 if (!RT->isPointerType() || RT->getPointeeType() 1420 .getAddressSpace() == LangAS::opencl_constant) { 1421 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1422 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1423 return true; 1424 } 1425 1426 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1427 S.Diag(Call->getArg(0)->getBeginLoc(), 1428 diag::warn_opencl_generic_address_space_arg) 1429 << Call->getDirectCallee()->getNameInfo().getAsString() 1430 << Call->getArg(0)->getSourceRange(); 1431 } 1432 1433 RT = RT->getPointeeType(); 1434 auto Qual = RT.getQualifiers(); 1435 switch (BuiltinID) { 1436 case Builtin::BIto_global: 1437 Qual.setAddressSpace(LangAS::opencl_global); 1438 break; 1439 case Builtin::BIto_local: 1440 Qual.setAddressSpace(LangAS::opencl_local); 1441 break; 1442 case Builtin::BIto_private: 1443 Qual.setAddressSpace(LangAS::opencl_private); 1444 break; 1445 default: 1446 llvm_unreachable("Invalid builtin function"); 1447 } 1448 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1449 RT.getUnqualifiedType(), Qual))); 1450 1451 return false; 1452 } 1453 1454 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1455 if (checkArgCount(S, TheCall, 1)) 1456 return ExprError(); 1457 1458 // Compute __builtin_launder's parameter type from the argument. 1459 // The parameter type is: 1460 // * The type of the argument if it's not an array or function type, 1461 // Otherwise, 1462 // * The decayed argument type. 1463 QualType ParamTy = [&]() { 1464 QualType ArgTy = TheCall->getArg(0)->getType(); 1465 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1466 return S.Context.getPointerType(Ty->getElementType()); 1467 if (ArgTy->isFunctionType()) { 1468 return S.Context.getPointerType(ArgTy); 1469 } 1470 return ArgTy; 1471 }(); 1472 1473 TheCall->setType(ParamTy); 1474 1475 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1476 if (!ParamTy->isPointerType()) 1477 return 0; 1478 if (ParamTy->isFunctionPointerType()) 1479 return 1; 1480 if (ParamTy->isVoidPointerType()) 1481 return 2; 1482 return llvm::Optional<unsigned>{}; 1483 }(); 1484 if (DiagSelect.hasValue()) { 1485 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1486 << DiagSelect.getValue() << TheCall->getSourceRange(); 1487 return ExprError(); 1488 } 1489 1490 // We either have an incomplete class type, or we have a class template 1491 // whose instantiation has not been forced. Example: 1492 // 1493 // template <class T> struct Foo { T value; }; 1494 // Foo<int> *p = nullptr; 1495 // auto *d = __builtin_launder(p); 1496 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1497 diag::err_incomplete_type)) 1498 return ExprError(); 1499 1500 assert(ParamTy->getPointeeType()->isObjectType() && 1501 "Unhandled non-object pointer case"); 1502 1503 InitializedEntity Entity = 1504 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1505 ExprResult Arg = 1506 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1507 if (Arg.isInvalid()) 1508 return ExprError(); 1509 TheCall->setArg(0, Arg.get()); 1510 1511 return TheCall; 1512 } 1513 1514 // Emit an error and return true if the current architecture is not in the list 1515 // of supported architectures. 1516 static bool 1517 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1518 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1519 llvm::Triple::ArchType CurArch = 1520 S.getASTContext().getTargetInfo().getTriple().getArch(); 1521 if (llvm::is_contained(SupportedArchs, CurArch)) 1522 return false; 1523 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1524 << TheCall->getSourceRange(); 1525 return true; 1526 } 1527 1528 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1529 SourceLocation CallSiteLoc); 1530 1531 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1532 CallExpr *TheCall) { 1533 switch (TI.getTriple().getArch()) { 1534 default: 1535 // Some builtins don't require additional checking, so just consider these 1536 // acceptable. 1537 return false; 1538 case llvm::Triple::arm: 1539 case llvm::Triple::armeb: 1540 case llvm::Triple::thumb: 1541 case llvm::Triple::thumbeb: 1542 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1543 case llvm::Triple::aarch64: 1544 case llvm::Triple::aarch64_32: 1545 case llvm::Triple::aarch64_be: 1546 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1547 case llvm::Triple::bpfeb: 1548 case llvm::Triple::bpfel: 1549 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1550 case llvm::Triple::hexagon: 1551 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1552 case llvm::Triple::mips: 1553 case llvm::Triple::mipsel: 1554 case llvm::Triple::mips64: 1555 case llvm::Triple::mips64el: 1556 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1557 case llvm::Triple::systemz: 1558 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1559 case llvm::Triple::x86: 1560 case llvm::Triple::x86_64: 1561 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1562 case llvm::Triple::ppc: 1563 case llvm::Triple::ppcle: 1564 case llvm::Triple::ppc64: 1565 case llvm::Triple::ppc64le: 1566 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1567 case llvm::Triple::amdgcn: 1568 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1569 case llvm::Triple::riscv32: 1570 case llvm::Triple::riscv64: 1571 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1572 } 1573 } 1574 1575 ExprResult 1576 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1577 CallExpr *TheCall) { 1578 ExprResult TheCallResult(TheCall); 1579 1580 // Find out if any arguments are required to be integer constant expressions. 1581 unsigned ICEArguments = 0; 1582 ASTContext::GetBuiltinTypeError Error; 1583 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1584 if (Error != ASTContext::GE_None) 1585 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1586 1587 // If any arguments are required to be ICE's, check and diagnose. 1588 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1589 // Skip arguments not required to be ICE's. 1590 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1591 1592 llvm::APSInt Result; 1593 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1594 return true; 1595 ICEArguments &= ~(1 << ArgNo); 1596 } 1597 1598 switch (BuiltinID) { 1599 case Builtin::BI__builtin___CFStringMakeConstantString: 1600 assert(TheCall->getNumArgs() == 1 && 1601 "Wrong # arguments to builtin CFStringMakeConstantString"); 1602 if (CheckObjCString(TheCall->getArg(0))) 1603 return ExprError(); 1604 break; 1605 case Builtin::BI__builtin_ms_va_start: 1606 case Builtin::BI__builtin_stdarg_start: 1607 case Builtin::BI__builtin_va_start: 1608 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1609 return ExprError(); 1610 break; 1611 case Builtin::BI__va_start: { 1612 switch (Context.getTargetInfo().getTriple().getArch()) { 1613 case llvm::Triple::aarch64: 1614 case llvm::Triple::arm: 1615 case llvm::Triple::thumb: 1616 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1617 return ExprError(); 1618 break; 1619 default: 1620 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1621 return ExprError(); 1622 break; 1623 } 1624 break; 1625 } 1626 1627 // The acquire, release, and no fence variants are ARM and AArch64 only. 1628 case Builtin::BI_interlockedbittestandset_acq: 1629 case Builtin::BI_interlockedbittestandset_rel: 1630 case Builtin::BI_interlockedbittestandset_nf: 1631 case Builtin::BI_interlockedbittestandreset_acq: 1632 case Builtin::BI_interlockedbittestandreset_rel: 1633 case Builtin::BI_interlockedbittestandreset_nf: 1634 if (CheckBuiltinTargetSupport( 1635 *this, BuiltinID, TheCall, 1636 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1637 return ExprError(); 1638 break; 1639 1640 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1641 case Builtin::BI_bittest64: 1642 case Builtin::BI_bittestandcomplement64: 1643 case Builtin::BI_bittestandreset64: 1644 case Builtin::BI_bittestandset64: 1645 case Builtin::BI_interlockedbittestandreset64: 1646 case Builtin::BI_interlockedbittestandset64: 1647 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1648 {llvm::Triple::x86_64, llvm::Triple::arm, 1649 llvm::Triple::thumb, llvm::Triple::aarch64})) 1650 return ExprError(); 1651 break; 1652 1653 case Builtin::BI__builtin_isgreater: 1654 case Builtin::BI__builtin_isgreaterequal: 1655 case Builtin::BI__builtin_isless: 1656 case Builtin::BI__builtin_islessequal: 1657 case Builtin::BI__builtin_islessgreater: 1658 case Builtin::BI__builtin_isunordered: 1659 if (SemaBuiltinUnorderedCompare(TheCall)) 1660 return ExprError(); 1661 break; 1662 case Builtin::BI__builtin_fpclassify: 1663 if (SemaBuiltinFPClassification(TheCall, 6)) 1664 return ExprError(); 1665 break; 1666 case Builtin::BI__builtin_isfinite: 1667 case Builtin::BI__builtin_isinf: 1668 case Builtin::BI__builtin_isinf_sign: 1669 case Builtin::BI__builtin_isnan: 1670 case Builtin::BI__builtin_isnormal: 1671 case Builtin::BI__builtin_signbit: 1672 case Builtin::BI__builtin_signbitf: 1673 case Builtin::BI__builtin_signbitl: 1674 if (SemaBuiltinFPClassification(TheCall, 1)) 1675 return ExprError(); 1676 break; 1677 case Builtin::BI__builtin_shufflevector: 1678 return SemaBuiltinShuffleVector(TheCall); 1679 // TheCall will be freed by the smart pointer here, but that's fine, since 1680 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1681 case Builtin::BI__builtin_prefetch: 1682 if (SemaBuiltinPrefetch(TheCall)) 1683 return ExprError(); 1684 break; 1685 case Builtin::BI__builtin_alloca_with_align: 1686 if (SemaBuiltinAllocaWithAlign(TheCall)) 1687 return ExprError(); 1688 LLVM_FALLTHROUGH; 1689 case Builtin::BI__builtin_alloca: 1690 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1691 << TheCall->getDirectCallee(); 1692 break; 1693 case Builtin::BI__arithmetic_fence: 1694 if (SemaBuiltinArithmeticFence(TheCall)) 1695 return ExprError(); 1696 break; 1697 case Builtin::BI__assume: 1698 case Builtin::BI__builtin_assume: 1699 if (SemaBuiltinAssume(TheCall)) 1700 return ExprError(); 1701 break; 1702 case Builtin::BI__builtin_assume_aligned: 1703 if (SemaBuiltinAssumeAligned(TheCall)) 1704 return ExprError(); 1705 break; 1706 case Builtin::BI__builtin_dynamic_object_size: 1707 case Builtin::BI__builtin_object_size: 1708 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1709 return ExprError(); 1710 break; 1711 case Builtin::BI__builtin_longjmp: 1712 if (SemaBuiltinLongjmp(TheCall)) 1713 return ExprError(); 1714 break; 1715 case Builtin::BI__builtin_setjmp: 1716 if (SemaBuiltinSetjmp(TheCall)) 1717 return ExprError(); 1718 break; 1719 case Builtin::BI__builtin_classify_type: 1720 if (checkArgCount(*this, TheCall, 1)) return true; 1721 TheCall->setType(Context.IntTy); 1722 break; 1723 case Builtin::BI__builtin_complex: 1724 if (SemaBuiltinComplex(TheCall)) 1725 return ExprError(); 1726 break; 1727 case Builtin::BI__builtin_constant_p: { 1728 if (checkArgCount(*this, TheCall, 1)) return true; 1729 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1730 if (Arg.isInvalid()) return true; 1731 TheCall->setArg(0, Arg.get()); 1732 TheCall->setType(Context.IntTy); 1733 break; 1734 } 1735 case Builtin::BI__builtin_launder: 1736 return SemaBuiltinLaunder(*this, TheCall); 1737 case Builtin::BI__sync_fetch_and_add: 1738 case Builtin::BI__sync_fetch_and_add_1: 1739 case Builtin::BI__sync_fetch_and_add_2: 1740 case Builtin::BI__sync_fetch_and_add_4: 1741 case Builtin::BI__sync_fetch_and_add_8: 1742 case Builtin::BI__sync_fetch_and_add_16: 1743 case Builtin::BI__sync_fetch_and_sub: 1744 case Builtin::BI__sync_fetch_and_sub_1: 1745 case Builtin::BI__sync_fetch_and_sub_2: 1746 case Builtin::BI__sync_fetch_and_sub_4: 1747 case Builtin::BI__sync_fetch_and_sub_8: 1748 case Builtin::BI__sync_fetch_and_sub_16: 1749 case Builtin::BI__sync_fetch_and_or: 1750 case Builtin::BI__sync_fetch_and_or_1: 1751 case Builtin::BI__sync_fetch_and_or_2: 1752 case Builtin::BI__sync_fetch_and_or_4: 1753 case Builtin::BI__sync_fetch_and_or_8: 1754 case Builtin::BI__sync_fetch_and_or_16: 1755 case Builtin::BI__sync_fetch_and_and: 1756 case Builtin::BI__sync_fetch_and_and_1: 1757 case Builtin::BI__sync_fetch_and_and_2: 1758 case Builtin::BI__sync_fetch_and_and_4: 1759 case Builtin::BI__sync_fetch_and_and_8: 1760 case Builtin::BI__sync_fetch_and_and_16: 1761 case Builtin::BI__sync_fetch_and_xor: 1762 case Builtin::BI__sync_fetch_and_xor_1: 1763 case Builtin::BI__sync_fetch_and_xor_2: 1764 case Builtin::BI__sync_fetch_and_xor_4: 1765 case Builtin::BI__sync_fetch_and_xor_8: 1766 case Builtin::BI__sync_fetch_and_xor_16: 1767 case Builtin::BI__sync_fetch_and_nand: 1768 case Builtin::BI__sync_fetch_and_nand_1: 1769 case Builtin::BI__sync_fetch_and_nand_2: 1770 case Builtin::BI__sync_fetch_and_nand_4: 1771 case Builtin::BI__sync_fetch_and_nand_8: 1772 case Builtin::BI__sync_fetch_and_nand_16: 1773 case Builtin::BI__sync_add_and_fetch: 1774 case Builtin::BI__sync_add_and_fetch_1: 1775 case Builtin::BI__sync_add_and_fetch_2: 1776 case Builtin::BI__sync_add_and_fetch_4: 1777 case Builtin::BI__sync_add_and_fetch_8: 1778 case Builtin::BI__sync_add_and_fetch_16: 1779 case Builtin::BI__sync_sub_and_fetch: 1780 case Builtin::BI__sync_sub_and_fetch_1: 1781 case Builtin::BI__sync_sub_and_fetch_2: 1782 case Builtin::BI__sync_sub_and_fetch_4: 1783 case Builtin::BI__sync_sub_and_fetch_8: 1784 case Builtin::BI__sync_sub_and_fetch_16: 1785 case Builtin::BI__sync_and_and_fetch: 1786 case Builtin::BI__sync_and_and_fetch_1: 1787 case Builtin::BI__sync_and_and_fetch_2: 1788 case Builtin::BI__sync_and_and_fetch_4: 1789 case Builtin::BI__sync_and_and_fetch_8: 1790 case Builtin::BI__sync_and_and_fetch_16: 1791 case Builtin::BI__sync_or_and_fetch: 1792 case Builtin::BI__sync_or_and_fetch_1: 1793 case Builtin::BI__sync_or_and_fetch_2: 1794 case Builtin::BI__sync_or_and_fetch_4: 1795 case Builtin::BI__sync_or_and_fetch_8: 1796 case Builtin::BI__sync_or_and_fetch_16: 1797 case Builtin::BI__sync_xor_and_fetch: 1798 case Builtin::BI__sync_xor_and_fetch_1: 1799 case Builtin::BI__sync_xor_and_fetch_2: 1800 case Builtin::BI__sync_xor_and_fetch_4: 1801 case Builtin::BI__sync_xor_and_fetch_8: 1802 case Builtin::BI__sync_xor_and_fetch_16: 1803 case Builtin::BI__sync_nand_and_fetch: 1804 case Builtin::BI__sync_nand_and_fetch_1: 1805 case Builtin::BI__sync_nand_and_fetch_2: 1806 case Builtin::BI__sync_nand_and_fetch_4: 1807 case Builtin::BI__sync_nand_and_fetch_8: 1808 case Builtin::BI__sync_nand_and_fetch_16: 1809 case Builtin::BI__sync_val_compare_and_swap: 1810 case Builtin::BI__sync_val_compare_and_swap_1: 1811 case Builtin::BI__sync_val_compare_and_swap_2: 1812 case Builtin::BI__sync_val_compare_and_swap_4: 1813 case Builtin::BI__sync_val_compare_and_swap_8: 1814 case Builtin::BI__sync_val_compare_and_swap_16: 1815 case Builtin::BI__sync_bool_compare_and_swap: 1816 case Builtin::BI__sync_bool_compare_and_swap_1: 1817 case Builtin::BI__sync_bool_compare_and_swap_2: 1818 case Builtin::BI__sync_bool_compare_and_swap_4: 1819 case Builtin::BI__sync_bool_compare_and_swap_8: 1820 case Builtin::BI__sync_bool_compare_and_swap_16: 1821 case Builtin::BI__sync_lock_test_and_set: 1822 case Builtin::BI__sync_lock_test_and_set_1: 1823 case Builtin::BI__sync_lock_test_and_set_2: 1824 case Builtin::BI__sync_lock_test_and_set_4: 1825 case Builtin::BI__sync_lock_test_and_set_8: 1826 case Builtin::BI__sync_lock_test_and_set_16: 1827 case Builtin::BI__sync_lock_release: 1828 case Builtin::BI__sync_lock_release_1: 1829 case Builtin::BI__sync_lock_release_2: 1830 case Builtin::BI__sync_lock_release_4: 1831 case Builtin::BI__sync_lock_release_8: 1832 case Builtin::BI__sync_lock_release_16: 1833 case Builtin::BI__sync_swap: 1834 case Builtin::BI__sync_swap_1: 1835 case Builtin::BI__sync_swap_2: 1836 case Builtin::BI__sync_swap_4: 1837 case Builtin::BI__sync_swap_8: 1838 case Builtin::BI__sync_swap_16: 1839 return SemaBuiltinAtomicOverloaded(TheCallResult); 1840 case Builtin::BI__sync_synchronize: 1841 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1842 << TheCall->getCallee()->getSourceRange(); 1843 break; 1844 case Builtin::BI__builtin_nontemporal_load: 1845 case Builtin::BI__builtin_nontemporal_store: 1846 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1847 case Builtin::BI__builtin_memcpy_inline: { 1848 clang::Expr *SizeOp = TheCall->getArg(2); 1849 // We warn about copying to or from `nullptr` pointers when `size` is 1850 // greater than 0. When `size` is value dependent we cannot evaluate its 1851 // value so we bail out. 1852 if (SizeOp->isValueDependent()) 1853 break; 1854 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) { 1855 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1856 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1857 } 1858 break; 1859 } 1860 #define BUILTIN(ID, TYPE, ATTRS) 1861 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1862 case Builtin::BI##ID: \ 1863 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1864 #include "clang/Basic/Builtins.def" 1865 case Builtin::BI__annotation: 1866 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1867 return ExprError(); 1868 break; 1869 case Builtin::BI__builtin_annotation: 1870 if (SemaBuiltinAnnotation(*this, TheCall)) 1871 return ExprError(); 1872 break; 1873 case Builtin::BI__builtin_addressof: 1874 if (SemaBuiltinAddressof(*this, TheCall)) 1875 return ExprError(); 1876 break; 1877 case Builtin::BI__builtin_is_aligned: 1878 case Builtin::BI__builtin_align_up: 1879 case Builtin::BI__builtin_align_down: 1880 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1881 return ExprError(); 1882 break; 1883 case Builtin::BI__builtin_add_overflow: 1884 case Builtin::BI__builtin_sub_overflow: 1885 case Builtin::BI__builtin_mul_overflow: 1886 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1887 return ExprError(); 1888 break; 1889 case Builtin::BI__builtin_operator_new: 1890 case Builtin::BI__builtin_operator_delete: { 1891 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1892 ExprResult Res = 1893 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1894 if (Res.isInvalid()) 1895 CorrectDelayedTyposInExpr(TheCallResult.get()); 1896 return Res; 1897 } 1898 case Builtin::BI__builtin_dump_struct: { 1899 // We first want to ensure we are called with 2 arguments 1900 if (checkArgCount(*this, TheCall, 2)) 1901 return ExprError(); 1902 // Ensure that the first argument is of type 'struct XX *' 1903 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1904 const QualType PtrArgType = PtrArg->getType(); 1905 if (!PtrArgType->isPointerType() || 1906 !PtrArgType->getPointeeType()->isRecordType()) { 1907 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1908 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1909 << "structure pointer"; 1910 return ExprError(); 1911 } 1912 1913 // Ensure that the second argument is of type 'FunctionType' 1914 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1915 const QualType FnPtrArgType = FnPtrArg->getType(); 1916 if (!FnPtrArgType->isPointerType()) { 1917 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1918 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1919 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1920 return ExprError(); 1921 } 1922 1923 const auto *FuncType = 1924 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1925 1926 if (!FuncType) { 1927 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1928 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1929 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1930 return ExprError(); 1931 } 1932 1933 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1934 if (!FT->getNumParams()) { 1935 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1936 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1937 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1938 return ExprError(); 1939 } 1940 QualType PT = FT->getParamType(0); 1941 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1942 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1943 !PT->getPointeeType().isConstQualified()) { 1944 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1945 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1946 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1947 return ExprError(); 1948 } 1949 } 1950 1951 TheCall->setType(Context.IntTy); 1952 break; 1953 } 1954 case Builtin::BI__builtin_expect_with_probability: { 1955 // We first want to ensure we are called with 3 arguments 1956 if (checkArgCount(*this, TheCall, 3)) 1957 return ExprError(); 1958 // then check probability is constant float in range [0.0, 1.0] 1959 const Expr *ProbArg = TheCall->getArg(2); 1960 SmallVector<PartialDiagnosticAt, 8> Notes; 1961 Expr::EvalResult Eval; 1962 Eval.Diag = &Notes; 1963 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1964 !Eval.Val.isFloat()) { 1965 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1966 << ProbArg->getSourceRange(); 1967 for (const PartialDiagnosticAt &PDiag : Notes) 1968 Diag(PDiag.first, PDiag.second); 1969 return ExprError(); 1970 } 1971 llvm::APFloat Probability = Eval.Val.getFloat(); 1972 bool LoseInfo = false; 1973 Probability.convert(llvm::APFloat::IEEEdouble(), 1974 llvm::RoundingMode::Dynamic, &LoseInfo); 1975 if (!(Probability >= llvm::APFloat(0.0) && 1976 Probability <= llvm::APFloat(1.0))) { 1977 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1978 << ProbArg->getSourceRange(); 1979 return ExprError(); 1980 } 1981 break; 1982 } 1983 case Builtin::BI__builtin_preserve_access_index: 1984 if (SemaBuiltinPreserveAI(*this, TheCall)) 1985 return ExprError(); 1986 break; 1987 case Builtin::BI__builtin_call_with_static_chain: 1988 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1989 return ExprError(); 1990 break; 1991 case Builtin::BI__exception_code: 1992 case Builtin::BI_exception_code: 1993 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1994 diag::err_seh___except_block)) 1995 return ExprError(); 1996 break; 1997 case Builtin::BI__exception_info: 1998 case Builtin::BI_exception_info: 1999 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 2000 diag::err_seh___except_filter)) 2001 return ExprError(); 2002 break; 2003 case Builtin::BI__GetExceptionInfo: 2004 if (checkArgCount(*this, TheCall, 1)) 2005 return ExprError(); 2006 2007 if (CheckCXXThrowOperand( 2008 TheCall->getBeginLoc(), 2009 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 2010 TheCall)) 2011 return ExprError(); 2012 2013 TheCall->setType(Context.VoidPtrTy); 2014 break; 2015 // OpenCL v2.0, s6.13.16 - Pipe functions 2016 case Builtin::BIread_pipe: 2017 case Builtin::BIwrite_pipe: 2018 // Since those two functions are declared with var args, we need a semantic 2019 // check for the argument. 2020 if (SemaBuiltinRWPipe(*this, TheCall)) 2021 return ExprError(); 2022 break; 2023 case Builtin::BIreserve_read_pipe: 2024 case Builtin::BIreserve_write_pipe: 2025 case Builtin::BIwork_group_reserve_read_pipe: 2026 case Builtin::BIwork_group_reserve_write_pipe: 2027 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 2028 return ExprError(); 2029 break; 2030 case Builtin::BIsub_group_reserve_read_pipe: 2031 case Builtin::BIsub_group_reserve_write_pipe: 2032 if (checkOpenCLSubgroupExt(*this, TheCall) || 2033 SemaBuiltinReserveRWPipe(*this, TheCall)) 2034 return ExprError(); 2035 break; 2036 case Builtin::BIcommit_read_pipe: 2037 case Builtin::BIcommit_write_pipe: 2038 case Builtin::BIwork_group_commit_read_pipe: 2039 case Builtin::BIwork_group_commit_write_pipe: 2040 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 2041 return ExprError(); 2042 break; 2043 case Builtin::BIsub_group_commit_read_pipe: 2044 case Builtin::BIsub_group_commit_write_pipe: 2045 if (checkOpenCLSubgroupExt(*this, TheCall) || 2046 SemaBuiltinCommitRWPipe(*this, TheCall)) 2047 return ExprError(); 2048 break; 2049 case Builtin::BIget_pipe_num_packets: 2050 case Builtin::BIget_pipe_max_packets: 2051 if (SemaBuiltinPipePackets(*this, TheCall)) 2052 return ExprError(); 2053 break; 2054 case Builtin::BIto_global: 2055 case Builtin::BIto_local: 2056 case Builtin::BIto_private: 2057 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 2058 return ExprError(); 2059 break; 2060 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 2061 case Builtin::BIenqueue_kernel: 2062 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 2063 return ExprError(); 2064 break; 2065 case Builtin::BIget_kernel_work_group_size: 2066 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 2067 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 2068 return ExprError(); 2069 break; 2070 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 2071 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 2072 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 2073 return ExprError(); 2074 break; 2075 case Builtin::BI__builtin_os_log_format: 2076 Cleanup.setExprNeedsCleanups(true); 2077 LLVM_FALLTHROUGH; 2078 case Builtin::BI__builtin_os_log_format_buffer_size: 2079 if (SemaBuiltinOSLogFormat(TheCall)) 2080 return ExprError(); 2081 break; 2082 case Builtin::BI__builtin_frame_address: 2083 case Builtin::BI__builtin_return_address: { 2084 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 2085 return ExprError(); 2086 2087 // -Wframe-address warning if non-zero passed to builtin 2088 // return/frame address. 2089 Expr::EvalResult Result; 2090 if (!TheCall->getArg(0)->isValueDependent() && 2091 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 2092 Result.Val.getInt() != 0) 2093 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 2094 << ((BuiltinID == Builtin::BI__builtin_return_address) 2095 ? "__builtin_return_address" 2096 : "__builtin_frame_address") 2097 << TheCall->getSourceRange(); 2098 break; 2099 } 2100 2101 // __builtin_elementwise_abs restricts the element type to signed integers or 2102 // floating point types only. 2103 case Builtin::BI__builtin_elementwise_abs: { 2104 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall)) 2105 return ExprError(); 2106 2107 QualType ArgTy = TheCall->getArg(0)->getType(); 2108 QualType EltTy = ArgTy; 2109 2110 if (auto *VecTy = EltTy->getAs<VectorType>()) 2111 EltTy = VecTy->getElementType(); 2112 if (EltTy->isUnsignedIntegerType()) { 2113 Diag(TheCall->getArg(0)->getBeginLoc(), 2114 diag::err_builtin_invalid_arg_type) 2115 << 1 << /* signed integer or float ty*/ 3 << ArgTy; 2116 return ExprError(); 2117 } 2118 break; 2119 } 2120 2121 // __builtin_elementwise_ceil restricts the element type to floating point 2122 // types only. 2123 case Builtin::BI__builtin_elementwise_ceil: { 2124 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall)) 2125 return ExprError(); 2126 2127 QualType ArgTy = TheCall->getArg(0)->getType(); 2128 QualType EltTy = ArgTy; 2129 2130 if (auto *VecTy = EltTy->getAs<VectorType>()) 2131 EltTy = VecTy->getElementType(); 2132 if (!EltTy->isFloatingType()) { 2133 Diag(TheCall->getArg(0)->getBeginLoc(), 2134 diag::err_builtin_invalid_arg_type) 2135 << 1 << /* float ty*/ 5 << ArgTy; 2136 2137 return ExprError(); 2138 } 2139 break; 2140 } 2141 2142 case Builtin::BI__builtin_elementwise_min: 2143 case Builtin::BI__builtin_elementwise_max: 2144 if (SemaBuiltinElementwiseMath(TheCall)) 2145 return ExprError(); 2146 break; 2147 case Builtin::BI__builtin_reduce_max: 2148 case Builtin::BI__builtin_reduce_min: 2149 if (SemaBuiltinReduceMath(TheCall)) 2150 return ExprError(); 2151 break; 2152 case Builtin::BI__builtin_matrix_transpose: 2153 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 2154 2155 case Builtin::BI__builtin_matrix_column_major_load: 2156 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 2157 2158 case Builtin::BI__builtin_matrix_column_major_store: 2159 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 2160 2161 case Builtin::BI__builtin_get_device_side_mangled_name: { 2162 auto Check = [](CallExpr *TheCall) { 2163 if (TheCall->getNumArgs() != 1) 2164 return false; 2165 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 2166 if (!DRE) 2167 return false; 2168 auto *D = DRE->getDecl(); 2169 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 2170 return false; 2171 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 2172 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 2173 }; 2174 if (!Check(TheCall)) { 2175 Diag(TheCall->getBeginLoc(), 2176 diag::err_hip_invalid_args_builtin_mangled_name); 2177 return ExprError(); 2178 } 2179 } 2180 } 2181 2182 // Since the target specific builtins for each arch overlap, only check those 2183 // of the arch we are compiling for. 2184 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 2185 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 2186 assert(Context.getAuxTargetInfo() && 2187 "Aux Target Builtin, but not an aux target?"); 2188 2189 if (CheckTSBuiltinFunctionCall( 2190 *Context.getAuxTargetInfo(), 2191 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2192 return ExprError(); 2193 } else { 2194 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2195 TheCall)) 2196 return ExprError(); 2197 } 2198 } 2199 2200 return TheCallResult; 2201 } 2202 2203 // Get the valid immediate range for the specified NEON type code. 2204 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2205 NeonTypeFlags Type(t); 2206 int IsQuad = ForceQuad ? true : Type.isQuad(); 2207 switch (Type.getEltType()) { 2208 case NeonTypeFlags::Int8: 2209 case NeonTypeFlags::Poly8: 2210 return shift ? 7 : (8 << IsQuad) - 1; 2211 case NeonTypeFlags::Int16: 2212 case NeonTypeFlags::Poly16: 2213 return shift ? 15 : (4 << IsQuad) - 1; 2214 case NeonTypeFlags::Int32: 2215 return shift ? 31 : (2 << IsQuad) - 1; 2216 case NeonTypeFlags::Int64: 2217 case NeonTypeFlags::Poly64: 2218 return shift ? 63 : (1 << IsQuad) - 1; 2219 case NeonTypeFlags::Poly128: 2220 return shift ? 127 : (1 << IsQuad) - 1; 2221 case NeonTypeFlags::Float16: 2222 assert(!shift && "cannot shift float types!"); 2223 return (4 << IsQuad) - 1; 2224 case NeonTypeFlags::Float32: 2225 assert(!shift && "cannot shift float types!"); 2226 return (2 << IsQuad) - 1; 2227 case NeonTypeFlags::Float64: 2228 assert(!shift && "cannot shift float types!"); 2229 return (1 << IsQuad) - 1; 2230 case NeonTypeFlags::BFloat16: 2231 assert(!shift && "cannot shift float types!"); 2232 return (4 << IsQuad) - 1; 2233 } 2234 llvm_unreachable("Invalid NeonTypeFlag!"); 2235 } 2236 2237 /// getNeonEltType - Return the QualType corresponding to the elements of 2238 /// the vector type specified by the NeonTypeFlags. This is used to check 2239 /// the pointer arguments for Neon load/store intrinsics. 2240 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2241 bool IsPolyUnsigned, bool IsInt64Long) { 2242 switch (Flags.getEltType()) { 2243 case NeonTypeFlags::Int8: 2244 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2245 case NeonTypeFlags::Int16: 2246 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2247 case NeonTypeFlags::Int32: 2248 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2249 case NeonTypeFlags::Int64: 2250 if (IsInt64Long) 2251 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2252 else 2253 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2254 : Context.LongLongTy; 2255 case NeonTypeFlags::Poly8: 2256 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2257 case NeonTypeFlags::Poly16: 2258 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2259 case NeonTypeFlags::Poly64: 2260 if (IsInt64Long) 2261 return Context.UnsignedLongTy; 2262 else 2263 return Context.UnsignedLongLongTy; 2264 case NeonTypeFlags::Poly128: 2265 break; 2266 case NeonTypeFlags::Float16: 2267 return Context.HalfTy; 2268 case NeonTypeFlags::Float32: 2269 return Context.FloatTy; 2270 case NeonTypeFlags::Float64: 2271 return Context.DoubleTy; 2272 case NeonTypeFlags::BFloat16: 2273 return Context.BFloat16Ty; 2274 } 2275 llvm_unreachable("Invalid NeonTypeFlag!"); 2276 } 2277 2278 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2279 // Range check SVE intrinsics that take immediate values. 2280 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2281 2282 switch (BuiltinID) { 2283 default: 2284 return false; 2285 #define GET_SVE_IMMEDIATE_CHECK 2286 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2287 #undef GET_SVE_IMMEDIATE_CHECK 2288 } 2289 2290 // Perform all the immediate checks for this builtin call. 2291 bool HasError = false; 2292 for (auto &I : ImmChecks) { 2293 int ArgNum, CheckTy, ElementSizeInBits; 2294 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2295 2296 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2297 2298 // Function that checks whether the operand (ArgNum) is an immediate 2299 // that is one of the predefined values. 2300 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2301 int ErrDiag) -> bool { 2302 // We can't check the value of a dependent argument. 2303 Expr *Arg = TheCall->getArg(ArgNum); 2304 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2305 return false; 2306 2307 // Check constant-ness first. 2308 llvm::APSInt Imm; 2309 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2310 return true; 2311 2312 if (!CheckImm(Imm.getSExtValue())) 2313 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2314 return false; 2315 }; 2316 2317 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2318 case SVETypeFlags::ImmCheck0_31: 2319 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2320 HasError = true; 2321 break; 2322 case SVETypeFlags::ImmCheck0_13: 2323 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2324 HasError = true; 2325 break; 2326 case SVETypeFlags::ImmCheck1_16: 2327 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2328 HasError = true; 2329 break; 2330 case SVETypeFlags::ImmCheck0_7: 2331 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2332 HasError = true; 2333 break; 2334 case SVETypeFlags::ImmCheckExtract: 2335 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2336 (2048 / ElementSizeInBits) - 1)) 2337 HasError = true; 2338 break; 2339 case SVETypeFlags::ImmCheckShiftRight: 2340 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2341 HasError = true; 2342 break; 2343 case SVETypeFlags::ImmCheckShiftRightNarrow: 2344 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2345 ElementSizeInBits / 2)) 2346 HasError = true; 2347 break; 2348 case SVETypeFlags::ImmCheckShiftLeft: 2349 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2350 ElementSizeInBits - 1)) 2351 HasError = true; 2352 break; 2353 case SVETypeFlags::ImmCheckLaneIndex: 2354 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2355 (128 / (1 * ElementSizeInBits)) - 1)) 2356 HasError = true; 2357 break; 2358 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2359 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2360 (128 / (2 * ElementSizeInBits)) - 1)) 2361 HasError = true; 2362 break; 2363 case SVETypeFlags::ImmCheckLaneIndexDot: 2364 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2365 (128 / (4 * ElementSizeInBits)) - 1)) 2366 HasError = true; 2367 break; 2368 case SVETypeFlags::ImmCheckComplexRot90_270: 2369 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2370 diag::err_rotation_argument_to_cadd)) 2371 HasError = true; 2372 break; 2373 case SVETypeFlags::ImmCheckComplexRotAll90: 2374 if (CheckImmediateInSet( 2375 [](int64_t V) { 2376 return V == 0 || V == 90 || V == 180 || V == 270; 2377 }, 2378 diag::err_rotation_argument_to_cmla)) 2379 HasError = true; 2380 break; 2381 case SVETypeFlags::ImmCheck0_1: 2382 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2383 HasError = true; 2384 break; 2385 case SVETypeFlags::ImmCheck0_2: 2386 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2387 HasError = true; 2388 break; 2389 case SVETypeFlags::ImmCheck0_3: 2390 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2391 HasError = true; 2392 break; 2393 } 2394 } 2395 2396 return HasError; 2397 } 2398 2399 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2400 unsigned BuiltinID, CallExpr *TheCall) { 2401 llvm::APSInt Result; 2402 uint64_t mask = 0; 2403 unsigned TV = 0; 2404 int PtrArgNum = -1; 2405 bool HasConstPtr = false; 2406 switch (BuiltinID) { 2407 #define GET_NEON_OVERLOAD_CHECK 2408 #include "clang/Basic/arm_neon.inc" 2409 #include "clang/Basic/arm_fp16.inc" 2410 #undef GET_NEON_OVERLOAD_CHECK 2411 } 2412 2413 // For NEON intrinsics which are overloaded on vector element type, validate 2414 // the immediate which specifies which variant to emit. 2415 unsigned ImmArg = TheCall->getNumArgs()-1; 2416 if (mask) { 2417 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2418 return true; 2419 2420 TV = Result.getLimitedValue(64); 2421 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2422 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2423 << TheCall->getArg(ImmArg)->getSourceRange(); 2424 } 2425 2426 if (PtrArgNum >= 0) { 2427 // Check that pointer arguments have the specified type. 2428 Expr *Arg = TheCall->getArg(PtrArgNum); 2429 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2430 Arg = ICE->getSubExpr(); 2431 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2432 QualType RHSTy = RHS.get()->getType(); 2433 2434 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2435 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2436 Arch == llvm::Triple::aarch64_32 || 2437 Arch == llvm::Triple::aarch64_be; 2438 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2439 QualType EltTy = 2440 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2441 if (HasConstPtr) 2442 EltTy = EltTy.withConst(); 2443 QualType LHSTy = Context.getPointerType(EltTy); 2444 AssignConvertType ConvTy; 2445 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2446 if (RHS.isInvalid()) 2447 return true; 2448 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2449 RHS.get(), AA_Assigning)) 2450 return true; 2451 } 2452 2453 // For NEON intrinsics which take an immediate value as part of the 2454 // instruction, range check them here. 2455 unsigned i = 0, l = 0, u = 0; 2456 switch (BuiltinID) { 2457 default: 2458 return false; 2459 #define GET_NEON_IMMEDIATE_CHECK 2460 #include "clang/Basic/arm_neon.inc" 2461 #include "clang/Basic/arm_fp16.inc" 2462 #undef GET_NEON_IMMEDIATE_CHECK 2463 } 2464 2465 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2466 } 2467 2468 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2469 switch (BuiltinID) { 2470 default: 2471 return false; 2472 #include "clang/Basic/arm_mve_builtin_sema.inc" 2473 } 2474 } 2475 2476 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2477 CallExpr *TheCall) { 2478 bool Err = false; 2479 switch (BuiltinID) { 2480 default: 2481 return false; 2482 #include "clang/Basic/arm_cde_builtin_sema.inc" 2483 } 2484 2485 if (Err) 2486 return true; 2487 2488 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2489 } 2490 2491 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2492 const Expr *CoprocArg, bool WantCDE) { 2493 if (isConstantEvaluated()) 2494 return false; 2495 2496 // We can't check the value of a dependent argument. 2497 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2498 return false; 2499 2500 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2501 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2502 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2503 2504 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2505 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2506 2507 if (IsCDECoproc != WantCDE) 2508 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2509 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2510 2511 return false; 2512 } 2513 2514 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2515 unsigned MaxWidth) { 2516 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2517 BuiltinID == ARM::BI__builtin_arm_ldaex || 2518 BuiltinID == ARM::BI__builtin_arm_strex || 2519 BuiltinID == ARM::BI__builtin_arm_stlex || 2520 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2521 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2522 BuiltinID == AArch64::BI__builtin_arm_strex || 2523 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2524 "unexpected ARM builtin"); 2525 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2526 BuiltinID == ARM::BI__builtin_arm_ldaex || 2527 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2528 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2529 2530 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2531 2532 // Ensure that we have the proper number of arguments. 2533 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2534 return true; 2535 2536 // Inspect the pointer argument of the atomic builtin. This should always be 2537 // a pointer type, whose element is an integral scalar or pointer type. 2538 // Because it is a pointer type, we don't have to worry about any implicit 2539 // casts here. 2540 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2541 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2542 if (PointerArgRes.isInvalid()) 2543 return true; 2544 PointerArg = PointerArgRes.get(); 2545 2546 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2547 if (!pointerType) { 2548 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2549 << PointerArg->getType() << PointerArg->getSourceRange(); 2550 return true; 2551 } 2552 2553 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2554 // task is to insert the appropriate casts into the AST. First work out just 2555 // what the appropriate type is. 2556 QualType ValType = pointerType->getPointeeType(); 2557 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2558 if (IsLdrex) 2559 AddrType.addConst(); 2560 2561 // Issue a warning if the cast is dodgy. 2562 CastKind CastNeeded = CK_NoOp; 2563 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2564 CastNeeded = CK_BitCast; 2565 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2566 << PointerArg->getType() << Context.getPointerType(AddrType) 2567 << AA_Passing << PointerArg->getSourceRange(); 2568 } 2569 2570 // Finally, do the cast and replace the argument with the corrected version. 2571 AddrType = Context.getPointerType(AddrType); 2572 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2573 if (PointerArgRes.isInvalid()) 2574 return true; 2575 PointerArg = PointerArgRes.get(); 2576 2577 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2578 2579 // In general, we allow ints, floats and pointers to be loaded and stored. 2580 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2581 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2582 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2583 << PointerArg->getType() << PointerArg->getSourceRange(); 2584 return true; 2585 } 2586 2587 // But ARM doesn't have instructions to deal with 128-bit versions. 2588 if (Context.getTypeSize(ValType) > MaxWidth) { 2589 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2590 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2591 << PointerArg->getType() << PointerArg->getSourceRange(); 2592 return true; 2593 } 2594 2595 switch (ValType.getObjCLifetime()) { 2596 case Qualifiers::OCL_None: 2597 case Qualifiers::OCL_ExplicitNone: 2598 // okay 2599 break; 2600 2601 case Qualifiers::OCL_Weak: 2602 case Qualifiers::OCL_Strong: 2603 case Qualifiers::OCL_Autoreleasing: 2604 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2605 << ValType << PointerArg->getSourceRange(); 2606 return true; 2607 } 2608 2609 if (IsLdrex) { 2610 TheCall->setType(ValType); 2611 return false; 2612 } 2613 2614 // Initialize the argument to be stored. 2615 ExprResult ValArg = TheCall->getArg(0); 2616 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2617 Context, ValType, /*consume*/ false); 2618 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2619 if (ValArg.isInvalid()) 2620 return true; 2621 TheCall->setArg(0, ValArg.get()); 2622 2623 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2624 // but the custom checker bypasses all default analysis. 2625 TheCall->setType(Context.IntTy); 2626 return false; 2627 } 2628 2629 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2630 CallExpr *TheCall) { 2631 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2632 BuiltinID == ARM::BI__builtin_arm_ldaex || 2633 BuiltinID == ARM::BI__builtin_arm_strex || 2634 BuiltinID == ARM::BI__builtin_arm_stlex) { 2635 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2636 } 2637 2638 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2639 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2640 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2641 } 2642 2643 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2644 BuiltinID == ARM::BI__builtin_arm_wsr64) 2645 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2646 2647 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2648 BuiltinID == ARM::BI__builtin_arm_rsrp || 2649 BuiltinID == ARM::BI__builtin_arm_wsr || 2650 BuiltinID == ARM::BI__builtin_arm_wsrp) 2651 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2652 2653 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2654 return true; 2655 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2656 return true; 2657 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2658 return true; 2659 2660 // For intrinsics which take an immediate value as part of the instruction, 2661 // range check them here. 2662 // FIXME: VFP Intrinsics should error if VFP not present. 2663 switch (BuiltinID) { 2664 default: return false; 2665 case ARM::BI__builtin_arm_ssat: 2666 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2667 case ARM::BI__builtin_arm_usat: 2668 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2669 case ARM::BI__builtin_arm_ssat16: 2670 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2671 case ARM::BI__builtin_arm_usat16: 2672 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2673 case ARM::BI__builtin_arm_vcvtr_f: 2674 case ARM::BI__builtin_arm_vcvtr_d: 2675 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2676 case ARM::BI__builtin_arm_dmb: 2677 case ARM::BI__builtin_arm_dsb: 2678 case ARM::BI__builtin_arm_isb: 2679 case ARM::BI__builtin_arm_dbg: 2680 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2681 case ARM::BI__builtin_arm_cdp: 2682 case ARM::BI__builtin_arm_cdp2: 2683 case ARM::BI__builtin_arm_mcr: 2684 case ARM::BI__builtin_arm_mcr2: 2685 case ARM::BI__builtin_arm_mrc: 2686 case ARM::BI__builtin_arm_mrc2: 2687 case ARM::BI__builtin_arm_mcrr: 2688 case ARM::BI__builtin_arm_mcrr2: 2689 case ARM::BI__builtin_arm_mrrc: 2690 case ARM::BI__builtin_arm_mrrc2: 2691 case ARM::BI__builtin_arm_ldc: 2692 case ARM::BI__builtin_arm_ldcl: 2693 case ARM::BI__builtin_arm_ldc2: 2694 case ARM::BI__builtin_arm_ldc2l: 2695 case ARM::BI__builtin_arm_stc: 2696 case ARM::BI__builtin_arm_stcl: 2697 case ARM::BI__builtin_arm_stc2: 2698 case ARM::BI__builtin_arm_stc2l: 2699 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2700 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2701 /*WantCDE*/ false); 2702 } 2703 } 2704 2705 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2706 unsigned BuiltinID, 2707 CallExpr *TheCall) { 2708 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2709 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2710 BuiltinID == AArch64::BI__builtin_arm_strex || 2711 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2712 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2713 } 2714 2715 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2716 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2717 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2718 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2719 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2720 } 2721 2722 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2723 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2724 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2725 2726 // Memory Tagging Extensions (MTE) Intrinsics 2727 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2728 BuiltinID == AArch64::BI__builtin_arm_addg || 2729 BuiltinID == AArch64::BI__builtin_arm_gmi || 2730 BuiltinID == AArch64::BI__builtin_arm_ldg || 2731 BuiltinID == AArch64::BI__builtin_arm_stg || 2732 BuiltinID == AArch64::BI__builtin_arm_subp) { 2733 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2734 } 2735 2736 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2737 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2738 BuiltinID == AArch64::BI__builtin_arm_wsr || 2739 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2740 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2741 2742 // Only check the valid encoding range. Any constant in this range would be 2743 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2744 // an exception for incorrect registers. This matches MSVC behavior. 2745 if (BuiltinID == AArch64::BI_ReadStatusReg || 2746 BuiltinID == AArch64::BI_WriteStatusReg) 2747 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2748 2749 if (BuiltinID == AArch64::BI__getReg) 2750 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2751 2752 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2753 return true; 2754 2755 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2756 return true; 2757 2758 // For intrinsics which take an immediate value as part of the instruction, 2759 // range check them here. 2760 unsigned i = 0, l = 0, u = 0; 2761 switch (BuiltinID) { 2762 default: return false; 2763 case AArch64::BI__builtin_arm_dmb: 2764 case AArch64::BI__builtin_arm_dsb: 2765 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2766 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2767 } 2768 2769 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2770 } 2771 2772 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2773 if (Arg->getType()->getAsPlaceholderType()) 2774 return false; 2775 2776 // The first argument needs to be a record field access. 2777 // If it is an array element access, we delay decision 2778 // to BPF backend to check whether the access is a 2779 // field access or not. 2780 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2781 isa<MemberExpr>(Arg->IgnoreParens()) || 2782 isa<ArraySubscriptExpr>(Arg->IgnoreParens())); 2783 } 2784 2785 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2786 QualType VectorTy, QualType EltTy) { 2787 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2788 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2789 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2790 << Call->getSourceRange() << VectorEltTy << EltTy; 2791 return false; 2792 } 2793 return true; 2794 } 2795 2796 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2797 QualType ArgType = Arg->getType(); 2798 if (ArgType->getAsPlaceholderType()) 2799 return false; 2800 2801 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2802 // format: 2803 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2804 // 2. <type> var; 2805 // __builtin_preserve_type_info(var, flag); 2806 if (!isa<DeclRefExpr>(Arg->IgnoreParens()) && 2807 !isa<UnaryOperator>(Arg->IgnoreParens())) 2808 return false; 2809 2810 // Typedef type. 2811 if (ArgType->getAs<TypedefType>()) 2812 return true; 2813 2814 // Record type or Enum type. 2815 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2816 if (const auto *RT = Ty->getAs<RecordType>()) { 2817 if (!RT->getDecl()->getDeclName().isEmpty()) 2818 return true; 2819 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2820 if (!ET->getDecl()->getDeclName().isEmpty()) 2821 return true; 2822 } 2823 2824 return false; 2825 } 2826 2827 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2828 QualType ArgType = Arg->getType(); 2829 if (ArgType->getAsPlaceholderType()) 2830 return false; 2831 2832 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2833 // format: 2834 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2835 // flag); 2836 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2837 if (!UO) 2838 return false; 2839 2840 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2841 if (!CE) 2842 return false; 2843 if (CE->getCastKind() != CK_IntegralToPointer && 2844 CE->getCastKind() != CK_NullToPointer) 2845 return false; 2846 2847 // The integer must be from an EnumConstantDecl. 2848 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2849 if (!DR) 2850 return false; 2851 2852 const EnumConstantDecl *Enumerator = 2853 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2854 if (!Enumerator) 2855 return false; 2856 2857 // The type must be EnumType. 2858 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2859 const auto *ET = Ty->getAs<EnumType>(); 2860 if (!ET) 2861 return false; 2862 2863 // The enum value must be supported. 2864 return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator); 2865 } 2866 2867 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2868 CallExpr *TheCall) { 2869 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2870 BuiltinID == BPF::BI__builtin_btf_type_id || 2871 BuiltinID == BPF::BI__builtin_preserve_type_info || 2872 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2873 "unexpected BPF builtin"); 2874 2875 if (checkArgCount(*this, TheCall, 2)) 2876 return true; 2877 2878 // The second argument needs to be a constant int 2879 Expr *Arg = TheCall->getArg(1); 2880 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2881 diag::kind kind; 2882 if (!Value) { 2883 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2884 kind = diag::err_preserve_field_info_not_const; 2885 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2886 kind = diag::err_btf_type_id_not_const; 2887 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2888 kind = diag::err_preserve_type_info_not_const; 2889 else 2890 kind = diag::err_preserve_enum_value_not_const; 2891 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2892 return true; 2893 } 2894 2895 // The first argument 2896 Arg = TheCall->getArg(0); 2897 bool InvalidArg = false; 2898 bool ReturnUnsignedInt = true; 2899 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2900 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2901 InvalidArg = true; 2902 kind = diag::err_preserve_field_info_not_field; 2903 } 2904 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2905 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2906 InvalidArg = true; 2907 kind = diag::err_preserve_type_info_invalid; 2908 } 2909 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2910 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2911 InvalidArg = true; 2912 kind = diag::err_preserve_enum_value_invalid; 2913 } 2914 ReturnUnsignedInt = false; 2915 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2916 ReturnUnsignedInt = false; 2917 } 2918 2919 if (InvalidArg) { 2920 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2921 return true; 2922 } 2923 2924 if (ReturnUnsignedInt) 2925 TheCall->setType(Context.UnsignedIntTy); 2926 else 2927 TheCall->setType(Context.UnsignedLongTy); 2928 return false; 2929 } 2930 2931 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2932 struct ArgInfo { 2933 uint8_t OpNum; 2934 bool IsSigned; 2935 uint8_t BitWidth; 2936 uint8_t Align; 2937 }; 2938 struct BuiltinInfo { 2939 unsigned BuiltinID; 2940 ArgInfo Infos[2]; 2941 }; 2942 2943 static BuiltinInfo Infos[] = { 2944 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2945 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2946 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2947 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2948 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2949 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2950 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2951 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2952 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2953 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2954 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2955 2956 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2957 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2958 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2959 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2960 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2961 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2962 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2963 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2964 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2965 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2966 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2967 2968 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2969 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2970 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2971 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2972 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2973 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2974 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2975 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2976 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2977 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2978 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2979 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2980 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2981 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2982 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2983 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2984 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2985 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2986 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2987 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2988 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2989 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2990 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2991 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2992 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2993 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2994 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2995 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2996 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2997 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2998 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2999 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 3000 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 3001 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 3002 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 3003 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 3004 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 3005 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 3006 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 3007 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 3008 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 3009 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 3010 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 3011 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 3012 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 3013 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 3014 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 3015 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 3016 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 3017 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 3018 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 3019 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 3020 {{ 1, false, 6, 0 }} }, 3021 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 3022 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 3023 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 3024 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 3025 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 3026 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 3027 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 3028 {{ 1, false, 5, 0 }} }, 3029 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 3030 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 3031 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 3032 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 3033 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 3034 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 3035 { 2, false, 5, 0 }} }, 3036 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 3037 { 2, false, 6, 0 }} }, 3038 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 3039 { 3, false, 5, 0 }} }, 3040 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 3041 { 3, false, 6, 0 }} }, 3042 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 3043 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 3044 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 3045 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 3046 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 3047 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 3048 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 3049 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 3050 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 3051 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 3052 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 3053 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 3054 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 3055 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 3056 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 3057 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 3058 {{ 2, false, 4, 0 }, 3059 { 3, false, 5, 0 }} }, 3060 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 3061 {{ 2, false, 4, 0 }, 3062 { 3, false, 5, 0 }} }, 3063 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 3064 {{ 2, false, 4, 0 }, 3065 { 3, false, 5, 0 }} }, 3066 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 3067 {{ 2, false, 4, 0 }, 3068 { 3, false, 5, 0 }} }, 3069 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 3070 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 3071 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 3072 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 3073 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 3074 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 3075 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 3076 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 3077 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 3078 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 3079 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 3080 { 2, false, 5, 0 }} }, 3081 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 3082 { 2, false, 6, 0 }} }, 3083 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 3084 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 3085 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 3086 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 3087 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 3088 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 3089 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 3090 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 3091 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 3092 {{ 1, false, 4, 0 }} }, 3093 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 3094 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 3095 {{ 1, false, 4, 0 }} }, 3096 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 3097 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 3098 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 3099 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 3100 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 3101 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 3102 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 3103 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 3104 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 3105 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 3106 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 3107 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 3108 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 3109 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 3110 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 3111 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 3112 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 3113 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 3114 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 3115 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 3116 {{ 3, false, 1, 0 }} }, 3117 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 3118 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 3119 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 3120 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 3121 {{ 3, false, 1, 0 }} }, 3122 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 3123 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 3124 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 3125 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 3126 {{ 3, false, 1, 0 }} }, 3127 }; 3128 3129 // Use a dynamically initialized static to sort the table exactly once on 3130 // first run. 3131 static const bool SortOnce = 3132 (llvm::sort(Infos, 3133 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 3134 return LHS.BuiltinID < RHS.BuiltinID; 3135 }), 3136 true); 3137 (void)SortOnce; 3138 3139 const BuiltinInfo *F = llvm::partition_point( 3140 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 3141 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 3142 return false; 3143 3144 bool Error = false; 3145 3146 for (const ArgInfo &A : F->Infos) { 3147 // Ignore empty ArgInfo elements. 3148 if (A.BitWidth == 0) 3149 continue; 3150 3151 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 3152 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 3153 if (!A.Align) { 3154 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3155 } else { 3156 unsigned M = 1 << A.Align; 3157 Min *= M; 3158 Max *= M; 3159 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3160 Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 3161 } 3162 } 3163 return Error; 3164 } 3165 3166 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 3167 CallExpr *TheCall) { 3168 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 3169 } 3170 3171 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 3172 unsigned BuiltinID, CallExpr *TheCall) { 3173 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 3174 CheckMipsBuiltinArgument(BuiltinID, TheCall); 3175 } 3176 3177 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 3178 CallExpr *TheCall) { 3179 3180 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 3181 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3182 if (!TI.hasFeature("dsp")) 3183 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3184 } 3185 3186 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3187 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3188 if (!TI.hasFeature("dspr2")) 3189 return Diag(TheCall->getBeginLoc(), 3190 diag::err_mips_builtin_requires_dspr2); 3191 } 3192 3193 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3194 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3195 if (!TI.hasFeature("msa")) 3196 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3197 } 3198 3199 return false; 3200 } 3201 3202 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3203 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3204 // ordering for DSP is unspecified. MSA is ordered by the data format used 3205 // by the underlying instruction i.e., df/m, df/n and then by size. 3206 // 3207 // FIXME: The size tests here should instead be tablegen'd along with the 3208 // definitions from include/clang/Basic/BuiltinsMips.def. 3209 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3210 // be too. 3211 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3212 unsigned i = 0, l = 0, u = 0, m = 0; 3213 switch (BuiltinID) { 3214 default: return false; 3215 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3216 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3217 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3218 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3219 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3220 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3221 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3222 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3223 // df/m field. 3224 // These intrinsics take an unsigned 3 bit immediate. 3225 case Mips::BI__builtin_msa_bclri_b: 3226 case Mips::BI__builtin_msa_bnegi_b: 3227 case Mips::BI__builtin_msa_bseti_b: 3228 case Mips::BI__builtin_msa_sat_s_b: 3229 case Mips::BI__builtin_msa_sat_u_b: 3230 case Mips::BI__builtin_msa_slli_b: 3231 case Mips::BI__builtin_msa_srai_b: 3232 case Mips::BI__builtin_msa_srari_b: 3233 case Mips::BI__builtin_msa_srli_b: 3234 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3235 case Mips::BI__builtin_msa_binsli_b: 3236 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3237 // These intrinsics take an unsigned 4 bit immediate. 3238 case Mips::BI__builtin_msa_bclri_h: 3239 case Mips::BI__builtin_msa_bnegi_h: 3240 case Mips::BI__builtin_msa_bseti_h: 3241 case Mips::BI__builtin_msa_sat_s_h: 3242 case Mips::BI__builtin_msa_sat_u_h: 3243 case Mips::BI__builtin_msa_slli_h: 3244 case Mips::BI__builtin_msa_srai_h: 3245 case Mips::BI__builtin_msa_srari_h: 3246 case Mips::BI__builtin_msa_srli_h: 3247 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3248 case Mips::BI__builtin_msa_binsli_h: 3249 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3250 // These intrinsics take an unsigned 5 bit immediate. 3251 // The first block of intrinsics actually have an unsigned 5 bit field, 3252 // not a df/n field. 3253 case Mips::BI__builtin_msa_cfcmsa: 3254 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3255 case Mips::BI__builtin_msa_clei_u_b: 3256 case Mips::BI__builtin_msa_clei_u_h: 3257 case Mips::BI__builtin_msa_clei_u_w: 3258 case Mips::BI__builtin_msa_clei_u_d: 3259 case Mips::BI__builtin_msa_clti_u_b: 3260 case Mips::BI__builtin_msa_clti_u_h: 3261 case Mips::BI__builtin_msa_clti_u_w: 3262 case Mips::BI__builtin_msa_clti_u_d: 3263 case Mips::BI__builtin_msa_maxi_u_b: 3264 case Mips::BI__builtin_msa_maxi_u_h: 3265 case Mips::BI__builtin_msa_maxi_u_w: 3266 case Mips::BI__builtin_msa_maxi_u_d: 3267 case Mips::BI__builtin_msa_mini_u_b: 3268 case Mips::BI__builtin_msa_mini_u_h: 3269 case Mips::BI__builtin_msa_mini_u_w: 3270 case Mips::BI__builtin_msa_mini_u_d: 3271 case Mips::BI__builtin_msa_addvi_b: 3272 case Mips::BI__builtin_msa_addvi_h: 3273 case Mips::BI__builtin_msa_addvi_w: 3274 case Mips::BI__builtin_msa_addvi_d: 3275 case Mips::BI__builtin_msa_bclri_w: 3276 case Mips::BI__builtin_msa_bnegi_w: 3277 case Mips::BI__builtin_msa_bseti_w: 3278 case Mips::BI__builtin_msa_sat_s_w: 3279 case Mips::BI__builtin_msa_sat_u_w: 3280 case Mips::BI__builtin_msa_slli_w: 3281 case Mips::BI__builtin_msa_srai_w: 3282 case Mips::BI__builtin_msa_srari_w: 3283 case Mips::BI__builtin_msa_srli_w: 3284 case Mips::BI__builtin_msa_srlri_w: 3285 case Mips::BI__builtin_msa_subvi_b: 3286 case Mips::BI__builtin_msa_subvi_h: 3287 case Mips::BI__builtin_msa_subvi_w: 3288 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3289 case Mips::BI__builtin_msa_binsli_w: 3290 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3291 // These intrinsics take an unsigned 6 bit immediate. 3292 case Mips::BI__builtin_msa_bclri_d: 3293 case Mips::BI__builtin_msa_bnegi_d: 3294 case Mips::BI__builtin_msa_bseti_d: 3295 case Mips::BI__builtin_msa_sat_s_d: 3296 case Mips::BI__builtin_msa_sat_u_d: 3297 case Mips::BI__builtin_msa_slli_d: 3298 case Mips::BI__builtin_msa_srai_d: 3299 case Mips::BI__builtin_msa_srari_d: 3300 case Mips::BI__builtin_msa_srli_d: 3301 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3302 case Mips::BI__builtin_msa_binsli_d: 3303 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3304 // These intrinsics take a signed 5 bit immediate. 3305 case Mips::BI__builtin_msa_ceqi_b: 3306 case Mips::BI__builtin_msa_ceqi_h: 3307 case Mips::BI__builtin_msa_ceqi_w: 3308 case Mips::BI__builtin_msa_ceqi_d: 3309 case Mips::BI__builtin_msa_clti_s_b: 3310 case Mips::BI__builtin_msa_clti_s_h: 3311 case Mips::BI__builtin_msa_clti_s_w: 3312 case Mips::BI__builtin_msa_clti_s_d: 3313 case Mips::BI__builtin_msa_clei_s_b: 3314 case Mips::BI__builtin_msa_clei_s_h: 3315 case Mips::BI__builtin_msa_clei_s_w: 3316 case Mips::BI__builtin_msa_clei_s_d: 3317 case Mips::BI__builtin_msa_maxi_s_b: 3318 case Mips::BI__builtin_msa_maxi_s_h: 3319 case Mips::BI__builtin_msa_maxi_s_w: 3320 case Mips::BI__builtin_msa_maxi_s_d: 3321 case Mips::BI__builtin_msa_mini_s_b: 3322 case Mips::BI__builtin_msa_mini_s_h: 3323 case Mips::BI__builtin_msa_mini_s_w: 3324 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3325 // These intrinsics take an unsigned 8 bit immediate. 3326 case Mips::BI__builtin_msa_andi_b: 3327 case Mips::BI__builtin_msa_nori_b: 3328 case Mips::BI__builtin_msa_ori_b: 3329 case Mips::BI__builtin_msa_shf_b: 3330 case Mips::BI__builtin_msa_shf_h: 3331 case Mips::BI__builtin_msa_shf_w: 3332 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3333 case Mips::BI__builtin_msa_bseli_b: 3334 case Mips::BI__builtin_msa_bmnzi_b: 3335 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3336 // df/n format 3337 // These intrinsics take an unsigned 4 bit immediate. 3338 case Mips::BI__builtin_msa_copy_s_b: 3339 case Mips::BI__builtin_msa_copy_u_b: 3340 case Mips::BI__builtin_msa_insve_b: 3341 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3342 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3343 // These intrinsics take an unsigned 3 bit immediate. 3344 case Mips::BI__builtin_msa_copy_s_h: 3345 case Mips::BI__builtin_msa_copy_u_h: 3346 case Mips::BI__builtin_msa_insve_h: 3347 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3348 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3349 // These intrinsics take an unsigned 2 bit immediate. 3350 case Mips::BI__builtin_msa_copy_s_w: 3351 case Mips::BI__builtin_msa_copy_u_w: 3352 case Mips::BI__builtin_msa_insve_w: 3353 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3354 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3355 // These intrinsics take an unsigned 1 bit immediate. 3356 case Mips::BI__builtin_msa_copy_s_d: 3357 case Mips::BI__builtin_msa_copy_u_d: 3358 case Mips::BI__builtin_msa_insve_d: 3359 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3360 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3361 // Memory offsets and immediate loads. 3362 // These intrinsics take a signed 10 bit immediate. 3363 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3364 case Mips::BI__builtin_msa_ldi_h: 3365 case Mips::BI__builtin_msa_ldi_w: 3366 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3367 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3368 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3369 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3370 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3371 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3372 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3373 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3374 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3375 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3376 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3377 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3378 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3379 } 3380 3381 if (!m) 3382 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3383 3384 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3385 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3386 } 3387 3388 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3389 /// advancing the pointer over the consumed characters. The decoded type is 3390 /// returned. If the decoded type represents a constant integer with a 3391 /// constraint on its value then Mask is set to that value. The type descriptors 3392 /// used in Str are specific to PPC MMA builtins and are documented in the file 3393 /// defining the PPC builtins. 3394 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3395 unsigned &Mask) { 3396 bool RequireICE = false; 3397 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3398 switch (*Str++) { 3399 case 'V': 3400 return Context.getVectorType(Context.UnsignedCharTy, 16, 3401 VectorType::VectorKind::AltiVecVector); 3402 case 'i': { 3403 char *End; 3404 unsigned size = strtoul(Str, &End, 10); 3405 assert(End != Str && "Missing constant parameter constraint"); 3406 Str = End; 3407 Mask = size; 3408 return Context.IntTy; 3409 } 3410 case 'W': { 3411 char *End; 3412 unsigned size = strtoul(Str, &End, 10); 3413 assert(End != Str && "Missing PowerPC MMA type size"); 3414 Str = End; 3415 QualType Type; 3416 switch (size) { 3417 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3418 case size: Type = Context.Id##Ty; break; 3419 #include "clang/Basic/PPCTypes.def" 3420 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3421 } 3422 bool CheckVectorArgs = false; 3423 while (!CheckVectorArgs) { 3424 switch (*Str++) { 3425 case '*': 3426 Type = Context.getPointerType(Type); 3427 break; 3428 case 'C': 3429 Type = Type.withConst(); 3430 break; 3431 default: 3432 CheckVectorArgs = true; 3433 --Str; 3434 break; 3435 } 3436 } 3437 return Type; 3438 } 3439 default: 3440 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3441 } 3442 } 3443 3444 static bool isPPC_64Builtin(unsigned BuiltinID) { 3445 // These builtins only work on PPC 64bit targets. 3446 switch (BuiltinID) { 3447 case PPC::BI__builtin_divde: 3448 case PPC::BI__builtin_divdeu: 3449 case PPC::BI__builtin_bpermd: 3450 case PPC::BI__builtin_ppc_ldarx: 3451 case PPC::BI__builtin_ppc_stdcx: 3452 case PPC::BI__builtin_ppc_tdw: 3453 case PPC::BI__builtin_ppc_trapd: 3454 case PPC::BI__builtin_ppc_cmpeqb: 3455 case PPC::BI__builtin_ppc_setb: 3456 case PPC::BI__builtin_ppc_mulhd: 3457 case PPC::BI__builtin_ppc_mulhdu: 3458 case PPC::BI__builtin_ppc_maddhd: 3459 case PPC::BI__builtin_ppc_maddhdu: 3460 case PPC::BI__builtin_ppc_maddld: 3461 case PPC::BI__builtin_ppc_load8r: 3462 case PPC::BI__builtin_ppc_store8r: 3463 case PPC::BI__builtin_ppc_insert_exp: 3464 case PPC::BI__builtin_ppc_extract_sig: 3465 case PPC::BI__builtin_ppc_addex: 3466 case PPC::BI__builtin_darn: 3467 case PPC::BI__builtin_darn_raw: 3468 case PPC::BI__builtin_ppc_compare_and_swaplp: 3469 case PPC::BI__builtin_ppc_fetch_and_addlp: 3470 case PPC::BI__builtin_ppc_fetch_and_andlp: 3471 case PPC::BI__builtin_ppc_fetch_and_orlp: 3472 case PPC::BI__builtin_ppc_fetch_and_swaplp: 3473 return true; 3474 } 3475 return false; 3476 } 3477 3478 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3479 StringRef FeatureToCheck, unsigned DiagID, 3480 StringRef DiagArg = "") { 3481 if (S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3482 return false; 3483 3484 if (DiagArg.empty()) 3485 S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3486 else 3487 S.Diag(TheCall->getBeginLoc(), DiagID) 3488 << DiagArg << TheCall->getSourceRange(); 3489 3490 return true; 3491 } 3492 3493 /// Returns true if the argument consists of one contiguous run of 1s with any 3494 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so 3495 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, 3496 /// since all 1s are not contiguous. 3497 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { 3498 llvm::APSInt Result; 3499 // We can't check the value of a dependent argument. 3500 Expr *Arg = TheCall->getArg(ArgNum); 3501 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3502 return false; 3503 3504 // Check constant-ness first. 3505 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3506 return true; 3507 3508 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. 3509 if (Result.isShiftedMask() || (~Result).isShiftedMask()) 3510 return false; 3511 3512 return Diag(TheCall->getBeginLoc(), 3513 diag::err_argument_not_contiguous_bit_field) 3514 << ArgNum << Arg->getSourceRange(); 3515 } 3516 3517 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3518 CallExpr *TheCall) { 3519 unsigned i = 0, l = 0, u = 0; 3520 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3521 llvm::APSInt Result; 3522 3523 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3524 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3525 << TheCall->getSourceRange(); 3526 3527 switch (BuiltinID) { 3528 default: return false; 3529 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3530 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3531 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3532 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3533 case PPC::BI__builtin_altivec_dss: 3534 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3535 case PPC::BI__builtin_tbegin: 3536 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3537 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3538 case PPC::BI__builtin_tabortwc: 3539 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3540 case PPC::BI__builtin_tabortwci: 3541 case PPC::BI__builtin_tabortdci: 3542 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3543 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3544 // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05', 3545 // __builtin_(un)pack_longdouble are available only if long double uses IBM 3546 // extended double representation. 3547 case PPC::BI__builtin_unpack_longdouble: 3548 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1)) 3549 return true; 3550 LLVM_FALLTHROUGH; 3551 case PPC::BI__builtin_pack_longdouble: 3552 if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble()) 3553 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi) 3554 << "ibmlongdouble"; 3555 return false; 3556 case PPC::BI__builtin_altivec_dst: 3557 case PPC::BI__builtin_altivec_dstt: 3558 case PPC::BI__builtin_altivec_dstst: 3559 case PPC::BI__builtin_altivec_dststt: 3560 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3561 case PPC::BI__builtin_vsx_xxpermdi: 3562 case PPC::BI__builtin_vsx_xxsldwi: 3563 return SemaBuiltinVSX(TheCall); 3564 case PPC::BI__builtin_divwe: 3565 case PPC::BI__builtin_divweu: 3566 case PPC::BI__builtin_divde: 3567 case PPC::BI__builtin_divdeu: 3568 return SemaFeatureCheck(*this, TheCall, "extdiv", 3569 diag::err_ppc_builtin_only_on_arch, "7"); 3570 case PPC::BI__builtin_bpermd: 3571 return SemaFeatureCheck(*this, TheCall, "bpermd", 3572 diag::err_ppc_builtin_only_on_arch, "7"); 3573 case PPC::BI__builtin_unpack_vector_int128: 3574 return SemaFeatureCheck(*this, TheCall, "vsx", 3575 diag::err_ppc_builtin_only_on_arch, "7") || 3576 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3577 case PPC::BI__builtin_pack_vector_int128: 3578 return SemaFeatureCheck(*this, TheCall, "vsx", 3579 diag::err_ppc_builtin_only_on_arch, "7"); 3580 case PPC::BI__builtin_altivec_vgnb: 3581 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3582 case PPC::BI__builtin_altivec_vec_replace_elt: 3583 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3584 QualType VecTy = TheCall->getArg(0)->getType(); 3585 QualType EltTy = TheCall->getArg(1)->getType(); 3586 unsigned Width = Context.getIntWidth(EltTy); 3587 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3588 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3589 } 3590 case PPC::BI__builtin_vsx_xxeval: 3591 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3592 case PPC::BI__builtin_altivec_vsldbi: 3593 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3594 case PPC::BI__builtin_altivec_vsrdbi: 3595 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3596 case PPC::BI__builtin_vsx_xxpermx: 3597 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3598 case PPC::BI__builtin_ppc_tw: 3599 case PPC::BI__builtin_ppc_tdw: 3600 return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31); 3601 case PPC::BI__builtin_ppc_cmpeqb: 3602 case PPC::BI__builtin_ppc_setb: 3603 case PPC::BI__builtin_ppc_maddhd: 3604 case PPC::BI__builtin_ppc_maddhdu: 3605 case PPC::BI__builtin_ppc_maddld: 3606 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3607 diag::err_ppc_builtin_only_on_arch, "9"); 3608 case PPC::BI__builtin_ppc_cmprb: 3609 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3610 diag::err_ppc_builtin_only_on_arch, "9") || 3611 SemaBuiltinConstantArgRange(TheCall, 0, 0, 1); 3612 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must 3613 // be a constant that represents a contiguous bit field. 3614 case PPC::BI__builtin_ppc_rlwnm: 3615 return SemaValueIsRunOfOnes(TheCall, 2); 3616 case PPC::BI__builtin_ppc_rlwimi: 3617 case PPC::BI__builtin_ppc_rldimi: 3618 return SemaBuiltinConstantArg(TheCall, 2, Result) || 3619 SemaValueIsRunOfOnes(TheCall, 3); 3620 case PPC::BI__builtin_ppc_extract_exp: 3621 case PPC::BI__builtin_ppc_extract_sig: 3622 case PPC::BI__builtin_ppc_insert_exp: 3623 return SemaFeatureCheck(*this, TheCall, "power9-vector", 3624 diag::err_ppc_builtin_only_on_arch, "9"); 3625 case PPC::BI__builtin_ppc_addex: { 3626 if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3627 diag::err_ppc_builtin_only_on_arch, "9") || 3628 SemaBuiltinConstantArgRange(TheCall, 2, 0, 3)) 3629 return true; 3630 // Output warning for reserved values 1 to 3. 3631 int ArgValue = 3632 TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue(); 3633 if (ArgValue != 0) 3634 Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour) 3635 << ArgValue; 3636 return false; 3637 } 3638 case PPC::BI__builtin_ppc_mtfsb0: 3639 case PPC::BI__builtin_ppc_mtfsb1: 3640 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 3641 case PPC::BI__builtin_ppc_mtfsf: 3642 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255); 3643 case PPC::BI__builtin_ppc_mtfsfi: 3644 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3645 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3646 case PPC::BI__builtin_ppc_alignx: 3647 return SemaBuiltinConstantArgPower2(TheCall, 0); 3648 case PPC::BI__builtin_ppc_rdlam: 3649 return SemaValueIsRunOfOnes(TheCall, 2); 3650 case PPC::BI__builtin_ppc_icbt: 3651 case PPC::BI__builtin_ppc_sthcx: 3652 case PPC::BI__builtin_ppc_stbcx: 3653 case PPC::BI__builtin_ppc_lharx: 3654 case PPC::BI__builtin_ppc_lbarx: 3655 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3656 diag::err_ppc_builtin_only_on_arch, "8"); 3657 case PPC::BI__builtin_vsx_ldrmb: 3658 case PPC::BI__builtin_vsx_strmb: 3659 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3660 diag::err_ppc_builtin_only_on_arch, "8") || 3661 SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 3662 case PPC::BI__builtin_altivec_vcntmbb: 3663 case PPC::BI__builtin_altivec_vcntmbh: 3664 case PPC::BI__builtin_altivec_vcntmbw: 3665 case PPC::BI__builtin_altivec_vcntmbd: 3666 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3667 case PPC::BI__builtin_darn: 3668 case PPC::BI__builtin_darn_raw: 3669 case PPC::BI__builtin_darn_32: 3670 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3671 diag::err_ppc_builtin_only_on_arch, "9"); 3672 case PPC::BI__builtin_vsx_xxgenpcvbm: 3673 case PPC::BI__builtin_vsx_xxgenpcvhm: 3674 case PPC::BI__builtin_vsx_xxgenpcvwm: 3675 case PPC::BI__builtin_vsx_xxgenpcvdm: 3676 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3677 case PPC::BI__builtin_ppc_compare_exp_uo: 3678 case PPC::BI__builtin_ppc_compare_exp_lt: 3679 case PPC::BI__builtin_ppc_compare_exp_gt: 3680 case PPC::BI__builtin_ppc_compare_exp_eq: 3681 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3682 diag::err_ppc_builtin_only_on_arch, "9") || 3683 SemaFeatureCheck(*this, TheCall, "vsx", 3684 diag::err_ppc_builtin_requires_vsx); 3685 case PPC::BI__builtin_ppc_test_data_class: { 3686 // Check if the first argument of the __builtin_ppc_test_data_class call is 3687 // valid. The argument must be either a 'float' or a 'double'. 3688 QualType ArgType = TheCall->getArg(0)->getType(); 3689 if (ArgType != QualType(Context.FloatTy) && 3690 ArgType != QualType(Context.DoubleTy)) 3691 return Diag(TheCall->getBeginLoc(), 3692 diag::err_ppc_invalid_test_data_class_type); 3693 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3694 diag::err_ppc_builtin_only_on_arch, "9") || 3695 SemaFeatureCheck(*this, TheCall, "vsx", 3696 diag::err_ppc_builtin_requires_vsx) || 3697 SemaBuiltinConstantArgRange(TheCall, 1, 0, 127); 3698 } 3699 case PPC::BI__builtin_ppc_load8r: 3700 case PPC::BI__builtin_ppc_store8r: 3701 return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions", 3702 diag::err_ppc_builtin_only_on_arch, "7"); 3703 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3704 case PPC::BI__builtin_##Name: \ 3705 return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types); 3706 #include "clang/Basic/BuiltinsPPC.def" 3707 } 3708 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3709 } 3710 3711 // Check if the given type is a non-pointer PPC MMA type. This function is used 3712 // in Sema to prevent invalid uses of restricted PPC MMA types. 3713 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3714 if (Type->isPointerType() || Type->isArrayType()) 3715 return false; 3716 3717 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3718 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3719 if (false 3720 #include "clang/Basic/PPCTypes.def" 3721 ) { 3722 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3723 return true; 3724 } 3725 return false; 3726 } 3727 3728 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3729 CallExpr *TheCall) { 3730 // position of memory order and scope arguments in the builtin 3731 unsigned OrderIndex, ScopeIndex; 3732 switch (BuiltinID) { 3733 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3734 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3735 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3736 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3737 OrderIndex = 2; 3738 ScopeIndex = 3; 3739 break; 3740 case AMDGPU::BI__builtin_amdgcn_fence: 3741 OrderIndex = 0; 3742 ScopeIndex = 1; 3743 break; 3744 default: 3745 return false; 3746 } 3747 3748 ExprResult Arg = TheCall->getArg(OrderIndex); 3749 auto ArgExpr = Arg.get(); 3750 Expr::EvalResult ArgResult; 3751 3752 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3753 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3754 << ArgExpr->getType(); 3755 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3756 3757 // Check validity of memory ordering as per C11 / C++11's memody model. 3758 // Only fence needs check. Atomic dec/inc allow all memory orders. 3759 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3760 return Diag(ArgExpr->getBeginLoc(), 3761 diag::warn_atomic_op_has_invalid_memory_order) 3762 << ArgExpr->getSourceRange(); 3763 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3764 case llvm::AtomicOrderingCABI::relaxed: 3765 case llvm::AtomicOrderingCABI::consume: 3766 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3767 return Diag(ArgExpr->getBeginLoc(), 3768 diag::warn_atomic_op_has_invalid_memory_order) 3769 << ArgExpr->getSourceRange(); 3770 break; 3771 case llvm::AtomicOrderingCABI::acquire: 3772 case llvm::AtomicOrderingCABI::release: 3773 case llvm::AtomicOrderingCABI::acq_rel: 3774 case llvm::AtomicOrderingCABI::seq_cst: 3775 break; 3776 } 3777 3778 Arg = TheCall->getArg(ScopeIndex); 3779 ArgExpr = Arg.get(); 3780 Expr::EvalResult ArgResult1; 3781 // Check that sync scope is a constant literal 3782 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3783 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3784 << ArgExpr->getType(); 3785 3786 return false; 3787 } 3788 3789 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 3790 llvm::APSInt Result; 3791 3792 // We can't check the value of a dependent argument. 3793 Expr *Arg = TheCall->getArg(ArgNum); 3794 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3795 return false; 3796 3797 // Check constant-ness first. 3798 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3799 return true; 3800 3801 int64_t Val = Result.getSExtValue(); 3802 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 3803 return false; 3804 3805 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 3806 << Arg->getSourceRange(); 3807 } 3808 3809 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3810 unsigned BuiltinID, 3811 CallExpr *TheCall) { 3812 // CodeGenFunction can also detect this, but this gives a better error 3813 // message. 3814 bool FeatureMissing = false; 3815 SmallVector<StringRef> ReqFeatures; 3816 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3817 Features.split(ReqFeatures, ','); 3818 3819 // Check if each required feature is included 3820 for (StringRef F : ReqFeatures) { 3821 if (TI.hasFeature(F)) 3822 continue; 3823 3824 // If the feature is 64bit, alter the string so it will print better in 3825 // the diagnostic. 3826 if (F == "64bit") 3827 F = "RV64"; 3828 3829 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 3830 F.consume_front("experimental-"); 3831 std::string FeatureStr = F.str(); 3832 FeatureStr[0] = std::toupper(FeatureStr[0]); 3833 3834 // Error message 3835 FeatureMissing = true; 3836 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 3837 << TheCall->getSourceRange() << StringRef(FeatureStr); 3838 } 3839 3840 if (FeatureMissing) 3841 return true; 3842 3843 switch (BuiltinID) { 3844 case RISCVVector::BI__builtin_rvv_vsetvli: 3845 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 3846 CheckRISCVLMUL(TheCall, 2); 3847 case RISCVVector::BI__builtin_rvv_vsetvlimax: 3848 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 3849 CheckRISCVLMUL(TheCall, 1); 3850 } 3851 3852 return false; 3853 } 3854 3855 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3856 CallExpr *TheCall) { 3857 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3858 Expr *Arg = TheCall->getArg(0); 3859 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3860 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3861 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3862 << Arg->getSourceRange(); 3863 } 3864 3865 // For intrinsics which take an immediate value as part of the instruction, 3866 // range check them here. 3867 unsigned i = 0, l = 0, u = 0; 3868 switch (BuiltinID) { 3869 default: return false; 3870 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3871 case SystemZ::BI__builtin_s390_verimb: 3872 case SystemZ::BI__builtin_s390_verimh: 3873 case SystemZ::BI__builtin_s390_verimf: 3874 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3875 case SystemZ::BI__builtin_s390_vfaeb: 3876 case SystemZ::BI__builtin_s390_vfaeh: 3877 case SystemZ::BI__builtin_s390_vfaef: 3878 case SystemZ::BI__builtin_s390_vfaebs: 3879 case SystemZ::BI__builtin_s390_vfaehs: 3880 case SystemZ::BI__builtin_s390_vfaefs: 3881 case SystemZ::BI__builtin_s390_vfaezb: 3882 case SystemZ::BI__builtin_s390_vfaezh: 3883 case SystemZ::BI__builtin_s390_vfaezf: 3884 case SystemZ::BI__builtin_s390_vfaezbs: 3885 case SystemZ::BI__builtin_s390_vfaezhs: 3886 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3887 case SystemZ::BI__builtin_s390_vfisb: 3888 case SystemZ::BI__builtin_s390_vfidb: 3889 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3890 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3891 case SystemZ::BI__builtin_s390_vftcisb: 3892 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3893 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3894 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3895 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3896 case SystemZ::BI__builtin_s390_vstrcb: 3897 case SystemZ::BI__builtin_s390_vstrch: 3898 case SystemZ::BI__builtin_s390_vstrcf: 3899 case SystemZ::BI__builtin_s390_vstrczb: 3900 case SystemZ::BI__builtin_s390_vstrczh: 3901 case SystemZ::BI__builtin_s390_vstrczf: 3902 case SystemZ::BI__builtin_s390_vstrcbs: 3903 case SystemZ::BI__builtin_s390_vstrchs: 3904 case SystemZ::BI__builtin_s390_vstrcfs: 3905 case SystemZ::BI__builtin_s390_vstrczbs: 3906 case SystemZ::BI__builtin_s390_vstrczhs: 3907 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3908 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3909 case SystemZ::BI__builtin_s390_vfminsb: 3910 case SystemZ::BI__builtin_s390_vfmaxsb: 3911 case SystemZ::BI__builtin_s390_vfmindb: 3912 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3913 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3914 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3915 case SystemZ::BI__builtin_s390_vclfnhs: 3916 case SystemZ::BI__builtin_s390_vclfnls: 3917 case SystemZ::BI__builtin_s390_vcfn: 3918 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break; 3919 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break; 3920 } 3921 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3922 } 3923 3924 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3925 /// This checks that the target supports __builtin_cpu_supports and 3926 /// that the string argument is constant and valid. 3927 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3928 CallExpr *TheCall) { 3929 Expr *Arg = TheCall->getArg(0); 3930 3931 // Check if the argument is a string literal. 3932 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3933 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3934 << Arg->getSourceRange(); 3935 3936 // Check the contents of the string. 3937 StringRef Feature = 3938 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3939 if (!TI.validateCpuSupports(Feature)) 3940 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3941 << Arg->getSourceRange(); 3942 return false; 3943 } 3944 3945 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3946 /// This checks that the target supports __builtin_cpu_is and 3947 /// that the string argument is constant and valid. 3948 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3949 Expr *Arg = TheCall->getArg(0); 3950 3951 // Check if the argument is a string literal. 3952 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3953 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3954 << Arg->getSourceRange(); 3955 3956 // Check the contents of the string. 3957 StringRef Feature = 3958 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3959 if (!TI.validateCpuIs(Feature)) 3960 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3961 << Arg->getSourceRange(); 3962 return false; 3963 } 3964 3965 // Check if the rounding mode is legal. 3966 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3967 // Indicates if this instruction has rounding control or just SAE. 3968 bool HasRC = false; 3969 3970 unsigned ArgNum = 0; 3971 switch (BuiltinID) { 3972 default: 3973 return false; 3974 case X86::BI__builtin_ia32_vcvttsd2si32: 3975 case X86::BI__builtin_ia32_vcvttsd2si64: 3976 case X86::BI__builtin_ia32_vcvttsd2usi32: 3977 case X86::BI__builtin_ia32_vcvttsd2usi64: 3978 case X86::BI__builtin_ia32_vcvttss2si32: 3979 case X86::BI__builtin_ia32_vcvttss2si64: 3980 case X86::BI__builtin_ia32_vcvttss2usi32: 3981 case X86::BI__builtin_ia32_vcvttss2usi64: 3982 case X86::BI__builtin_ia32_vcvttsh2si32: 3983 case X86::BI__builtin_ia32_vcvttsh2si64: 3984 case X86::BI__builtin_ia32_vcvttsh2usi32: 3985 case X86::BI__builtin_ia32_vcvttsh2usi64: 3986 ArgNum = 1; 3987 break; 3988 case X86::BI__builtin_ia32_maxpd512: 3989 case X86::BI__builtin_ia32_maxps512: 3990 case X86::BI__builtin_ia32_minpd512: 3991 case X86::BI__builtin_ia32_minps512: 3992 case X86::BI__builtin_ia32_maxph512: 3993 case X86::BI__builtin_ia32_minph512: 3994 ArgNum = 2; 3995 break; 3996 case X86::BI__builtin_ia32_vcvtph2pd512_mask: 3997 case X86::BI__builtin_ia32_vcvtph2psx512_mask: 3998 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3999 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 4000 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 4001 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 4002 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 4003 case X86::BI__builtin_ia32_cvttps2dq512_mask: 4004 case X86::BI__builtin_ia32_cvttps2qq512_mask: 4005 case X86::BI__builtin_ia32_cvttps2udq512_mask: 4006 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 4007 case X86::BI__builtin_ia32_vcvttph2w512_mask: 4008 case X86::BI__builtin_ia32_vcvttph2uw512_mask: 4009 case X86::BI__builtin_ia32_vcvttph2dq512_mask: 4010 case X86::BI__builtin_ia32_vcvttph2udq512_mask: 4011 case X86::BI__builtin_ia32_vcvttph2qq512_mask: 4012 case X86::BI__builtin_ia32_vcvttph2uqq512_mask: 4013 case X86::BI__builtin_ia32_exp2pd_mask: 4014 case X86::BI__builtin_ia32_exp2ps_mask: 4015 case X86::BI__builtin_ia32_getexppd512_mask: 4016 case X86::BI__builtin_ia32_getexpps512_mask: 4017 case X86::BI__builtin_ia32_getexpph512_mask: 4018 case X86::BI__builtin_ia32_rcp28pd_mask: 4019 case X86::BI__builtin_ia32_rcp28ps_mask: 4020 case X86::BI__builtin_ia32_rsqrt28pd_mask: 4021 case X86::BI__builtin_ia32_rsqrt28ps_mask: 4022 case X86::BI__builtin_ia32_vcomisd: 4023 case X86::BI__builtin_ia32_vcomiss: 4024 case X86::BI__builtin_ia32_vcomish: 4025 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 4026 ArgNum = 3; 4027 break; 4028 case X86::BI__builtin_ia32_cmppd512_mask: 4029 case X86::BI__builtin_ia32_cmpps512_mask: 4030 case X86::BI__builtin_ia32_cmpsd_mask: 4031 case X86::BI__builtin_ia32_cmpss_mask: 4032 case X86::BI__builtin_ia32_cmpsh_mask: 4033 case X86::BI__builtin_ia32_vcvtsh2sd_round_mask: 4034 case X86::BI__builtin_ia32_vcvtsh2ss_round_mask: 4035 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 4036 case X86::BI__builtin_ia32_getexpsd128_round_mask: 4037 case X86::BI__builtin_ia32_getexpss128_round_mask: 4038 case X86::BI__builtin_ia32_getexpsh128_round_mask: 4039 case X86::BI__builtin_ia32_getmantpd512_mask: 4040 case X86::BI__builtin_ia32_getmantps512_mask: 4041 case X86::BI__builtin_ia32_getmantph512_mask: 4042 case X86::BI__builtin_ia32_maxsd_round_mask: 4043 case X86::BI__builtin_ia32_maxss_round_mask: 4044 case X86::BI__builtin_ia32_maxsh_round_mask: 4045 case X86::BI__builtin_ia32_minsd_round_mask: 4046 case X86::BI__builtin_ia32_minss_round_mask: 4047 case X86::BI__builtin_ia32_minsh_round_mask: 4048 case X86::BI__builtin_ia32_rcp28sd_round_mask: 4049 case X86::BI__builtin_ia32_rcp28ss_round_mask: 4050 case X86::BI__builtin_ia32_reducepd512_mask: 4051 case X86::BI__builtin_ia32_reduceps512_mask: 4052 case X86::BI__builtin_ia32_reduceph512_mask: 4053 case X86::BI__builtin_ia32_rndscalepd_mask: 4054 case X86::BI__builtin_ia32_rndscaleps_mask: 4055 case X86::BI__builtin_ia32_rndscaleph_mask: 4056 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 4057 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 4058 ArgNum = 4; 4059 break; 4060 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4061 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4062 case X86::BI__builtin_ia32_fixupimmps512_mask: 4063 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4064 case X86::BI__builtin_ia32_fixupimmsd_mask: 4065 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4066 case X86::BI__builtin_ia32_fixupimmss_mask: 4067 case X86::BI__builtin_ia32_fixupimmss_maskz: 4068 case X86::BI__builtin_ia32_getmantsd_round_mask: 4069 case X86::BI__builtin_ia32_getmantss_round_mask: 4070 case X86::BI__builtin_ia32_getmantsh_round_mask: 4071 case X86::BI__builtin_ia32_rangepd512_mask: 4072 case X86::BI__builtin_ia32_rangeps512_mask: 4073 case X86::BI__builtin_ia32_rangesd128_round_mask: 4074 case X86::BI__builtin_ia32_rangess128_round_mask: 4075 case X86::BI__builtin_ia32_reducesd_mask: 4076 case X86::BI__builtin_ia32_reducess_mask: 4077 case X86::BI__builtin_ia32_reducesh_mask: 4078 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4079 case X86::BI__builtin_ia32_rndscaless_round_mask: 4080 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4081 ArgNum = 5; 4082 break; 4083 case X86::BI__builtin_ia32_vcvtsd2si64: 4084 case X86::BI__builtin_ia32_vcvtsd2si32: 4085 case X86::BI__builtin_ia32_vcvtsd2usi32: 4086 case X86::BI__builtin_ia32_vcvtsd2usi64: 4087 case X86::BI__builtin_ia32_vcvtss2si32: 4088 case X86::BI__builtin_ia32_vcvtss2si64: 4089 case X86::BI__builtin_ia32_vcvtss2usi32: 4090 case X86::BI__builtin_ia32_vcvtss2usi64: 4091 case X86::BI__builtin_ia32_vcvtsh2si32: 4092 case X86::BI__builtin_ia32_vcvtsh2si64: 4093 case X86::BI__builtin_ia32_vcvtsh2usi32: 4094 case X86::BI__builtin_ia32_vcvtsh2usi64: 4095 case X86::BI__builtin_ia32_sqrtpd512: 4096 case X86::BI__builtin_ia32_sqrtps512: 4097 case X86::BI__builtin_ia32_sqrtph512: 4098 ArgNum = 1; 4099 HasRC = true; 4100 break; 4101 case X86::BI__builtin_ia32_addph512: 4102 case X86::BI__builtin_ia32_divph512: 4103 case X86::BI__builtin_ia32_mulph512: 4104 case X86::BI__builtin_ia32_subph512: 4105 case X86::BI__builtin_ia32_addpd512: 4106 case X86::BI__builtin_ia32_addps512: 4107 case X86::BI__builtin_ia32_divpd512: 4108 case X86::BI__builtin_ia32_divps512: 4109 case X86::BI__builtin_ia32_mulpd512: 4110 case X86::BI__builtin_ia32_mulps512: 4111 case X86::BI__builtin_ia32_subpd512: 4112 case X86::BI__builtin_ia32_subps512: 4113 case X86::BI__builtin_ia32_cvtsi2sd64: 4114 case X86::BI__builtin_ia32_cvtsi2ss32: 4115 case X86::BI__builtin_ia32_cvtsi2ss64: 4116 case X86::BI__builtin_ia32_cvtusi2sd64: 4117 case X86::BI__builtin_ia32_cvtusi2ss32: 4118 case X86::BI__builtin_ia32_cvtusi2ss64: 4119 case X86::BI__builtin_ia32_vcvtusi2sh: 4120 case X86::BI__builtin_ia32_vcvtusi642sh: 4121 case X86::BI__builtin_ia32_vcvtsi2sh: 4122 case X86::BI__builtin_ia32_vcvtsi642sh: 4123 ArgNum = 2; 4124 HasRC = true; 4125 break; 4126 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 4127 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 4128 case X86::BI__builtin_ia32_vcvtpd2ph512_mask: 4129 case X86::BI__builtin_ia32_vcvtps2phx512_mask: 4130 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 4131 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 4132 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 4133 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 4134 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 4135 case X86::BI__builtin_ia32_cvtps2dq512_mask: 4136 case X86::BI__builtin_ia32_cvtps2qq512_mask: 4137 case X86::BI__builtin_ia32_cvtps2udq512_mask: 4138 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 4139 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 4140 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 4141 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 4142 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 4143 case X86::BI__builtin_ia32_vcvtdq2ph512_mask: 4144 case X86::BI__builtin_ia32_vcvtudq2ph512_mask: 4145 case X86::BI__builtin_ia32_vcvtw2ph512_mask: 4146 case X86::BI__builtin_ia32_vcvtuw2ph512_mask: 4147 case X86::BI__builtin_ia32_vcvtph2w512_mask: 4148 case X86::BI__builtin_ia32_vcvtph2uw512_mask: 4149 case X86::BI__builtin_ia32_vcvtph2dq512_mask: 4150 case X86::BI__builtin_ia32_vcvtph2udq512_mask: 4151 case X86::BI__builtin_ia32_vcvtph2qq512_mask: 4152 case X86::BI__builtin_ia32_vcvtph2uqq512_mask: 4153 case X86::BI__builtin_ia32_vcvtqq2ph512_mask: 4154 case X86::BI__builtin_ia32_vcvtuqq2ph512_mask: 4155 ArgNum = 3; 4156 HasRC = true; 4157 break; 4158 case X86::BI__builtin_ia32_addsh_round_mask: 4159 case X86::BI__builtin_ia32_addss_round_mask: 4160 case X86::BI__builtin_ia32_addsd_round_mask: 4161 case X86::BI__builtin_ia32_divsh_round_mask: 4162 case X86::BI__builtin_ia32_divss_round_mask: 4163 case X86::BI__builtin_ia32_divsd_round_mask: 4164 case X86::BI__builtin_ia32_mulsh_round_mask: 4165 case X86::BI__builtin_ia32_mulss_round_mask: 4166 case X86::BI__builtin_ia32_mulsd_round_mask: 4167 case X86::BI__builtin_ia32_subsh_round_mask: 4168 case X86::BI__builtin_ia32_subss_round_mask: 4169 case X86::BI__builtin_ia32_subsd_round_mask: 4170 case X86::BI__builtin_ia32_scalefph512_mask: 4171 case X86::BI__builtin_ia32_scalefpd512_mask: 4172 case X86::BI__builtin_ia32_scalefps512_mask: 4173 case X86::BI__builtin_ia32_scalefsd_round_mask: 4174 case X86::BI__builtin_ia32_scalefss_round_mask: 4175 case X86::BI__builtin_ia32_scalefsh_round_mask: 4176 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 4177 case X86::BI__builtin_ia32_vcvtss2sh_round_mask: 4178 case X86::BI__builtin_ia32_vcvtsd2sh_round_mask: 4179 case X86::BI__builtin_ia32_sqrtsd_round_mask: 4180 case X86::BI__builtin_ia32_sqrtss_round_mask: 4181 case X86::BI__builtin_ia32_sqrtsh_round_mask: 4182 case X86::BI__builtin_ia32_vfmaddsd3_mask: 4183 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 4184 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 4185 case X86::BI__builtin_ia32_vfmaddss3_mask: 4186 case X86::BI__builtin_ia32_vfmaddss3_maskz: 4187 case X86::BI__builtin_ia32_vfmaddss3_mask3: 4188 case X86::BI__builtin_ia32_vfmaddsh3_mask: 4189 case X86::BI__builtin_ia32_vfmaddsh3_maskz: 4190 case X86::BI__builtin_ia32_vfmaddsh3_mask3: 4191 case X86::BI__builtin_ia32_vfmaddpd512_mask: 4192 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 4193 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 4194 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 4195 case X86::BI__builtin_ia32_vfmaddps512_mask: 4196 case X86::BI__builtin_ia32_vfmaddps512_maskz: 4197 case X86::BI__builtin_ia32_vfmaddps512_mask3: 4198 case X86::BI__builtin_ia32_vfmsubps512_mask3: 4199 case X86::BI__builtin_ia32_vfmaddph512_mask: 4200 case X86::BI__builtin_ia32_vfmaddph512_maskz: 4201 case X86::BI__builtin_ia32_vfmaddph512_mask3: 4202 case X86::BI__builtin_ia32_vfmsubph512_mask3: 4203 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 4204 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 4205 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 4206 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 4207 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 4208 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 4209 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 4210 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 4211 case X86::BI__builtin_ia32_vfmaddsubph512_mask: 4212 case X86::BI__builtin_ia32_vfmaddsubph512_maskz: 4213 case X86::BI__builtin_ia32_vfmaddsubph512_mask3: 4214 case X86::BI__builtin_ia32_vfmsubaddph512_mask3: 4215 case X86::BI__builtin_ia32_vfmaddcsh_mask: 4216 case X86::BI__builtin_ia32_vfmaddcsh_round_mask: 4217 case X86::BI__builtin_ia32_vfmaddcsh_round_mask3: 4218 case X86::BI__builtin_ia32_vfmaddcph512_mask: 4219 case X86::BI__builtin_ia32_vfmaddcph512_maskz: 4220 case X86::BI__builtin_ia32_vfmaddcph512_mask3: 4221 case X86::BI__builtin_ia32_vfcmaddcsh_mask: 4222 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask: 4223 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3: 4224 case X86::BI__builtin_ia32_vfcmaddcph512_mask: 4225 case X86::BI__builtin_ia32_vfcmaddcph512_maskz: 4226 case X86::BI__builtin_ia32_vfcmaddcph512_mask3: 4227 case X86::BI__builtin_ia32_vfmulcsh_mask: 4228 case X86::BI__builtin_ia32_vfmulcph512_mask: 4229 case X86::BI__builtin_ia32_vfcmulcsh_mask: 4230 case X86::BI__builtin_ia32_vfcmulcph512_mask: 4231 ArgNum = 4; 4232 HasRC = true; 4233 break; 4234 } 4235 4236 llvm::APSInt Result; 4237 4238 // We can't check the value of a dependent argument. 4239 Expr *Arg = TheCall->getArg(ArgNum); 4240 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4241 return false; 4242 4243 // Check constant-ness first. 4244 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4245 return true; 4246 4247 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 4248 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 4249 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 4250 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 4251 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 4252 Result == 8/*ROUND_NO_EXC*/ || 4253 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 4254 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 4255 return false; 4256 4257 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 4258 << Arg->getSourceRange(); 4259 } 4260 4261 // Check if the gather/scatter scale is legal. 4262 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 4263 CallExpr *TheCall) { 4264 unsigned ArgNum = 0; 4265 switch (BuiltinID) { 4266 default: 4267 return false; 4268 case X86::BI__builtin_ia32_gatherpfdpd: 4269 case X86::BI__builtin_ia32_gatherpfdps: 4270 case X86::BI__builtin_ia32_gatherpfqpd: 4271 case X86::BI__builtin_ia32_gatherpfqps: 4272 case X86::BI__builtin_ia32_scatterpfdpd: 4273 case X86::BI__builtin_ia32_scatterpfdps: 4274 case X86::BI__builtin_ia32_scatterpfqpd: 4275 case X86::BI__builtin_ia32_scatterpfqps: 4276 ArgNum = 3; 4277 break; 4278 case X86::BI__builtin_ia32_gatherd_pd: 4279 case X86::BI__builtin_ia32_gatherd_pd256: 4280 case X86::BI__builtin_ia32_gatherq_pd: 4281 case X86::BI__builtin_ia32_gatherq_pd256: 4282 case X86::BI__builtin_ia32_gatherd_ps: 4283 case X86::BI__builtin_ia32_gatherd_ps256: 4284 case X86::BI__builtin_ia32_gatherq_ps: 4285 case X86::BI__builtin_ia32_gatherq_ps256: 4286 case X86::BI__builtin_ia32_gatherd_q: 4287 case X86::BI__builtin_ia32_gatherd_q256: 4288 case X86::BI__builtin_ia32_gatherq_q: 4289 case X86::BI__builtin_ia32_gatherq_q256: 4290 case X86::BI__builtin_ia32_gatherd_d: 4291 case X86::BI__builtin_ia32_gatherd_d256: 4292 case X86::BI__builtin_ia32_gatherq_d: 4293 case X86::BI__builtin_ia32_gatherq_d256: 4294 case X86::BI__builtin_ia32_gather3div2df: 4295 case X86::BI__builtin_ia32_gather3div2di: 4296 case X86::BI__builtin_ia32_gather3div4df: 4297 case X86::BI__builtin_ia32_gather3div4di: 4298 case X86::BI__builtin_ia32_gather3div4sf: 4299 case X86::BI__builtin_ia32_gather3div4si: 4300 case X86::BI__builtin_ia32_gather3div8sf: 4301 case X86::BI__builtin_ia32_gather3div8si: 4302 case X86::BI__builtin_ia32_gather3siv2df: 4303 case X86::BI__builtin_ia32_gather3siv2di: 4304 case X86::BI__builtin_ia32_gather3siv4df: 4305 case X86::BI__builtin_ia32_gather3siv4di: 4306 case X86::BI__builtin_ia32_gather3siv4sf: 4307 case X86::BI__builtin_ia32_gather3siv4si: 4308 case X86::BI__builtin_ia32_gather3siv8sf: 4309 case X86::BI__builtin_ia32_gather3siv8si: 4310 case X86::BI__builtin_ia32_gathersiv8df: 4311 case X86::BI__builtin_ia32_gathersiv16sf: 4312 case X86::BI__builtin_ia32_gatherdiv8df: 4313 case X86::BI__builtin_ia32_gatherdiv16sf: 4314 case X86::BI__builtin_ia32_gathersiv8di: 4315 case X86::BI__builtin_ia32_gathersiv16si: 4316 case X86::BI__builtin_ia32_gatherdiv8di: 4317 case X86::BI__builtin_ia32_gatherdiv16si: 4318 case X86::BI__builtin_ia32_scatterdiv2df: 4319 case X86::BI__builtin_ia32_scatterdiv2di: 4320 case X86::BI__builtin_ia32_scatterdiv4df: 4321 case X86::BI__builtin_ia32_scatterdiv4di: 4322 case X86::BI__builtin_ia32_scatterdiv4sf: 4323 case X86::BI__builtin_ia32_scatterdiv4si: 4324 case X86::BI__builtin_ia32_scatterdiv8sf: 4325 case X86::BI__builtin_ia32_scatterdiv8si: 4326 case X86::BI__builtin_ia32_scattersiv2df: 4327 case X86::BI__builtin_ia32_scattersiv2di: 4328 case X86::BI__builtin_ia32_scattersiv4df: 4329 case X86::BI__builtin_ia32_scattersiv4di: 4330 case X86::BI__builtin_ia32_scattersiv4sf: 4331 case X86::BI__builtin_ia32_scattersiv4si: 4332 case X86::BI__builtin_ia32_scattersiv8sf: 4333 case X86::BI__builtin_ia32_scattersiv8si: 4334 case X86::BI__builtin_ia32_scattersiv8df: 4335 case X86::BI__builtin_ia32_scattersiv16sf: 4336 case X86::BI__builtin_ia32_scatterdiv8df: 4337 case X86::BI__builtin_ia32_scatterdiv16sf: 4338 case X86::BI__builtin_ia32_scattersiv8di: 4339 case X86::BI__builtin_ia32_scattersiv16si: 4340 case X86::BI__builtin_ia32_scatterdiv8di: 4341 case X86::BI__builtin_ia32_scatterdiv16si: 4342 ArgNum = 4; 4343 break; 4344 } 4345 4346 llvm::APSInt Result; 4347 4348 // We can't check the value of a dependent argument. 4349 Expr *Arg = TheCall->getArg(ArgNum); 4350 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4351 return false; 4352 4353 // Check constant-ness first. 4354 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4355 return true; 4356 4357 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4358 return false; 4359 4360 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4361 << Arg->getSourceRange(); 4362 } 4363 4364 enum { TileRegLow = 0, TileRegHigh = 7 }; 4365 4366 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4367 ArrayRef<int> ArgNums) { 4368 for (int ArgNum : ArgNums) { 4369 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4370 return true; 4371 } 4372 return false; 4373 } 4374 4375 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4376 ArrayRef<int> ArgNums) { 4377 // Because the max number of tile register is TileRegHigh + 1, so here we use 4378 // each bit to represent the usage of them in bitset. 4379 std::bitset<TileRegHigh + 1> ArgValues; 4380 for (int ArgNum : ArgNums) { 4381 Expr *Arg = TheCall->getArg(ArgNum); 4382 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4383 continue; 4384 4385 llvm::APSInt Result; 4386 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4387 return true; 4388 int ArgExtValue = Result.getExtValue(); 4389 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4390 "Incorrect tile register num."); 4391 if (ArgValues.test(ArgExtValue)) 4392 return Diag(TheCall->getBeginLoc(), 4393 diag::err_x86_builtin_tile_arg_duplicate) 4394 << TheCall->getArg(ArgNum)->getSourceRange(); 4395 ArgValues.set(ArgExtValue); 4396 } 4397 return false; 4398 } 4399 4400 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 4401 ArrayRef<int> ArgNums) { 4402 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 4403 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 4404 } 4405 4406 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 4407 switch (BuiltinID) { 4408 default: 4409 return false; 4410 case X86::BI__builtin_ia32_tileloadd64: 4411 case X86::BI__builtin_ia32_tileloaddt164: 4412 case X86::BI__builtin_ia32_tilestored64: 4413 case X86::BI__builtin_ia32_tilezero: 4414 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 4415 case X86::BI__builtin_ia32_tdpbssd: 4416 case X86::BI__builtin_ia32_tdpbsud: 4417 case X86::BI__builtin_ia32_tdpbusd: 4418 case X86::BI__builtin_ia32_tdpbuud: 4419 case X86::BI__builtin_ia32_tdpbf16ps: 4420 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 4421 } 4422 } 4423 static bool isX86_32Builtin(unsigned BuiltinID) { 4424 // These builtins only work on x86-32 targets. 4425 switch (BuiltinID) { 4426 case X86::BI__builtin_ia32_readeflags_u32: 4427 case X86::BI__builtin_ia32_writeeflags_u32: 4428 return true; 4429 } 4430 4431 return false; 4432 } 4433 4434 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 4435 CallExpr *TheCall) { 4436 if (BuiltinID == X86::BI__builtin_cpu_supports) 4437 return SemaBuiltinCpuSupports(*this, TI, TheCall); 4438 4439 if (BuiltinID == X86::BI__builtin_cpu_is) 4440 return SemaBuiltinCpuIs(*this, TI, TheCall); 4441 4442 // Check for 32-bit only builtins on a 64-bit target. 4443 const llvm::Triple &TT = TI.getTriple(); 4444 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 4445 return Diag(TheCall->getCallee()->getBeginLoc(), 4446 diag::err_32_bit_builtin_64_bit_tgt); 4447 4448 // If the intrinsic has rounding or SAE make sure its valid. 4449 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 4450 return true; 4451 4452 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 4453 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 4454 return true; 4455 4456 // If the intrinsic has a tile arguments, make sure they are valid. 4457 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4458 return true; 4459 4460 // For intrinsics which take an immediate value as part of the instruction, 4461 // range check them here. 4462 int i = 0, l = 0, u = 0; 4463 switch (BuiltinID) { 4464 default: 4465 return false; 4466 case X86::BI__builtin_ia32_vec_ext_v2si: 4467 case X86::BI__builtin_ia32_vec_ext_v2di: 4468 case X86::BI__builtin_ia32_vextractf128_pd256: 4469 case X86::BI__builtin_ia32_vextractf128_ps256: 4470 case X86::BI__builtin_ia32_vextractf128_si256: 4471 case X86::BI__builtin_ia32_extract128i256: 4472 case X86::BI__builtin_ia32_extractf64x4_mask: 4473 case X86::BI__builtin_ia32_extracti64x4_mask: 4474 case X86::BI__builtin_ia32_extractf32x8_mask: 4475 case X86::BI__builtin_ia32_extracti32x8_mask: 4476 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4477 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4478 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4479 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4480 i = 1; l = 0; u = 1; 4481 break; 4482 case X86::BI__builtin_ia32_vec_set_v2di: 4483 case X86::BI__builtin_ia32_vinsertf128_pd256: 4484 case X86::BI__builtin_ia32_vinsertf128_ps256: 4485 case X86::BI__builtin_ia32_vinsertf128_si256: 4486 case X86::BI__builtin_ia32_insert128i256: 4487 case X86::BI__builtin_ia32_insertf32x8: 4488 case X86::BI__builtin_ia32_inserti32x8: 4489 case X86::BI__builtin_ia32_insertf64x4: 4490 case X86::BI__builtin_ia32_inserti64x4: 4491 case X86::BI__builtin_ia32_insertf64x2_256: 4492 case X86::BI__builtin_ia32_inserti64x2_256: 4493 case X86::BI__builtin_ia32_insertf32x4_256: 4494 case X86::BI__builtin_ia32_inserti32x4_256: 4495 i = 2; l = 0; u = 1; 4496 break; 4497 case X86::BI__builtin_ia32_vpermilpd: 4498 case X86::BI__builtin_ia32_vec_ext_v4hi: 4499 case X86::BI__builtin_ia32_vec_ext_v4si: 4500 case X86::BI__builtin_ia32_vec_ext_v4sf: 4501 case X86::BI__builtin_ia32_vec_ext_v4di: 4502 case X86::BI__builtin_ia32_extractf32x4_mask: 4503 case X86::BI__builtin_ia32_extracti32x4_mask: 4504 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4505 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4506 i = 1; l = 0; u = 3; 4507 break; 4508 case X86::BI_mm_prefetch: 4509 case X86::BI__builtin_ia32_vec_ext_v8hi: 4510 case X86::BI__builtin_ia32_vec_ext_v8si: 4511 i = 1; l = 0; u = 7; 4512 break; 4513 case X86::BI__builtin_ia32_sha1rnds4: 4514 case X86::BI__builtin_ia32_blendpd: 4515 case X86::BI__builtin_ia32_shufpd: 4516 case X86::BI__builtin_ia32_vec_set_v4hi: 4517 case X86::BI__builtin_ia32_vec_set_v4si: 4518 case X86::BI__builtin_ia32_vec_set_v4di: 4519 case X86::BI__builtin_ia32_shuf_f32x4_256: 4520 case X86::BI__builtin_ia32_shuf_f64x2_256: 4521 case X86::BI__builtin_ia32_shuf_i32x4_256: 4522 case X86::BI__builtin_ia32_shuf_i64x2_256: 4523 case X86::BI__builtin_ia32_insertf64x2_512: 4524 case X86::BI__builtin_ia32_inserti64x2_512: 4525 case X86::BI__builtin_ia32_insertf32x4: 4526 case X86::BI__builtin_ia32_inserti32x4: 4527 i = 2; l = 0; u = 3; 4528 break; 4529 case X86::BI__builtin_ia32_vpermil2pd: 4530 case X86::BI__builtin_ia32_vpermil2pd256: 4531 case X86::BI__builtin_ia32_vpermil2ps: 4532 case X86::BI__builtin_ia32_vpermil2ps256: 4533 i = 3; l = 0; u = 3; 4534 break; 4535 case X86::BI__builtin_ia32_cmpb128_mask: 4536 case X86::BI__builtin_ia32_cmpw128_mask: 4537 case X86::BI__builtin_ia32_cmpd128_mask: 4538 case X86::BI__builtin_ia32_cmpq128_mask: 4539 case X86::BI__builtin_ia32_cmpb256_mask: 4540 case X86::BI__builtin_ia32_cmpw256_mask: 4541 case X86::BI__builtin_ia32_cmpd256_mask: 4542 case X86::BI__builtin_ia32_cmpq256_mask: 4543 case X86::BI__builtin_ia32_cmpb512_mask: 4544 case X86::BI__builtin_ia32_cmpw512_mask: 4545 case X86::BI__builtin_ia32_cmpd512_mask: 4546 case X86::BI__builtin_ia32_cmpq512_mask: 4547 case X86::BI__builtin_ia32_ucmpb128_mask: 4548 case X86::BI__builtin_ia32_ucmpw128_mask: 4549 case X86::BI__builtin_ia32_ucmpd128_mask: 4550 case X86::BI__builtin_ia32_ucmpq128_mask: 4551 case X86::BI__builtin_ia32_ucmpb256_mask: 4552 case X86::BI__builtin_ia32_ucmpw256_mask: 4553 case X86::BI__builtin_ia32_ucmpd256_mask: 4554 case X86::BI__builtin_ia32_ucmpq256_mask: 4555 case X86::BI__builtin_ia32_ucmpb512_mask: 4556 case X86::BI__builtin_ia32_ucmpw512_mask: 4557 case X86::BI__builtin_ia32_ucmpd512_mask: 4558 case X86::BI__builtin_ia32_ucmpq512_mask: 4559 case X86::BI__builtin_ia32_vpcomub: 4560 case X86::BI__builtin_ia32_vpcomuw: 4561 case X86::BI__builtin_ia32_vpcomud: 4562 case X86::BI__builtin_ia32_vpcomuq: 4563 case X86::BI__builtin_ia32_vpcomb: 4564 case X86::BI__builtin_ia32_vpcomw: 4565 case X86::BI__builtin_ia32_vpcomd: 4566 case X86::BI__builtin_ia32_vpcomq: 4567 case X86::BI__builtin_ia32_vec_set_v8hi: 4568 case X86::BI__builtin_ia32_vec_set_v8si: 4569 i = 2; l = 0; u = 7; 4570 break; 4571 case X86::BI__builtin_ia32_vpermilpd256: 4572 case X86::BI__builtin_ia32_roundps: 4573 case X86::BI__builtin_ia32_roundpd: 4574 case X86::BI__builtin_ia32_roundps256: 4575 case X86::BI__builtin_ia32_roundpd256: 4576 case X86::BI__builtin_ia32_getmantpd128_mask: 4577 case X86::BI__builtin_ia32_getmantpd256_mask: 4578 case X86::BI__builtin_ia32_getmantps128_mask: 4579 case X86::BI__builtin_ia32_getmantps256_mask: 4580 case X86::BI__builtin_ia32_getmantpd512_mask: 4581 case X86::BI__builtin_ia32_getmantps512_mask: 4582 case X86::BI__builtin_ia32_getmantph128_mask: 4583 case X86::BI__builtin_ia32_getmantph256_mask: 4584 case X86::BI__builtin_ia32_getmantph512_mask: 4585 case X86::BI__builtin_ia32_vec_ext_v16qi: 4586 case X86::BI__builtin_ia32_vec_ext_v16hi: 4587 i = 1; l = 0; u = 15; 4588 break; 4589 case X86::BI__builtin_ia32_pblendd128: 4590 case X86::BI__builtin_ia32_blendps: 4591 case X86::BI__builtin_ia32_blendpd256: 4592 case X86::BI__builtin_ia32_shufpd256: 4593 case X86::BI__builtin_ia32_roundss: 4594 case X86::BI__builtin_ia32_roundsd: 4595 case X86::BI__builtin_ia32_rangepd128_mask: 4596 case X86::BI__builtin_ia32_rangepd256_mask: 4597 case X86::BI__builtin_ia32_rangepd512_mask: 4598 case X86::BI__builtin_ia32_rangeps128_mask: 4599 case X86::BI__builtin_ia32_rangeps256_mask: 4600 case X86::BI__builtin_ia32_rangeps512_mask: 4601 case X86::BI__builtin_ia32_getmantsd_round_mask: 4602 case X86::BI__builtin_ia32_getmantss_round_mask: 4603 case X86::BI__builtin_ia32_getmantsh_round_mask: 4604 case X86::BI__builtin_ia32_vec_set_v16qi: 4605 case X86::BI__builtin_ia32_vec_set_v16hi: 4606 i = 2; l = 0; u = 15; 4607 break; 4608 case X86::BI__builtin_ia32_vec_ext_v32qi: 4609 i = 1; l = 0; u = 31; 4610 break; 4611 case X86::BI__builtin_ia32_cmpps: 4612 case X86::BI__builtin_ia32_cmpss: 4613 case X86::BI__builtin_ia32_cmppd: 4614 case X86::BI__builtin_ia32_cmpsd: 4615 case X86::BI__builtin_ia32_cmpps256: 4616 case X86::BI__builtin_ia32_cmppd256: 4617 case X86::BI__builtin_ia32_cmpps128_mask: 4618 case X86::BI__builtin_ia32_cmppd128_mask: 4619 case X86::BI__builtin_ia32_cmpps256_mask: 4620 case X86::BI__builtin_ia32_cmppd256_mask: 4621 case X86::BI__builtin_ia32_cmpps512_mask: 4622 case X86::BI__builtin_ia32_cmppd512_mask: 4623 case X86::BI__builtin_ia32_cmpsd_mask: 4624 case X86::BI__builtin_ia32_cmpss_mask: 4625 case X86::BI__builtin_ia32_vec_set_v32qi: 4626 i = 2; l = 0; u = 31; 4627 break; 4628 case X86::BI__builtin_ia32_permdf256: 4629 case X86::BI__builtin_ia32_permdi256: 4630 case X86::BI__builtin_ia32_permdf512: 4631 case X86::BI__builtin_ia32_permdi512: 4632 case X86::BI__builtin_ia32_vpermilps: 4633 case X86::BI__builtin_ia32_vpermilps256: 4634 case X86::BI__builtin_ia32_vpermilpd512: 4635 case X86::BI__builtin_ia32_vpermilps512: 4636 case X86::BI__builtin_ia32_pshufd: 4637 case X86::BI__builtin_ia32_pshufd256: 4638 case X86::BI__builtin_ia32_pshufd512: 4639 case X86::BI__builtin_ia32_pshufhw: 4640 case X86::BI__builtin_ia32_pshufhw256: 4641 case X86::BI__builtin_ia32_pshufhw512: 4642 case X86::BI__builtin_ia32_pshuflw: 4643 case X86::BI__builtin_ia32_pshuflw256: 4644 case X86::BI__builtin_ia32_pshuflw512: 4645 case X86::BI__builtin_ia32_vcvtps2ph: 4646 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4647 case X86::BI__builtin_ia32_vcvtps2ph256: 4648 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4649 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4650 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4651 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4652 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4653 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4654 case X86::BI__builtin_ia32_rndscaleps_mask: 4655 case X86::BI__builtin_ia32_rndscalepd_mask: 4656 case X86::BI__builtin_ia32_rndscaleph_mask: 4657 case X86::BI__builtin_ia32_reducepd128_mask: 4658 case X86::BI__builtin_ia32_reducepd256_mask: 4659 case X86::BI__builtin_ia32_reducepd512_mask: 4660 case X86::BI__builtin_ia32_reduceps128_mask: 4661 case X86::BI__builtin_ia32_reduceps256_mask: 4662 case X86::BI__builtin_ia32_reduceps512_mask: 4663 case X86::BI__builtin_ia32_reduceph128_mask: 4664 case X86::BI__builtin_ia32_reduceph256_mask: 4665 case X86::BI__builtin_ia32_reduceph512_mask: 4666 case X86::BI__builtin_ia32_prold512: 4667 case X86::BI__builtin_ia32_prolq512: 4668 case X86::BI__builtin_ia32_prold128: 4669 case X86::BI__builtin_ia32_prold256: 4670 case X86::BI__builtin_ia32_prolq128: 4671 case X86::BI__builtin_ia32_prolq256: 4672 case X86::BI__builtin_ia32_prord512: 4673 case X86::BI__builtin_ia32_prorq512: 4674 case X86::BI__builtin_ia32_prord128: 4675 case X86::BI__builtin_ia32_prord256: 4676 case X86::BI__builtin_ia32_prorq128: 4677 case X86::BI__builtin_ia32_prorq256: 4678 case X86::BI__builtin_ia32_fpclasspd128_mask: 4679 case X86::BI__builtin_ia32_fpclasspd256_mask: 4680 case X86::BI__builtin_ia32_fpclassps128_mask: 4681 case X86::BI__builtin_ia32_fpclassps256_mask: 4682 case X86::BI__builtin_ia32_fpclassps512_mask: 4683 case X86::BI__builtin_ia32_fpclasspd512_mask: 4684 case X86::BI__builtin_ia32_fpclassph128_mask: 4685 case X86::BI__builtin_ia32_fpclassph256_mask: 4686 case X86::BI__builtin_ia32_fpclassph512_mask: 4687 case X86::BI__builtin_ia32_fpclasssd_mask: 4688 case X86::BI__builtin_ia32_fpclassss_mask: 4689 case X86::BI__builtin_ia32_fpclasssh_mask: 4690 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4691 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4692 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4693 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4694 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4695 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4696 case X86::BI__builtin_ia32_kshiftliqi: 4697 case X86::BI__builtin_ia32_kshiftlihi: 4698 case X86::BI__builtin_ia32_kshiftlisi: 4699 case X86::BI__builtin_ia32_kshiftlidi: 4700 case X86::BI__builtin_ia32_kshiftriqi: 4701 case X86::BI__builtin_ia32_kshiftrihi: 4702 case X86::BI__builtin_ia32_kshiftrisi: 4703 case X86::BI__builtin_ia32_kshiftridi: 4704 i = 1; l = 0; u = 255; 4705 break; 4706 case X86::BI__builtin_ia32_vperm2f128_pd256: 4707 case X86::BI__builtin_ia32_vperm2f128_ps256: 4708 case X86::BI__builtin_ia32_vperm2f128_si256: 4709 case X86::BI__builtin_ia32_permti256: 4710 case X86::BI__builtin_ia32_pblendw128: 4711 case X86::BI__builtin_ia32_pblendw256: 4712 case X86::BI__builtin_ia32_blendps256: 4713 case X86::BI__builtin_ia32_pblendd256: 4714 case X86::BI__builtin_ia32_palignr128: 4715 case X86::BI__builtin_ia32_palignr256: 4716 case X86::BI__builtin_ia32_palignr512: 4717 case X86::BI__builtin_ia32_alignq512: 4718 case X86::BI__builtin_ia32_alignd512: 4719 case X86::BI__builtin_ia32_alignd128: 4720 case X86::BI__builtin_ia32_alignd256: 4721 case X86::BI__builtin_ia32_alignq128: 4722 case X86::BI__builtin_ia32_alignq256: 4723 case X86::BI__builtin_ia32_vcomisd: 4724 case X86::BI__builtin_ia32_vcomiss: 4725 case X86::BI__builtin_ia32_shuf_f32x4: 4726 case X86::BI__builtin_ia32_shuf_f64x2: 4727 case X86::BI__builtin_ia32_shuf_i32x4: 4728 case X86::BI__builtin_ia32_shuf_i64x2: 4729 case X86::BI__builtin_ia32_shufpd512: 4730 case X86::BI__builtin_ia32_shufps: 4731 case X86::BI__builtin_ia32_shufps256: 4732 case X86::BI__builtin_ia32_shufps512: 4733 case X86::BI__builtin_ia32_dbpsadbw128: 4734 case X86::BI__builtin_ia32_dbpsadbw256: 4735 case X86::BI__builtin_ia32_dbpsadbw512: 4736 case X86::BI__builtin_ia32_vpshldd128: 4737 case X86::BI__builtin_ia32_vpshldd256: 4738 case X86::BI__builtin_ia32_vpshldd512: 4739 case X86::BI__builtin_ia32_vpshldq128: 4740 case X86::BI__builtin_ia32_vpshldq256: 4741 case X86::BI__builtin_ia32_vpshldq512: 4742 case X86::BI__builtin_ia32_vpshldw128: 4743 case X86::BI__builtin_ia32_vpshldw256: 4744 case X86::BI__builtin_ia32_vpshldw512: 4745 case X86::BI__builtin_ia32_vpshrdd128: 4746 case X86::BI__builtin_ia32_vpshrdd256: 4747 case X86::BI__builtin_ia32_vpshrdd512: 4748 case X86::BI__builtin_ia32_vpshrdq128: 4749 case X86::BI__builtin_ia32_vpshrdq256: 4750 case X86::BI__builtin_ia32_vpshrdq512: 4751 case X86::BI__builtin_ia32_vpshrdw128: 4752 case X86::BI__builtin_ia32_vpshrdw256: 4753 case X86::BI__builtin_ia32_vpshrdw512: 4754 i = 2; l = 0; u = 255; 4755 break; 4756 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4757 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4758 case X86::BI__builtin_ia32_fixupimmps512_mask: 4759 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4760 case X86::BI__builtin_ia32_fixupimmsd_mask: 4761 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4762 case X86::BI__builtin_ia32_fixupimmss_mask: 4763 case X86::BI__builtin_ia32_fixupimmss_maskz: 4764 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4765 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4766 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4767 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4768 case X86::BI__builtin_ia32_fixupimmps128_mask: 4769 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4770 case X86::BI__builtin_ia32_fixupimmps256_mask: 4771 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4772 case X86::BI__builtin_ia32_pternlogd512_mask: 4773 case X86::BI__builtin_ia32_pternlogd512_maskz: 4774 case X86::BI__builtin_ia32_pternlogq512_mask: 4775 case X86::BI__builtin_ia32_pternlogq512_maskz: 4776 case X86::BI__builtin_ia32_pternlogd128_mask: 4777 case X86::BI__builtin_ia32_pternlogd128_maskz: 4778 case X86::BI__builtin_ia32_pternlogd256_mask: 4779 case X86::BI__builtin_ia32_pternlogd256_maskz: 4780 case X86::BI__builtin_ia32_pternlogq128_mask: 4781 case X86::BI__builtin_ia32_pternlogq128_maskz: 4782 case X86::BI__builtin_ia32_pternlogq256_mask: 4783 case X86::BI__builtin_ia32_pternlogq256_maskz: 4784 i = 3; l = 0; u = 255; 4785 break; 4786 case X86::BI__builtin_ia32_gatherpfdpd: 4787 case X86::BI__builtin_ia32_gatherpfdps: 4788 case X86::BI__builtin_ia32_gatherpfqpd: 4789 case X86::BI__builtin_ia32_gatherpfqps: 4790 case X86::BI__builtin_ia32_scatterpfdpd: 4791 case X86::BI__builtin_ia32_scatterpfdps: 4792 case X86::BI__builtin_ia32_scatterpfqpd: 4793 case X86::BI__builtin_ia32_scatterpfqps: 4794 i = 4; l = 2; u = 3; 4795 break; 4796 case X86::BI__builtin_ia32_reducesd_mask: 4797 case X86::BI__builtin_ia32_reducess_mask: 4798 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4799 case X86::BI__builtin_ia32_rndscaless_round_mask: 4800 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4801 case X86::BI__builtin_ia32_reducesh_mask: 4802 i = 4; l = 0; u = 255; 4803 break; 4804 } 4805 4806 // Note that we don't force a hard error on the range check here, allowing 4807 // template-generated or macro-generated dead code to potentially have out-of- 4808 // range values. These need to code generate, but don't need to necessarily 4809 // make any sense. We use a warning that defaults to an error. 4810 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4811 } 4812 4813 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4814 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4815 /// Returns true when the format fits the function and the FormatStringInfo has 4816 /// been populated. 4817 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4818 FormatStringInfo *FSI) { 4819 FSI->HasVAListArg = Format->getFirstArg() == 0; 4820 FSI->FormatIdx = Format->getFormatIdx() - 1; 4821 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4822 4823 // The way the format attribute works in GCC, the implicit this argument 4824 // of member functions is counted. However, it doesn't appear in our own 4825 // lists, so decrement format_idx in that case. 4826 if (IsCXXMember) { 4827 if(FSI->FormatIdx == 0) 4828 return false; 4829 --FSI->FormatIdx; 4830 if (FSI->FirstDataArg != 0) 4831 --FSI->FirstDataArg; 4832 } 4833 return true; 4834 } 4835 4836 /// Checks if a the given expression evaluates to null. 4837 /// 4838 /// Returns true if the value evaluates to null. 4839 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4840 // If the expression has non-null type, it doesn't evaluate to null. 4841 if (auto nullability 4842 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4843 if (*nullability == NullabilityKind::NonNull) 4844 return false; 4845 } 4846 4847 // As a special case, transparent unions initialized with zero are 4848 // considered null for the purposes of the nonnull attribute. 4849 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4850 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4851 if (const CompoundLiteralExpr *CLE = 4852 dyn_cast<CompoundLiteralExpr>(Expr)) 4853 if (const InitListExpr *ILE = 4854 dyn_cast<InitListExpr>(CLE->getInitializer())) 4855 Expr = ILE->getInit(0); 4856 } 4857 4858 bool Result; 4859 return (!Expr->isValueDependent() && 4860 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4861 !Result); 4862 } 4863 4864 static void CheckNonNullArgument(Sema &S, 4865 const Expr *ArgExpr, 4866 SourceLocation CallSiteLoc) { 4867 if (CheckNonNullExpr(S, ArgExpr)) 4868 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4869 S.PDiag(diag::warn_null_arg) 4870 << ArgExpr->getSourceRange()); 4871 } 4872 4873 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4874 FormatStringInfo FSI; 4875 if ((GetFormatStringType(Format) == FST_NSString) && 4876 getFormatStringInfo(Format, false, &FSI)) { 4877 Idx = FSI.FormatIdx; 4878 return true; 4879 } 4880 return false; 4881 } 4882 4883 /// Diagnose use of %s directive in an NSString which is being passed 4884 /// as formatting string to formatting method. 4885 static void 4886 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4887 const NamedDecl *FDecl, 4888 Expr **Args, 4889 unsigned NumArgs) { 4890 unsigned Idx = 0; 4891 bool Format = false; 4892 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4893 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4894 Idx = 2; 4895 Format = true; 4896 } 4897 else 4898 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4899 if (S.GetFormatNSStringIdx(I, Idx)) { 4900 Format = true; 4901 break; 4902 } 4903 } 4904 if (!Format || NumArgs <= Idx) 4905 return; 4906 const Expr *FormatExpr = Args[Idx]; 4907 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4908 FormatExpr = CSCE->getSubExpr(); 4909 const StringLiteral *FormatString; 4910 if (const ObjCStringLiteral *OSL = 4911 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4912 FormatString = OSL->getString(); 4913 else 4914 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4915 if (!FormatString) 4916 return; 4917 if (S.FormatStringHasSArg(FormatString)) { 4918 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4919 << "%s" << 1 << 1; 4920 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4921 << FDecl->getDeclName(); 4922 } 4923 } 4924 4925 /// Determine whether the given type has a non-null nullability annotation. 4926 static bool isNonNullType(ASTContext &ctx, QualType type) { 4927 if (auto nullability = type->getNullability(ctx)) 4928 return *nullability == NullabilityKind::NonNull; 4929 4930 return false; 4931 } 4932 4933 static void CheckNonNullArguments(Sema &S, 4934 const NamedDecl *FDecl, 4935 const FunctionProtoType *Proto, 4936 ArrayRef<const Expr *> Args, 4937 SourceLocation CallSiteLoc) { 4938 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4939 4940 // Already checked by by constant evaluator. 4941 if (S.isConstantEvaluated()) 4942 return; 4943 // Check the attributes attached to the method/function itself. 4944 llvm::SmallBitVector NonNullArgs; 4945 if (FDecl) { 4946 // Handle the nonnull attribute on the function/method declaration itself. 4947 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4948 if (!NonNull->args_size()) { 4949 // Easy case: all pointer arguments are nonnull. 4950 for (const auto *Arg : Args) 4951 if (S.isValidPointerAttrType(Arg->getType())) 4952 CheckNonNullArgument(S, Arg, CallSiteLoc); 4953 return; 4954 } 4955 4956 for (const ParamIdx &Idx : NonNull->args()) { 4957 unsigned IdxAST = Idx.getASTIndex(); 4958 if (IdxAST >= Args.size()) 4959 continue; 4960 if (NonNullArgs.empty()) 4961 NonNullArgs.resize(Args.size()); 4962 NonNullArgs.set(IdxAST); 4963 } 4964 } 4965 } 4966 4967 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4968 // Handle the nonnull attribute on the parameters of the 4969 // function/method. 4970 ArrayRef<ParmVarDecl*> parms; 4971 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4972 parms = FD->parameters(); 4973 else 4974 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4975 4976 unsigned ParamIndex = 0; 4977 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4978 I != E; ++I, ++ParamIndex) { 4979 const ParmVarDecl *PVD = *I; 4980 if (PVD->hasAttr<NonNullAttr>() || 4981 isNonNullType(S.Context, PVD->getType())) { 4982 if (NonNullArgs.empty()) 4983 NonNullArgs.resize(Args.size()); 4984 4985 NonNullArgs.set(ParamIndex); 4986 } 4987 } 4988 } else { 4989 // If we have a non-function, non-method declaration but no 4990 // function prototype, try to dig out the function prototype. 4991 if (!Proto) { 4992 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4993 QualType type = VD->getType().getNonReferenceType(); 4994 if (auto pointerType = type->getAs<PointerType>()) 4995 type = pointerType->getPointeeType(); 4996 else if (auto blockType = type->getAs<BlockPointerType>()) 4997 type = blockType->getPointeeType(); 4998 // FIXME: data member pointers? 4999 5000 // Dig out the function prototype, if there is one. 5001 Proto = type->getAs<FunctionProtoType>(); 5002 } 5003 } 5004 5005 // Fill in non-null argument information from the nullability 5006 // information on the parameter types (if we have them). 5007 if (Proto) { 5008 unsigned Index = 0; 5009 for (auto paramType : Proto->getParamTypes()) { 5010 if (isNonNullType(S.Context, paramType)) { 5011 if (NonNullArgs.empty()) 5012 NonNullArgs.resize(Args.size()); 5013 5014 NonNullArgs.set(Index); 5015 } 5016 5017 ++Index; 5018 } 5019 } 5020 } 5021 5022 // Check for non-null arguments. 5023 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 5024 ArgIndex != ArgIndexEnd; ++ArgIndex) { 5025 if (NonNullArgs[ArgIndex]) 5026 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 5027 } 5028 } 5029 5030 /// Warn if a pointer or reference argument passed to a function points to an 5031 /// object that is less aligned than the parameter. This can happen when 5032 /// creating a typedef with a lower alignment than the original type and then 5033 /// calling functions defined in terms of the original type. 5034 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 5035 StringRef ParamName, QualType ArgTy, 5036 QualType ParamTy) { 5037 5038 // If a function accepts a pointer or reference type 5039 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 5040 return; 5041 5042 // If the parameter is a pointer type, get the pointee type for the 5043 // argument too. If the parameter is a reference type, don't try to get 5044 // the pointee type for the argument. 5045 if (ParamTy->isPointerType()) 5046 ArgTy = ArgTy->getPointeeType(); 5047 5048 // Remove reference or pointer 5049 ParamTy = ParamTy->getPointeeType(); 5050 5051 // Find expected alignment, and the actual alignment of the passed object. 5052 // getTypeAlignInChars requires complete types 5053 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 5054 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 5055 ArgTy->isUndeducedType()) 5056 return; 5057 5058 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 5059 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 5060 5061 // If the argument is less aligned than the parameter, there is a 5062 // potential alignment issue. 5063 if (ArgAlign < ParamAlign) 5064 Diag(Loc, diag::warn_param_mismatched_alignment) 5065 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 5066 << ParamName << (FDecl != nullptr) << FDecl; 5067 } 5068 5069 /// Handles the checks for format strings, non-POD arguments to vararg 5070 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 5071 /// attributes. 5072 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 5073 const Expr *ThisArg, ArrayRef<const Expr *> Args, 5074 bool IsMemberFunction, SourceLocation Loc, 5075 SourceRange Range, VariadicCallType CallType) { 5076 // FIXME: We should check as much as we can in the template definition. 5077 if (CurContext->isDependentContext()) 5078 return; 5079 5080 // Printf and scanf checking. 5081 llvm::SmallBitVector CheckedVarArgs; 5082 if (FDecl) { 5083 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 5084 // Only create vector if there are format attributes. 5085 CheckedVarArgs.resize(Args.size()); 5086 5087 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 5088 CheckedVarArgs); 5089 } 5090 } 5091 5092 // Refuse POD arguments that weren't caught by the format string 5093 // checks above. 5094 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 5095 if (CallType != VariadicDoesNotApply && 5096 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 5097 unsigned NumParams = Proto ? Proto->getNumParams() 5098 : FDecl && isa<FunctionDecl>(FDecl) 5099 ? cast<FunctionDecl>(FDecl)->getNumParams() 5100 : FDecl && isa<ObjCMethodDecl>(FDecl) 5101 ? cast<ObjCMethodDecl>(FDecl)->param_size() 5102 : 0; 5103 5104 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 5105 // Args[ArgIdx] can be null in malformed code. 5106 if (const Expr *Arg = Args[ArgIdx]) { 5107 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 5108 checkVariadicArgument(Arg, CallType); 5109 } 5110 } 5111 } 5112 5113 if (FDecl || Proto) { 5114 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 5115 5116 // Type safety checking. 5117 if (FDecl) { 5118 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 5119 CheckArgumentWithTypeTag(I, Args, Loc); 5120 } 5121 } 5122 5123 // Check that passed arguments match the alignment of original arguments. 5124 // Try to get the missing prototype from the declaration. 5125 if (!Proto && FDecl) { 5126 const auto *FT = FDecl->getFunctionType(); 5127 if (isa_and_nonnull<FunctionProtoType>(FT)) 5128 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 5129 } 5130 if (Proto) { 5131 // For variadic functions, we may have more args than parameters. 5132 // For some K&R functions, we may have less args than parameters. 5133 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 5134 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 5135 // Args[ArgIdx] can be null in malformed code. 5136 if (const Expr *Arg = Args[ArgIdx]) { 5137 if (Arg->containsErrors()) 5138 continue; 5139 5140 QualType ParamTy = Proto->getParamType(ArgIdx); 5141 QualType ArgTy = Arg->getType(); 5142 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 5143 ArgTy, ParamTy); 5144 } 5145 } 5146 } 5147 5148 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 5149 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 5150 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 5151 if (!Arg->isValueDependent()) { 5152 Expr::EvalResult Align; 5153 if (Arg->EvaluateAsInt(Align, Context)) { 5154 const llvm::APSInt &I = Align.Val.getInt(); 5155 if (!I.isPowerOf2()) 5156 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 5157 << Arg->getSourceRange(); 5158 5159 if (I > Sema::MaximumAlignment) 5160 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 5161 << Arg->getSourceRange() << Sema::MaximumAlignment; 5162 } 5163 } 5164 } 5165 5166 if (FD) 5167 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 5168 } 5169 5170 /// CheckConstructorCall - Check a constructor call for correctness and safety 5171 /// properties not enforced by the C type system. 5172 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 5173 ArrayRef<const Expr *> Args, 5174 const FunctionProtoType *Proto, 5175 SourceLocation Loc) { 5176 VariadicCallType CallType = 5177 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 5178 5179 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 5180 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 5181 Context.getPointerType(Ctor->getThisObjectType())); 5182 5183 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 5184 Loc, SourceRange(), CallType); 5185 } 5186 5187 /// CheckFunctionCall - Check a direct function call for various correctness 5188 /// and safety properties not strictly enforced by the C type system. 5189 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 5190 const FunctionProtoType *Proto) { 5191 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 5192 isa<CXXMethodDecl>(FDecl); 5193 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 5194 IsMemberOperatorCall; 5195 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 5196 TheCall->getCallee()); 5197 Expr** Args = TheCall->getArgs(); 5198 unsigned NumArgs = TheCall->getNumArgs(); 5199 5200 Expr *ImplicitThis = nullptr; 5201 if (IsMemberOperatorCall) { 5202 // If this is a call to a member operator, hide the first argument 5203 // from checkCall. 5204 // FIXME: Our choice of AST representation here is less than ideal. 5205 ImplicitThis = Args[0]; 5206 ++Args; 5207 --NumArgs; 5208 } else if (IsMemberFunction) 5209 ImplicitThis = 5210 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 5211 5212 if (ImplicitThis) { 5213 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 5214 // used. 5215 QualType ThisType = ImplicitThis->getType(); 5216 if (!ThisType->isPointerType()) { 5217 assert(!ThisType->isReferenceType()); 5218 ThisType = Context.getPointerType(ThisType); 5219 } 5220 5221 QualType ThisTypeFromDecl = 5222 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 5223 5224 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 5225 ThisTypeFromDecl); 5226 } 5227 5228 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 5229 IsMemberFunction, TheCall->getRParenLoc(), 5230 TheCall->getCallee()->getSourceRange(), CallType); 5231 5232 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5233 // None of the checks below are needed for functions that don't have 5234 // simple names (e.g., C++ conversion functions). 5235 if (!FnInfo) 5236 return false; 5237 5238 CheckTCBEnforcement(TheCall, FDecl); 5239 5240 CheckAbsoluteValueFunction(TheCall, FDecl); 5241 CheckMaxUnsignedZero(TheCall, FDecl); 5242 5243 if (getLangOpts().ObjC) 5244 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 5245 5246 unsigned CMId = FDecl->getMemoryFunctionKind(); 5247 5248 // Handle memory setting and copying functions. 5249 switch (CMId) { 5250 case 0: 5251 return false; 5252 case Builtin::BIstrlcpy: // fallthrough 5253 case Builtin::BIstrlcat: 5254 CheckStrlcpycatArguments(TheCall, FnInfo); 5255 break; 5256 case Builtin::BIstrncat: 5257 CheckStrncatArguments(TheCall, FnInfo); 5258 break; 5259 case Builtin::BIfree: 5260 CheckFreeArguments(TheCall); 5261 break; 5262 default: 5263 CheckMemaccessArguments(TheCall, CMId, FnInfo); 5264 } 5265 5266 return false; 5267 } 5268 5269 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 5270 ArrayRef<const Expr *> Args) { 5271 VariadicCallType CallType = 5272 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 5273 5274 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 5275 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 5276 CallType); 5277 5278 return false; 5279 } 5280 5281 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 5282 const FunctionProtoType *Proto) { 5283 QualType Ty; 5284 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 5285 Ty = V->getType().getNonReferenceType(); 5286 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 5287 Ty = F->getType().getNonReferenceType(); 5288 else 5289 return false; 5290 5291 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 5292 !Ty->isFunctionProtoType()) 5293 return false; 5294 5295 VariadicCallType CallType; 5296 if (!Proto || !Proto->isVariadic()) { 5297 CallType = VariadicDoesNotApply; 5298 } else if (Ty->isBlockPointerType()) { 5299 CallType = VariadicBlock; 5300 } else { // Ty->isFunctionPointerType() 5301 CallType = VariadicFunction; 5302 } 5303 5304 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 5305 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5306 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5307 TheCall->getCallee()->getSourceRange(), CallType); 5308 5309 return false; 5310 } 5311 5312 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 5313 /// such as function pointers returned from functions. 5314 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 5315 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 5316 TheCall->getCallee()); 5317 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 5318 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5319 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5320 TheCall->getCallee()->getSourceRange(), CallType); 5321 5322 return false; 5323 } 5324 5325 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 5326 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 5327 return false; 5328 5329 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 5330 switch (Op) { 5331 case AtomicExpr::AO__c11_atomic_init: 5332 case AtomicExpr::AO__opencl_atomic_init: 5333 llvm_unreachable("There is no ordering argument for an init"); 5334 5335 case AtomicExpr::AO__c11_atomic_load: 5336 case AtomicExpr::AO__opencl_atomic_load: 5337 case AtomicExpr::AO__hip_atomic_load: 5338 case AtomicExpr::AO__atomic_load_n: 5339 case AtomicExpr::AO__atomic_load: 5340 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5341 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5342 5343 case AtomicExpr::AO__c11_atomic_store: 5344 case AtomicExpr::AO__opencl_atomic_store: 5345 case AtomicExpr::AO__hip_atomic_store: 5346 case AtomicExpr::AO__atomic_store: 5347 case AtomicExpr::AO__atomic_store_n: 5348 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5349 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5350 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5351 5352 default: 5353 return true; 5354 } 5355 } 5356 5357 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5358 AtomicExpr::AtomicOp Op) { 5359 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5360 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5361 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5362 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5363 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5364 Op); 5365 } 5366 5367 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5368 SourceLocation RParenLoc, MultiExprArg Args, 5369 AtomicExpr::AtomicOp Op, 5370 AtomicArgumentOrder ArgOrder) { 5371 // All the non-OpenCL operations take one of the following forms. 5372 // The OpenCL operations take the __c11 forms with one extra argument for 5373 // synchronization scope. 5374 enum { 5375 // C __c11_atomic_init(A *, C) 5376 Init, 5377 5378 // C __c11_atomic_load(A *, int) 5379 Load, 5380 5381 // void __atomic_load(A *, CP, int) 5382 LoadCopy, 5383 5384 // void __atomic_store(A *, CP, int) 5385 Copy, 5386 5387 // C __c11_atomic_add(A *, M, int) 5388 Arithmetic, 5389 5390 // C __atomic_exchange_n(A *, CP, int) 5391 Xchg, 5392 5393 // void __atomic_exchange(A *, C *, CP, int) 5394 GNUXchg, 5395 5396 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 5397 C11CmpXchg, 5398 5399 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 5400 GNUCmpXchg 5401 } Form = Init; 5402 5403 const unsigned NumForm = GNUCmpXchg + 1; 5404 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 5405 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 5406 // where: 5407 // C is an appropriate type, 5408 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 5409 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 5410 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 5411 // the int parameters are for orderings. 5412 5413 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 5414 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 5415 "need to update code for modified forms"); 5416 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 5417 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 5418 AtomicExpr::AO__atomic_load, 5419 "need to update code for modified C11 atomics"); 5420 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 5421 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 5422 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load && 5423 Op <= AtomicExpr::AO__hip_atomic_fetch_max; 5424 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 5425 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 5426 IsOpenCL; 5427 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 5428 Op == AtomicExpr::AO__atomic_store_n || 5429 Op == AtomicExpr::AO__atomic_exchange_n || 5430 Op == AtomicExpr::AO__atomic_compare_exchange_n; 5431 bool IsAddSub = false; 5432 5433 switch (Op) { 5434 case AtomicExpr::AO__c11_atomic_init: 5435 case AtomicExpr::AO__opencl_atomic_init: 5436 Form = Init; 5437 break; 5438 5439 case AtomicExpr::AO__c11_atomic_load: 5440 case AtomicExpr::AO__opencl_atomic_load: 5441 case AtomicExpr::AO__hip_atomic_load: 5442 case AtomicExpr::AO__atomic_load_n: 5443 Form = Load; 5444 break; 5445 5446 case AtomicExpr::AO__atomic_load: 5447 Form = LoadCopy; 5448 break; 5449 5450 case AtomicExpr::AO__c11_atomic_store: 5451 case AtomicExpr::AO__opencl_atomic_store: 5452 case AtomicExpr::AO__hip_atomic_store: 5453 case AtomicExpr::AO__atomic_store: 5454 case AtomicExpr::AO__atomic_store_n: 5455 Form = Copy; 5456 break; 5457 case AtomicExpr::AO__hip_atomic_fetch_add: 5458 case AtomicExpr::AO__hip_atomic_fetch_min: 5459 case AtomicExpr::AO__hip_atomic_fetch_max: 5460 case AtomicExpr::AO__c11_atomic_fetch_add: 5461 case AtomicExpr::AO__c11_atomic_fetch_sub: 5462 case AtomicExpr::AO__opencl_atomic_fetch_add: 5463 case AtomicExpr::AO__opencl_atomic_fetch_sub: 5464 case AtomicExpr::AO__atomic_fetch_add: 5465 case AtomicExpr::AO__atomic_fetch_sub: 5466 case AtomicExpr::AO__atomic_add_fetch: 5467 case AtomicExpr::AO__atomic_sub_fetch: 5468 IsAddSub = true; 5469 Form = Arithmetic; 5470 break; 5471 case AtomicExpr::AO__c11_atomic_fetch_and: 5472 case AtomicExpr::AO__c11_atomic_fetch_or: 5473 case AtomicExpr::AO__c11_atomic_fetch_xor: 5474 case AtomicExpr::AO__hip_atomic_fetch_and: 5475 case AtomicExpr::AO__hip_atomic_fetch_or: 5476 case AtomicExpr::AO__hip_atomic_fetch_xor: 5477 case AtomicExpr::AO__c11_atomic_fetch_nand: 5478 case AtomicExpr::AO__opencl_atomic_fetch_and: 5479 case AtomicExpr::AO__opencl_atomic_fetch_or: 5480 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5481 case AtomicExpr::AO__atomic_fetch_and: 5482 case AtomicExpr::AO__atomic_fetch_or: 5483 case AtomicExpr::AO__atomic_fetch_xor: 5484 case AtomicExpr::AO__atomic_fetch_nand: 5485 case AtomicExpr::AO__atomic_and_fetch: 5486 case AtomicExpr::AO__atomic_or_fetch: 5487 case AtomicExpr::AO__atomic_xor_fetch: 5488 case AtomicExpr::AO__atomic_nand_fetch: 5489 Form = Arithmetic; 5490 break; 5491 case AtomicExpr::AO__c11_atomic_fetch_min: 5492 case AtomicExpr::AO__c11_atomic_fetch_max: 5493 case AtomicExpr::AO__opencl_atomic_fetch_min: 5494 case AtomicExpr::AO__opencl_atomic_fetch_max: 5495 case AtomicExpr::AO__atomic_min_fetch: 5496 case AtomicExpr::AO__atomic_max_fetch: 5497 case AtomicExpr::AO__atomic_fetch_min: 5498 case AtomicExpr::AO__atomic_fetch_max: 5499 Form = Arithmetic; 5500 break; 5501 5502 case AtomicExpr::AO__c11_atomic_exchange: 5503 case AtomicExpr::AO__hip_atomic_exchange: 5504 case AtomicExpr::AO__opencl_atomic_exchange: 5505 case AtomicExpr::AO__atomic_exchange_n: 5506 Form = Xchg; 5507 break; 5508 5509 case AtomicExpr::AO__atomic_exchange: 5510 Form = GNUXchg; 5511 break; 5512 5513 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5514 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5515 case AtomicExpr::AO__hip_atomic_compare_exchange_strong: 5516 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5517 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5518 case AtomicExpr::AO__hip_atomic_compare_exchange_weak: 5519 Form = C11CmpXchg; 5520 break; 5521 5522 case AtomicExpr::AO__atomic_compare_exchange: 5523 case AtomicExpr::AO__atomic_compare_exchange_n: 5524 Form = GNUCmpXchg; 5525 break; 5526 } 5527 5528 unsigned AdjustedNumArgs = NumArgs[Form]; 5529 if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init) 5530 ++AdjustedNumArgs; 5531 // Check we have the right number of arguments. 5532 if (Args.size() < AdjustedNumArgs) { 5533 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5534 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5535 << ExprRange; 5536 return ExprError(); 5537 } else if (Args.size() > AdjustedNumArgs) { 5538 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5539 diag::err_typecheck_call_too_many_args) 5540 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5541 << ExprRange; 5542 return ExprError(); 5543 } 5544 5545 // Inspect the first argument of the atomic operation. 5546 Expr *Ptr = Args[0]; 5547 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5548 if (ConvertedPtr.isInvalid()) 5549 return ExprError(); 5550 5551 Ptr = ConvertedPtr.get(); 5552 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5553 if (!pointerType) { 5554 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5555 << Ptr->getType() << Ptr->getSourceRange(); 5556 return ExprError(); 5557 } 5558 5559 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5560 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5561 QualType ValType = AtomTy; // 'C' 5562 if (IsC11) { 5563 if (!AtomTy->isAtomicType()) { 5564 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5565 << Ptr->getType() << Ptr->getSourceRange(); 5566 return ExprError(); 5567 } 5568 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5569 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5570 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5571 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5572 << Ptr->getSourceRange(); 5573 return ExprError(); 5574 } 5575 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5576 } else if (Form != Load && Form != LoadCopy) { 5577 if (ValType.isConstQualified()) { 5578 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5579 << Ptr->getType() << Ptr->getSourceRange(); 5580 return ExprError(); 5581 } 5582 } 5583 5584 // For an arithmetic operation, the implied arithmetic must be well-formed. 5585 if (Form == Arithmetic) { 5586 // GCC does not enforce these rules for GNU atomics, but we do to help catch 5587 // trivial type errors. 5588 auto IsAllowedValueType = [&](QualType ValType) { 5589 if (ValType->isIntegerType()) 5590 return true; 5591 if (ValType->isPointerType()) 5592 return true; 5593 if (!ValType->isFloatingType()) 5594 return false; 5595 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5596 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5597 &Context.getTargetInfo().getLongDoubleFormat() == 5598 &llvm::APFloat::x87DoubleExtended()) 5599 return false; 5600 return true; 5601 }; 5602 if (IsAddSub && !IsAllowedValueType(ValType)) { 5603 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5604 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5605 return ExprError(); 5606 } 5607 if (!IsAddSub && !ValType->isIntegerType()) { 5608 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5609 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5610 return ExprError(); 5611 } 5612 if (IsC11 && ValType->isPointerType() && 5613 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5614 diag::err_incomplete_type)) { 5615 return ExprError(); 5616 } 5617 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5618 // For __atomic_*_n operations, the value type must be a scalar integral or 5619 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5620 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5621 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5622 return ExprError(); 5623 } 5624 5625 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5626 !AtomTy->isScalarType()) { 5627 // For GNU atomics, require a trivially-copyable type. This is not part of 5628 // the GNU atomics specification but we enforce it for consistency with 5629 // other atomics which generally all require a trivially-copyable type. This 5630 // is because atomics just copy bits. 5631 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5632 << Ptr->getType() << Ptr->getSourceRange(); 5633 return ExprError(); 5634 } 5635 5636 switch (ValType.getObjCLifetime()) { 5637 case Qualifiers::OCL_None: 5638 case Qualifiers::OCL_ExplicitNone: 5639 // okay 5640 break; 5641 5642 case Qualifiers::OCL_Weak: 5643 case Qualifiers::OCL_Strong: 5644 case Qualifiers::OCL_Autoreleasing: 5645 // FIXME: Can this happen? By this point, ValType should be known 5646 // to be trivially copyable. 5647 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5648 << ValType << Ptr->getSourceRange(); 5649 return ExprError(); 5650 } 5651 5652 // All atomic operations have an overload which takes a pointer to a volatile 5653 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5654 // into the result or the other operands. Similarly atomic_load takes a 5655 // pointer to a const 'A'. 5656 ValType.removeLocalVolatile(); 5657 ValType.removeLocalConst(); 5658 QualType ResultType = ValType; 5659 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5660 Form == Init) 5661 ResultType = Context.VoidTy; 5662 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5663 ResultType = Context.BoolTy; 5664 5665 // The type of a parameter passed 'by value'. In the GNU atomics, such 5666 // arguments are actually passed as pointers. 5667 QualType ByValType = ValType; // 'CP' 5668 bool IsPassedByAddress = false; 5669 if (!IsC11 && !IsHIP && !IsN) { 5670 ByValType = Ptr->getType(); 5671 IsPassedByAddress = true; 5672 } 5673 5674 SmallVector<Expr *, 5> APIOrderedArgs; 5675 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5676 APIOrderedArgs.push_back(Args[0]); 5677 switch (Form) { 5678 case Init: 5679 case Load: 5680 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5681 break; 5682 case LoadCopy: 5683 case Copy: 5684 case Arithmetic: 5685 case Xchg: 5686 APIOrderedArgs.push_back(Args[2]); // Val1 5687 APIOrderedArgs.push_back(Args[1]); // Order 5688 break; 5689 case GNUXchg: 5690 APIOrderedArgs.push_back(Args[2]); // Val1 5691 APIOrderedArgs.push_back(Args[3]); // Val2 5692 APIOrderedArgs.push_back(Args[1]); // Order 5693 break; 5694 case C11CmpXchg: 5695 APIOrderedArgs.push_back(Args[2]); // Val1 5696 APIOrderedArgs.push_back(Args[4]); // Val2 5697 APIOrderedArgs.push_back(Args[1]); // Order 5698 APIOrderedArgs.push_back(Args[3]); // OrderFail 5699 break; 5700 case GNUCmpXchg: 5701 APIOrderedArgs.push_back(Args[2]); // Val1 5702 APIOrderedArgs.push_back(Args[4]); // Val2 5703 APIOrderedArgs.push_back(Args[5]); // Weak 5704 APIOrderedArgs.push_back(Args[1]); // Order 5705 APIOrderedArgs.push_back(Args[3]); // OrderFail 5706 break; 5707 } 5708 } else 5709 APIOrderedArgs.append(Args.begin(), Args.end()); 5710 5711 // The first argument's non-CV pointer type is used to deduce the type of 5712 // subsequent arguments, except for: 5713 // - weak flag (always converted to bool) 5714 // - memory order (always converted to int) 5715 // - scope (always converted to int) 5716 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5717 QualType Ty; 5718 if (i < NumVals[Form] + 1) { 5719 switch (i) { 5720 case 0: 5721 // The first argument is always a pointer. It has a fixed type. 5722 // It is always dereferenced, a nullptr is undefined. 5723 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5724 // Nothing else to do: we already know all we want about this pointer. 5725 continue; 5726 case 1: 5727 // The second argument is the non-atomic operand. For arithmetic, this 5728 // is always passed by value, and for a compare_exchange it is always 5729 // passed by address. For the rest, GNU uses by-address and C11 uses 5730 // by-value. 5731 assert(Form != Load); 5732 if (Form == Arithmetic && ValType->isPointerType()) 5733 Ty = Context.getPointerDiffType(); 5734 else if (Form == Init || Form == Arithmetic) 5735 Ty = ValType; 5736 else if (Form == Copy || Form == Xchg) { 5737 if (IsPassedByAddress) { 5738 // The value pointer is always dereferenced, a nullptr is undefined. 5739 CheckNonNullArgument(*this, APIOrderedArgs[i], 5740 ExprRange.getBegin()); 5741 } 5742 Ty = ByValType; 5743 } else { 5744 Expr *ValArg = APIOrderedArgs[i]; 5745 // The value pointer is always dereferenced, a nullptr is undefined. 5746 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5747 LangAS AS = LangAS::Default; 5748 // Keep address space of non-atomic pointer type. 5749 if (const PointerType *PtrTy = 5750 ValArg->getType()->getAs<PointerType>()) { 5751 AS = PtrTy->getPointeeType().getAddressSpace(); 5752 } 5753 Ty = Context.getPointerType( 5754 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5755 } 5756 break; 5757 case 2: 5758 // The third argument to compare_exchange / GNU exchange is the desired 5759 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5760 if (IsPassedByAddress) 5761 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5762 Ty = ByValType; 5763 break; 5764 case 3: 5765 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5766 Ty = Context.BoolTy; 5767 break; 5768 } 5769 } else { 5770 // The order(s) and scope are always converted to int. 5771 Ty = Context.IntTy; 5772 } 5773 5774 InitializedEntity Entity = 5775 InitializedEntity::InitializeParameter(Context, Ty, false); 5776 ExprResult Arg = APIOrderedArgs[i]; 5777 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5778 if (Arg.isInvalid()) 5779 return true; 5780 APIOrderedArgs[i] = Arg.get(); 5781 } 5782 5783 // Permute the arguments into a 'consistent' order. 5784 SmallVector<Expr*, 5> SubExprs; 5785 SubExprs.push_back(Ptr); 5786 switch (Form) { 5787 case Init: 5788 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5789 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5790 break; 5791 case Load: 5792 SubExprs.push_back(APIOrderedArgs[1]); // Order 5793 break; 5794 case LoadCopy: 5795 case Copy: 5796 case Arithmetic: 5797 case Xchg: 5798 SubExprs.push_back(APIOrderedArgs[2]); // Order 5799 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5800 break; 5801 case GNUXchg: 5802 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5803 SubExprs.push_back(APIOrderedArgs[3]); // Order 5804 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5805 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5806 break; 5807 case C11CmpXchg: 5808 SubExprs.push_back(APIOrderedArgs[3]); // Order 5809 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5810 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5811 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5812 break; 5813 case GNUCmpXchg: 5814 SubExprs.push_back(APIOrderedArgs[4]); // Order 5815 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5816 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5817 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5818 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5819 break; 5820 } 5821 5822 if (SubExprs.size() >= 2 && Form != Init) { 5823 if (Optional<llvm::APSInt> Result = 5824 SubExprs[1]->getIntegerConstantExpr(Context)) 5825 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5826 Diag(SubExprs[1]->getBeginLoc(), 5827 diag::warn_atomic_op_has_invalid_memory_order) 5828 << SubExprs[1]->getSourceRange(); 5829 } 5830 5831 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5832 auto *Scope = Args[Args.size() - 1]; 5833 if (Optional<llvm::APSInt> Result = 5834 Scope->getIntegerConstantExpr(Context)) { 5835 if (!ScopeModel->isValid(Result->getZExtValue())) 5836 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5837 << Scope->getSourceRange(); 5838 } 5839 SubExprs.push_back(Scope); 5840 } 5841 5842 AtomicExpr *AE = new (Context) 5843 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5844 5845 if ((Op == AtomicExpr::AO__c11_atomic_load || 5846 Op == AtomicExpr::AO__c11_atomic_store || 5847 Op == AtomicExpr::AO__opencl_atomic_load || 5848 Op == AtomicExpr::AO__hip_atomic_load || 5849 Op == AtomicExpr::AO__opencl_atomic_store || 5850 Op == AtomicExpr::AO__hip_atomic_store) && 5851 Context.AtomicUsesUnsupportedLibcall(AE)) 5852 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5853 << ((Op == AtomicExpr::AO__c11_atomic_load || 5854 Op == AtomicExpr::AO__opencl_atomic_load || 5855 Op == AtomicExpr::AO__hip_atomic_load) 5856 ? 0 5857 : 1); 5858 5859 if (ValType->isBitIntType()) { 5860 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit); 5861 return ExprError(); 5862 } 5863 5864 return AE; 5865 } 5866 5867 /// checkBuiltinArgument - Given a call to a builtin function, perform 5868 /// normal type-checking on the given argument, updating the call in 5869 /// place. This is useful when a builtin function requires custom 5870 /// type-checking for some of its arguments but not necessarily all of 5871 /// them. 5872 /// 5873 /// Returns true on error. 5874 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5875 FunctionDecl *Fn = E->getDirectCallee(); 5876 assert(Fn && "builtin call without direct callee!"); 5877 5878 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5879 InitializedEntity Entity = 5880 InitializedEntity::InitializeParameter(S.Context, Param); 5881 5882 ExprResult Arg = E->getArg(0); 5883 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5884 if (Arg.isInvalid()) 5885 return true; 5886 5887 E->setArg(ArgIndex, Arg.get()); 5888 return false; 5889 } 5890 5891 /// We have a call to a function like __sync_fetch_and_add, which is an 5892 /// overloaded function based on the pointer type of its first argument. 5893 /// The main BuildCallExpr routines have already promoted the types of 5894 /// arguments because all of these calls are prototyped as void(...). 5895 /// 5896 /// This function goes through and does final semantic checking for these 5897 /// builtins, as well as generating any warnings. 5898 ExprResult 5899 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5900 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5901 Expr *Callee = TheCall->getCallee(); 5902 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5903 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5904 5905 // Ensure that we have at least one argument to do type inference from. 5906 if (TheCall->getNumArgs() < 1) { 5907 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5908 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5909 return ExprError(); 5910 } 5911 5912 // Inspect the first argument of the atomic builtin. This should always be 5913 // a pointer type, whose element is an integral scalar or pointer type. 5914 // Because it is a pointer type, we don't have to worry about any implicit 5915 // casts here. 5916 // FIXME: We don't allow floating point scalars as input. 5917 Expr *FirstArg = TheCall->getArg(0); 5918 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5919 if (FirstArgResult.isInvalid()) 5920 return ExprError(); 5921 FirstArg = FirstArgResult.get(); 5922 TheCall->setArg(0, FirstArg); 5923 5924 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5925 if (!pointerType) { 5926 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5927 << FirstArg->getType() << FirstArg->getSourceRange(); 5928 return ExprError(); 5929 } 5930 5931 QualType ValType = pointerType->getPointeeType(); 5932 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5933 !ValType->isBlockPointerType()) { 5934 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5935 << FirstArg->getType() << FirstArg->getSourceRange(); 5936 return ExprError(); 5937 } 5938 5939 if (ValType.isConstQualified()) { 5940 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5941 << FirstArg->getType() << FirstArg->getSourceRange(); 5942 return ExprError(); 5943 } 5944 5945 switch (ValType.getObjCLifetime()) { 5946 case Qualifiers::OCL_None: 5947 case Qualifiers::OCL_ExplicitNone: 5948 // okay 5949 break; 5950 5951 case Qualifiers::OCL_Weak: 5952 case Qualifiers::OCL_Strong: 5953 case Qualifiers::OCL_Autoreleasing: 5954 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5955 << ValType << FirstArg->getSourceRange(); 5956 return ExprError(); 5957 } 5958 5959 // Strip any qualifiers off ValType. 5960 ValType = ValType.getUnqualifiedType(); 5961 5962 // The majority of builtins return a value, but a few have special return 5963 // types, so allow them to override appropriately below. 5964 QualType ResultType = ValType; 5965 5966 // We need to figure out which concrete builtin this maps onto. For example, 5967 // __sync_fetch_and_add with a 2 byte object turns into 5968 // __sync_fetch_and_add_2. 5969 #define BUILTIN_ROW(x) \ 5970 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5971 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5972 5973 static const unsigned BuiltinIndices[][5] = { 5974 BUILTIN_ROW(__sync_fetch_and_add), 5975 BUILTIN_ROW(__sync_fetch_and_sub), 5976 BUILTIN_ROW(__sync_fetch_and_or), 5977 BUILTIN_ROW(__sync_fetch_and_and), 5978 BUILTIN_ROW(__sync_fetch_and_xor), 5979 BUILTIN_ROW(__sync_fetch_and_nand), 5980 5981 BUILTIN_ROW(__sync_add_and_fetch), 5982 BUILTIN_ROW(__sync_sub_and_fetch), 5983 BUILTIN_ROW(__sync_and_and_fetch), 5984 BUILTIN_ROW(__sync_or_and_fetch), 5985 BUILTIN_ROW(__sync_xor_and_fetch), 5986 BUILTIN_ROW(__sync_nand_and_fetch), 5987 5988 BUILTIN_ROW(__sync_val_compare_and_swap), 5989 BUILTIN_ROW(__sync_bool_compare_and_swap), 5990 BUILTIN_ROW(__sync_lock_test_and_set), 5991 BUILTIN_ROW(__sync_lock_release), 5992 BUILTIN_ROW(__sync_swap) 5993 }; 5994 #undef BUILTIN_ROW 5995 5996 // Determine the index of the size. 5997 unsigned SizeIndex; 5998 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5999 case 1: SizeIndex = 0; break; 6000 case 2: SizeIndex = 1; break; 6001 case 4: SizeIndex = 2; break; 6002 case 8: SizeIndex = 3; break; 6003 case 16: SizeIndex = 4; break; 6004 default: 6005 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 6006 << FirstArg->getType() << FirstArg->getSourceRange(); 6007 return ExprError(); 6008 } 6009 6010 // Each of these builtins has one pointer argument, followed by some number of 6011 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 6012 // that we ignore. Find out which row of BuiltinIndices to read from as well 6013 // as the number of fixed args. 6014 unsigned BuiltinID = FDecl->getBuiltinID(); 6015 unsigned BuiltinIndex, NumFixed = 1; 6016 bool WarnAboutSemanticsChange = false; 6017 switch (BuiltinID) { 6018 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 6019 case Builtin::BI__sync_fetch_and_add: 6020 case Builtin::BI__sync_fetch_and_add_1: 6021 case Builtin::BI__sync_fetch_and_add_2: 6022 case Builtin::BI__sync_fetch_and_add_4: 6023 case Builtin::BI__sync_fetch_and_add_8: 6024 case Builtin::BI__sync_fetch_and_add_16: 6025 BuiltinIndex = 0; 6026 break; 6027 6028 case Builtin::BI__sync_fetch_and_sub: 6029 case Builtin::BI__sync_fetch_and_sub_1: 6030 case Builtin::BI__sync_fetch_and_sub_2: 6031 case Builtin::BI__sync_fetch_and_sub_4: 6032 case Builtin::BI__sync_fetch_and_sub_8: 6033 case Builtin::BI__sync_fetch_and_sub_16: 6034 BuiltinIndex = 1; 6035 break; 6036 6037 case Builtin::BI__sync_fetch_and_or: 6038 case Builtin::BI__sync_fetch_and_or_1: 6039 case Builtin::BI__sync_fetch_and_or_2: 6040 case Builtin::BI__sync_fetch_and_or_4: 6041 case Builtin::BI__sync_fetch_and_or_8: 6042 case Builtin::BI__sync_fetch_and_or_16: 6043 BuiltinIndex = 2; 6044 break; 6045 6046 case Builtin::BI__sync_fetch_and_and: 6047 case Builtin::BI__sync_fetch_and_and_1: 6048 case Builtin::BI__sync_fetch_and_and_2: 6049 case Builtin::BI__sync_fetch_and_and_4: 6050 case Builtin::BI__sync_fetch_and_and_8: 6051 case Builtin::BI__sync_fetch_and_and_16: 6052 BuiltinIndex = 3; 6053 break; 6054 6055 case Builtin::BI__sync_fetch_and_xor: 6056 case Builtin::BI__sync_fetch_and_xor_1: 6057 case Builtin::BI__sync_fetch_and_xor_2: 6058 case Builtin::BI__sync_fetch_and_xor_4: 6059 case Builtin::BI__sync_fetch_and_xor_8: 6060 case Builtin::BI__sync_fetch_and_xor_16: 6061 BuiltinIndex = 4; 6062 break; 6063 6064 case Builtin::BI__sync_fetch_and_nand: 6065 case Builtin::BI__sync_fetch_and_nand_1: 6066 case Builtin::BI__sync_fetch_and_nand_2: 6067 case Builtin::BI__sync_fetch_and_nand_4: 6068 case Builtin::BI__sync_fetch_and_nand_8: 6069 case Builtin::BI__sync_fetch_and_nand_16: 6070 BuiltinIndex = 5; 6071 WarnAboutSemanticsChange = true; 6072 break; 6073 6074 case Builtin::BI__sync_add_and_fetch: 6075 case Builtin::BI__sync_add_and_fetch_1: 6076 case Builtin::BI__sync_add_and_fetch_2: 6077 case Builtin::BI__sync_add_and_fetch_4: 6078 case Builtin::BI__sync_add_and_fetch_8: 6079 case Builtin::BI__sync_add_and_fetch_16: 6080 BuiltinIndex = 6; 6081 break; 6082 6083 case Builtin::BI__sync_sub_and_fetch: 6084 case Builtin::BI__sync_sub_and_fetch_1: 6085 case Builtin::BI__sync_sub_and_fetch_2: 6086 case Builtin::BI__sync_sub_and_fetch_4: 6087 case Builtin::BI__sync_sub_and_fetch_8: 6088 case Builtin::BI__sync_sub_and_fetch_16: 6089 BuiltinIndex = 7; 6090 break; 6091 6092 case Builtin::BI__sync_and_and_fetch: 6093 case Builtin::BI__sync_and_and_fetch_1: 6094 case Builtin::BI__sync_and_and_fetch_2: 6095 case Builtin::BI__sync_and_and_fetch_4: 6096 case Builtin::BI__sync_and_and_fetch_8: 6097 case Builtin::BI__sync_and_and_fetch_16: 6098 BuiltinIndex = 8; 6099 break; 6100 6101 case Builtin::BI__sync_or_and_fetch: 6102 case Builtin::BI__sync_or_and_fetch_1: 6103 case Builtin::BI__sync_or_and_fetch_2: 6104 case Builtin::BI__sync_or_and_fetch_4: 6105 case Builtin::BI__sync_or_and_fetch_8: 6106 case Builtin::BI__sync_or_and_fetch_16: 6107 BuiltinIndex = 9; 6108 break; 6109 6110 case Builtin::BI__sync_xor_and_fetch: 6111 case Builtin::BI__sync_xor_and_fetch_1: 6112 case Builtin::BI__sync_xor_and_fetch_2: 6113 case Builtin::BI__sync_xor_and_fetch_4: 6114 case Builtin::BI__sync_xor_and_fetch_8: 6115 case Builtin::BI__sync_xor_and_fetch_16: 6116 BuiltinIndex = 10; 6117 break; 6118 6119 case Builtin::BI__sync_nand_and_fetch: 6120 case Builtin::BI__sync_nand_and_fetch_1: 6121 case Builtin::BI__sync_nand_and_fetch_2: 6122 case Builtin::BI__sync_nand_and_fetch_4: 6123 case Builtin::BI__sync_nand_and_fetch_8: 6124 case Builtin::BI__sync_nand_and_fetch_16: 6125 BuiltinIndex = 11; 6126 WarnAboutSemanticsChange = true; 6127 break; 6128 6129 case Builtin::BI__sync_val_compare_and_swap: 6130 case Builtin::BI__sync_val_compare_and_swap_1: 6131 case Builtin::BI__sync_val_compare_and_swap_2: 6132 case Builtin::BI__sync_val_compare_and_swap_4: 6133 case Builtin::BI__sync_val_compare_and_swap_8: 6134 case Builtin::BI__sync_val_compare_and_swap_16: 6135 BuiltinIndex = 12; 6136 NumFixed = 2; 6137 break; 6138 6139 case Builtin::BI__sync_bool_compare_and_swap: 6140 case Builtin::BI__sync_bool_compare_and_swap_1: 6141 case Builtin::BI__sync_bool_compare_and_swap_2: 6142 case Builtin::BI__sync_bool_compare_and_swap_4: 6143 case Builtin::BI__sync_bool_compare_and_swap_8: 6144 case Builtin::BI__sync_bool_compare_and_swap_16: 6145 BuiltinIndex = 13; 6146 NumFixed = 2; 6147 ResultType = Context.BoolTy; 6148 break; 6149 6150 case Builtin::BI__sync_lock_test_and_set: 6151 case Builtin::BI__sync_lock_test_and_set_1: 6152 case Builtin::BI__sync_lock_test_and_set_2: 6153 case Builtin::BI__sync_lock_test_and_set_4: 6154 case Builtin::BI__sync_lock_test_and_set_8: 6155 case Builtin::BI__sync_lock_test_and_set_16: 6156 BuiltinIndex = 14; 6157 break; 6158 6159 case Builtin::BI__sync_lock_release: 6160 case Builtin::BI__sync_lock_release_1: 6161 case Builtin::BI__sync_lock_release_2: 6162 case Builtin::BI__sync_lock_release_4: 6163 case Builtin::BI__sync_lock_release_8: 6164 case Builtin::BI__sync_lock_release_16: 6165 BuiltinIndex = 15; 6166 NumFixed = 0; 6167 ResultType = Context.VoidTy; 6168 break; 6169 6170 case Builtin::BI__sync_swap: 6171 case Builtin::BI__sync_swap_1: 6172 case Builtin::BI__sync_swap_2: 6173 case Builtin::BI__sync_swap_4: 6174 case Builtin::BI__sync_swap_8: 6175 case Builtin::BI__sync_swap_16: 6176 BuiltinIndex = 16; 6177 break; 6178 } 6179 6180 // Now that we know how many fixed arguments we expect, first check that we 6181 // have at least that many. 6182 if (TheCall->getNumArgs() < 1+NumFixed) { 6183 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6184 << 0 << 1 + NumFixed << TheCall->getNumArgs() 6185 << Callee->getSourceRange(); 6186 return ExprError(); 6187 } 6188 6189 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 6190 << Callee->getSourceRange(); 6191 6192 if (WarnAboutSemanticsChange) { 6193 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 6194 << Callee->getSourceRange(); 6195 } 6196 6197 // Get the decl for the concrete builtin from this, we can tell what the 6198 // concrete integer type we should convert to is. 6199 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 6200 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 6201 FunctionDecl *NewBuiltinDecl; 6202 if (NewBuiltinID == BuiltinID) 6203 NewBuiltinDecl = FDecl; 6204 else { 6205 // Perform builtin lookup to avoid redeclaring it. 6206 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 6207 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 6208 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 6209 assert(Res.getFoundDecl()); 6210 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 6211 if (!NewBuiltinDecl) 6212 return ExprError(); 6213 } 6214 6215 // The first argument --- the pointer --- has a fixed type; we 6216 // deduce the types of the rest of the arguments accordingly. Walk 6217 // the remaining arguments, converting them to the deduced value type. 6218 for (unsigned i = 0; i != NumFixed; ++i) { 6219 ExprResult Arg = TheCall->getArg(i+1); 6220 6221 // GCC does an implicit conversion to the pointer or integer ValType. This 6222 // can fail in some cases (1i -> int**), check for this error case now. 6223 // Initialize the argument. 6224 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6225 ValType, /*consume*/ false); 6226 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6227 if (Arg.isInvalid()) 6228 return ExprError(); 6229 6230 // Okay, we have something that *can* be converted to the right type. Check 6231 // to see if there is a potentially weird extension going on here. This can 6232 // happen when you do an atomic operation on something like an char* and 6233 // pass in 42. The 42 gets converted to char. This is even more strange 6234 // for things like 45.123 -> char, etc. 6235 // FIXME: Do this check. 6236 TheCall->setArg(i+1, Arg.get()); 6237 } 6238 6239 // Create a new DeclRefExpr to refer to the new decl. 6240 DeclRefExpr *NewDRE = DeclRefExpr::Create( 6241 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 6242 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 6243 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 6244 6245 // Set the callee in the CallExpr. 6246 // FIXME: This loses syntactic information. 6247 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 6248 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 6249 CK_BuiltinFnToFnPtr); 6250 TheCall->setCallee(PromotedCall.get()); 6251 6252 // Change the result type of the call to match the original value type. This 6253 // is arbitrary, but the codegen for these builtins ins design to handle it 6254 // gracefully. 6255 TheCall->setType(ResultType); 6256 6257 // Prohibit problematic uses of bit-precise integer types with atomic 6258 // builtins. The arguments would have already been converted to the first 6259 // argument's type, so only need to check the first argument. 6260 const auto *BitIntValType = ValType->getAs<BitIntType>(); 6261 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) { 6262 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 6263 return ExprError(); 6264 } 6265 6266 return TheCallResult; 6267 } 6268 6269 /// SemaBuiltinNontemporalOverloaded - We have a call to 6270 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 6271 /// overloaded function based on the pointer type of its last argument. 6272 /// 6273 /// This function goes through and does final semantic checking for these 6274 /// builtins. 6275 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 6276 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 6277 DeclRefExpr *DRE = 6278 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6279 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6280 unsigned BuiltinID = FDecl->getBuiltinID(); 6281 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 6282 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 6283 "Unexpected nontemporal load/store builtin!"); 6284 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 6285 unsigned numArgs = isStore ? 2 : 1; 6286 6287 // Ensure that we have the proper number of arguments. 6288 if (checkArgCount(*this, TheCall, numArgs)) 6289 return ExprError(); 6290 6291 // Inspect the last argument of the nontemporal builtin. This should always 6292 // be a pointer type, from which we imply the type of the memory access. 6293 // Because it is a pointer type, we don't have to worry about any implicit 6294 // casts here. 6295 Expr *PointerArg = TheCall->getArg(numArgs - 1); 6296 ExprResult PointerArgResult = 6297 DefaultFunctionArrayLvalueConversion(PointerArg); 6298 6299 if (PointerArgResult.isInvalid()) 6300 return ExprError(); 6301 PointerArg = PointerArgResult.get(); 6302 TheCall->setArg(numArgs - 1, PointerArg); 6303 6304 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 6305 if (!pointerType) { 6306 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 6307 << PointerArg->getType() << PointerArg->getSourceRange(); 6308 return ExprError(); 6309 } 6310 6311 QualType ValType = pointerType->getPointeeType(); 6312 6313 // Strip any qualifiers off ValType. 6314 ValType = ValType.getUnqualifiedType(); 6315 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6316 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 6317 !ValType->isVectorType()) { 6318 Diag(DRE->getBeginLoc(), 6319 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 6320 << PointerArg->getType() << PointerArg->getSourceRange(); 6321 return ExprError(); 6322 } 6323 6324 if (!isStore) { 6325 TheCall->setType(ValType); 6326 return TheCallResult; 6327 } 6328 6329 ExprResult ValArg = TheCall->getArg(0); 6330 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6331 Context, ValType, /*consume*/ false); 6332 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 6333 if (ValArg.isInvalid()) 6334 return ExprError(); 6335 6336 TheCall->setArg(0, ValArg.get()); 6337 TheCall->setType(Context.VoidTy); 6338 return TheCallResult; 6339 } 6340 6341 /// CheckObjCString - Checks that the argument to the builtin 6342 /// CFString constructor is correct 6343 /// Note: It might also make sense to do the UTF-16 conversion here (would 6344 /// simplify the backend). 6345 bool Sema::CheckObjCString(Expr *Arg) { 6346 Arg = Arg->IgnoreParenCasts(); 6347 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 6348 6349 if (!Literal || !Literal->isAscii()) { 6350 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 6351 << Arg->getSourceRange(); 6352 return true; 6353 } 6354 6355 if (Literal->containsNonAsciiOrNull()) { 6356 StringRef String = Literal->getString(); 6357 unsigned NumBytes = String.size(); 6358 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6359 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6360 llvm::UTF16 *ToPtr = &ToBuf[0]; 6361 6362 llvm::ConversionResult Result = 6363 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6364 ToPtr + NumBytes, llvm::strictConversion); 6365 // Check for conversion failure. 6366 if (Result != llvm::conversionOK) 6367 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6368 << Arg->getSourceRange(); 6369 } 6370 return false; 6371 } 6372 6373 /// CheckObjCString - Checks that the format string argument to the os_log() 6374 /// and os_trace() functions is correct, and converts it to const char *. 6375 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6376 Arg = Arg->IgnoreParenCasts(); 6377 auto *Literal = dyn_cast<StringLiteral>(Arg); 6378 if (!Literal) { 6379 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6380 Literal = ObjcLiteral->getString(); 6381 } 6382 } 6383 6384 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6385 return ExprError( 6386 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 6387 << Arg->getSourceRange()); 6388 } 6389 6390 ExprResult Result(Literal); 6391 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 6392 InitializedEntity Entity = 6393 InitializedEntity::InitializeParameter(Context, ResultTy, false); 6394 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 6395 return Result; 6396 } 6397 6398 /// Check that the user is calling the appropriate va_start builtin for the 6399 /// target and calling convention. 6400 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 6401 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 6402 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 6403 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 6404 TT.getArch() == llvm::Triple::aarch64_32); 6405 bool IsWindows = TT.isOSWindows(); 6406 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 6407 if (IsX64 || IsAArch64) { 6408 CallingConv CC = CC_C; 6409 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 6410 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 6411 if (IsMSVAStart) { 6412 // Don't allow this in System V ABI functions. 6413 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 6414 return S.Diag(Fn->getBeginLoc(), 6415 diag::err_ms_va_start_used_in_sysv_function); 6416 } else { 6417 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 6418 // On x64 Windows, don't allow this in System V ABI functions. 6419 // (Yes, that means there's no corresponding way to support variadic 6420 // System V ABI functions on Windows.) 6421 if ((IsWindows && CC == CC_X86_64SysV) || 6422 (!IsWindows && CC == CC_Win64)) 6423 return S.Diag(Fn->getBeginLoc(), 6424 diag::err_va_start_used_in_wrong_abi_function) 6425 << !IsWindows; 6426 } 6427 return false; 6428 } 6429 6430 if (IsMSVAStart) 6431 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 6432 return false; 6433 } 6434 6435 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 6436 ParmVarDecl **LastParam = nullptr) { 6437 // Determine whether the current function, block, or obj-c method is variadic 6438 // and get its parameter list. 6439 bool IsVariadic = false; 6440 ArrayRef<ParmVarDecl *> Params; 6441 DeclContext *Caller = S.CurContext; 6442 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 6443 IsVariadic = Block->isVariadic(); 6444 Params = Block->parameters(); 6445 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 6446 IsVariadic = FD->isVariadic(); 6447 Params = FD->parameters(); 6448 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 6449 IsVariadic = MD->isVariadic(); 6450 // FIXME: This isn't correct for methods (results in bogus warning). 6451 Params = MD->parameters(); 6452 } else if (isa<CapturedDecl>(Caller)) { 6453 // We don't support va_start in a CapturedDecl. 6454 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 6455 return true; 6456 } else { 6457 // This must be some other declcontext that parses exprs. 6458 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 6459 return true; 6460 } 6461 6462 if (!IsVariadic) { 6463 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 6464 return true; 6465 } 6466 6467 if (LastParam) 6468 *LastParam = Params.empty() ? nullptr : Params.back(); 6469 6470 return false; 6471 } 6472 6473 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 6474 /// for validity. Emit an error and return true on failure; return false 6475 /// on success. 6476 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 6477 Expr *Fn = TheCall->getCallee(); 6478 6479 if (checkVAStartABI(*this, BuiltinID, Fn)) 6480 return true; 6481 6482 if (checkArgCount(*this, TheCall, 2)) 6483 return true; 6484 6485 // Type-check the first argument normally. 6486 if (checkBuiltinArgument(*this, TheCall, 0)) 6487 return true; 6488 6489 // Check that the current function is variadic, and get its last parameter. 6490 ParmVarDecl *LastParam; 6491 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6492 return true; 6493 6494 // Verify that the second argument to the builtin is the last argument of the 6495 // current function or method. 6496 bool SecondArgIsLastNamedArgument = false; 6497 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6498 6499 // These are valid if SecondArgIsLastNamedArgument is false after the next 6500 // block. 6501 QualType Type; 6502 SourceLocation ParamLoc; 6503 bool IsCRegister = false; 6504 6505 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6506 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6507 SecondArgIsLastNamedArgument = PV == LastParam; 6508 6509 Type = PV->getType(); 6510 ParamLoc = PV->getLocation(); 6511 IsCRegister = 6512 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6513 } 6514 } 6515 6516 if (!SecondArgIsLastNamedArgument) 6517 Diag(TheCall->getArg(1)->getBeginLoc(), 6518 diag::warn_second_arg_of_va_start_not_last_named_param); 6519 else if (IsCRegister || Type->isReferenceType() || 6520 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6521 // Promotable integers are UB, but enumerations need a bit of 6522 // extra checking to see what their promotable type actually is. 6523 if (!Type->isPromotableIntegerType()) 6524 return false; 6525 if (!Type->isEnumeralType()) 6526 return true; 6527 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6528 return !(ED && 6529 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6530 }()) { 6531 unsigned Reason = 0; 6532 if (Type->isReferenceType()) Reason = 1; 6533 else if (IsCRegister) Reason = 2; 6534 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6535 Diag(ParamLoc, diag::note_parameter_type) << Type; 6536 } 6537 6538 TheCall->setType(Context.VoidTy); 6539 return false; 6540 } 6541 6542 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6543 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool { 6544 const LangOptions &LO = getLangOpts(); 6545 6546 if (LO.CPlusPlus) 6547 return Arg->getType() 6548 .getCanonicalType() 6549 .getTypePtr() 6550 ->getPointeeType() 6551 .withoutLocalFastQualifiers() == Context.CharTy; 6552 6553 // In C, allow aliasing through `char *`, this is required for AArch64 at 6554 // least. 6555 return true; 6556 }; 6557 6558 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6559 // const char *named_addr); 6560 6561 Expr *Func = Call->getCallee(); 6562 6563 if (Call->getNumArgs() < 3) 6564 return Diag(Call->getEndLoc(), 6565 diag::err_typecheck_call_too_few_args_at_least) 6566 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6567 6568 // Type-check the first argument normally. 6569 if (checkBuiltinArgument(*this, Call, 0)) 6570 return true; 6571 6572 // Check that the current function is variadic. 6573 if (checkVAStartIsInVariadicFunction(*this, Func)) 6574 return true; 6575 6576 // __va_start on Windows does not validate the parameter qualifiers 6577 6578 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6579 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6580 6581 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6582 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6583 6584 const QualType &ConstCharPtrTy = 6585 Context.getPointerType(Context.CharTy.withConst()); 6586 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1)) 6587 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6588 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6589 << 0 /* qualifier difference */ 6590 << 3 /* parameter mismatch */ 6591 << 2 << Arg1->getType() << ConstCharPtrTy; 6592 6593 const QualType SizeTy = Context.getSizeType(); 6594 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6595 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6596 << Arg2->getType() << SizeTy << 1 /* different class */ 6597 << 0 /* qualifier difference */ 6598 << 3 /* parameter mismatch */ 6599 << 3 << Arg2->getType() << SizeTy; 6600 6601 return false; 6602 } 6603 6604 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6605 /// friends. This is declared to take (...), so we have to check everything. 6606 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6607 if (checkArgCount(*this, TheCall, 2)) 6608 return true; 6609 6610 ExprResult OrigArg0 = TheCall->getArg(0); 6611 ExprResult OrigArg1 = TheCall->getArg(1); 6612 6613 // Do standard promotions between the two arguments, returning their common 6614 // type. 6615 QualType Res = UsualArithmeticConversions( 6616 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6617 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6618 return true; 6619 6620 // Make sure any conversions are pushed back into the call; this is 6621 // type safe since unordered compare builtins are declared as "_Bool 6622 // foo(...)". 6623 TheCall->setArg(0, OrigArg0.get()); 6624 TheCall->setArg(1, OrigArg1.get()); 6625 6626 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6627 return false; 6628 6629 // If the common type isn't a real floating type, then the arguments were 6630 // invalid for this operation. 6631 if (Res.isNull() || !Res->isRealFloatingType()) 6632 return Diag(OrigArg0.get()->getBeginLoc(), 6633 diag::err_typecheck_call_invalid_ordered_compare) 6634 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6635 << SourceRange(OrigArg0.get()->getBeginLoc(), 6636 OrigArg1.get()->getEndLoc()); 6637 6638 return false; 6639 } 6640 6641 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6642 /// __builtin_isnan and friends. This is declared to take (...), so we have 6643 /// to check everything. We expect the last argument to be a floating point 6644 /// value. 6645 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6646 if (checkArgCount(*this, TheCall, NumArgs)) 6647 return true; 6648 6649 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6650 // on all preceding parameters just being int. Try all of those. 6651 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6652 Expr *Arg = TheCall->getArg(i); 6653 6654 if (Arg->isTypeDependent()) 6655 return false; 6656 6657 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6658 6659 if (Res.isInvalid()) 6660 return true; 6661 TheCall->setArg(i, Res.get()); 6662 } 6663 6664 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6665 6666 if (OrigArg->isTypeDependent()) 6667 return false; 6668 6669 // Usual Unary Conversions will convert half to float, which we want for 6670 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6671 // type how it is, but do normal L->Rvalue conversions. 6672 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6673 OrigArg = UsualUnaryConversions(OrigArg).get(); 6674 else 6675 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6676 TheCall->setArg(NumArgs - 1, OrigArg); 6677 6678 // This operation requires a non-_Complex floating-point number. 6679 if (!OrigArg->getType()->isRealFloatingType()) 6680 return Diag(OrigArg->getBeginLoc(), 6681 diag::err_typecheck_call_invalid_unary_fp) 6682 << OrigArg->getType() << OrigArg->getSourceRange(); 6683 6684 return false; 6685 } 6686 6687 /// Perform semantic analysis for a call to __builtin_complex. 6688 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6689 if (checkArgCount(*this, TheCall, 2)) 6690 return true; 6691 6692 bool Dependent = false; 6693 for (unsigned I = 0; I != 2; ++I) { 6694 Expr *Arg = TheCall->getArg(I); 6695 QualType T = Arg->getType(); 6696 if (T->isDependentType()) { 6697 Dependent = true; 6698 continue; 6699 } 6700 6701 // Despite supporting _Complex int, GCC requires a real floating point type 6702 // for the operands of __builtin_complex. 6703 if (!T->isRealFloatingType()) { 6704 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6705 << Arg->getType() << Arg->getSourceRange(); 6706 } 6707 6708 ExprResult Converted = DefaultLvalueConversion(Arg); 6709 if (Converted.isInvalid()) 6710 return true; 6711 TheCall->setArg(I, Converted.get()); 6712 } 6713 6714 if (Dependent) { 6715 TheCall->setType(Context.DependentTy); 6716 return false; 6717 } 6718 6719 Expr *Real = TheCall->getArg(0); 6720 Expr *Imag = TheCall->getArg(1); 6721 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6722 return Diag(Real->getBeginLoc(), 6723 diag::err_typecheck_call_different_arg_types) 6724 << Real->getType() << Imag->getType() 6725 << Real->getSourceRange() << Imag->getSourceRange(); 6726 } 6727 6728 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6729 // don't allow this builtin to form those types either. 6730 // FIXME: Should we allow these types? 6731 if (Real->getType()->isFloat16Type()) 6732 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6733 << "_Float16"; 6734 if (Real->getType()->isHalfType()) 6735 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6736 << "half"; 6737 6738 TheCall->setType(Context.getComplexType(Real->getType())); 6739 return false; 6740 } 6741 6742 // Customized Sema Checking for VSX builtins that have the following signature: 6743 // vector [...] builtinName(vector [...], vector [...], const int); 6744 // Which takes the same type of vectors (any legal vector type) for the first 6745 // two arguments and takes compile time constant for the third argument. 6746 // Example builtins are : 6747 // vector double vec_xxpermdi(vector double, vector double, int); 6748 // vector short vec_xxsldwi(vector short, vector short, int); 6749 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6750 unsigned ExpectedNumArgs = 3; 6751 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6752 return true; 6753 6754 // Check the third argument is a compile time constant 6755 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6756 return Diag(TheCall->getBeginLoc(), 6757 diag::err_vsx_builtin_nonconstant_argument) 6758 << 3 /* argument index */ << TheCall->getDirectCallee() 6759 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6760 TheCall->getArg(2)->getEndLoc()); 6761 6762 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6763 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6764 6765 // Check the type of argument 1 and argument 2 are vectors. 6766 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6767 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6768 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6769 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6770 << TheCall->getDirectCallee() 6771 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6772 TheCall->getArg(1)->getEndLoc()); 6773 } 6774 6775 // Check the first two arguments are the same type. 6776 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6777 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6778 << TheCall->getDirectCallee() 6779 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6780 TheCall->getArg(1)->getEndLoc()); 6781 } 6782 6783 // When default clang type checking is turned off and the customized type 6784 // checking is used, the returning type of the function must be explicitly 6785 // set. Otherwise it is _Bool by default. 6786 TheCall->setType(Arg1Ty); 6787 6788 return false; 6789 } 6790 6791 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6792 // This is declared to take (...), so we have to check everything. 6793 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6794 if (TheCall->getNumArgs() < 2) 6795 return ExprError(Diag(TheCall->getEndLoc(), 6796 diag::err_typecheck_call_too_few_args_at_least) 6797 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6798 << TheCall->getSourceRange()); 6799 6800 // Determine which of the following types of shufflevector we're checking: 6801 // 1) unary, vector mask: (lhs, mask) 6802 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6803 QualType resType = TheCall->getArg(0)->getType(); 6804 unsigned numElements = 0; 6805 6806 if (!TheCall->getArg(0)->isTypeDependent() && 6807 !TheCall->getArg(1)->isTypeDependent()) { 6808 QualType LHSType = TheCall->getArg(0)->getType(); 6809 QualType RHSType = TheCall->getArg(1)->getType(); 6810 6811 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6812 return ExprError( 6813 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6814 << TheCall->getDirectCallee() 6815 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6816 TheCall->getArg(1)->getEndLoc())); 6817 6818 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6819 unsigned numResElements = TheCall->getNumArgs() - 2; 6820 6821 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6822 // with mask. If so, verify that RHS is an integer vector type with the 6823 // same number of elts as lhs. 6824 if (TheCall->getNumArgs() == 2) { 6825 if (!RHSType->hasIntegerRepresentation() || 6826 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6827 return ExprError(Diag(TheCall->getBeginLoc(), 6828 diag::err_vec_builtin_incompatible_vector) 6829 << TheCall->getDirectCallee() 6830 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6831 TheCall->getArg(1)->getEndLoc())); 6832 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6833 return ExprError(Diag(TheCall->getBeginLoc(), 6834 diag::err_vec_builtin_incompatible_vector) 6835 << TheCall->getDirectCallee() 6836 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6837 TheCall->getArg(1)->getEndLoc())); 6838 } else if (numElements != numResElements) { 6839 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6840 resType = Context.getVectorType(eltType, numResElements, 6841 VectorType::GenericVector); 6842 } 6843 } 6844 6845 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6846 if (TheCall->getArg(i)->isTypeDependent() || 6847 TheCall->getArg(i)->isValueDependent()) 6848 continue; 6849 6850 Optional<llvm::APSInt> Result; 6851 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6852 return ExprError(Diag(TheCall->getBeginLoc(), 6853 diag::err_shufflevector_nonconstant_argument) 6854 << TheCall->getArg(i)->getSourceRange()); 6855 6856 // Allow -1 which will be translated to undef in the IR. 6857 if (Result->isSigned() && Result->isAllOnes()) 6858 continue; 6859 6860 if (Result->getActiveBits() > 64 || 6861 Result->getZExtValue() >= numElements * 2) 6862 return ExprError(Diag(TheCall->getBeginLoc(), 6863 diag::err_shufflevector_argument_too_large) 6864 << TheCall->getArg(i)->getSourceRange()); 6865 } 6866 6867 SmallVector<Expr*, 32> exprs; 6868 6869 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6870 exprs.push_back(TheCall->getArg(i)); 6871 TheCall->setArg(i, nullptr); 6872 } 6873 6874 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6875 TheCall->getCallee()->getBeginLoc(), 6876 TheCall->getRParenLoc()); 6877 } 6878 6879 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6880 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6881 SourceLocation BuiltinLoc, 6882 SourceLocation RParenLoc) { 6883 ExprValueKind VK = VK_PRValue; 6884 ExprObjectKind OK = OK_Ordinary; 6885 QualType DstTy = TInfo->getType(); 6886 QualType SrcTy = E->getType(); 6887 6888 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6889 return ExprError(Diag(BuiltinLoc, 6890 diag::err_convertvector_non_vector) 6891 << E->getSourceRange()); 6892 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6893 return ExprError(Diag(BuiltinLoc, 6894 diag::err_convertvector_non_vector_type)); 6895 6896 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6897 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6898 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6899 if (SrcElts != DstElts) 6900 return ExprError(Diag(BuiltinLoc, 6901 diag::err_convertvector_incompatible_vector) 6902 << E->getSourceRange()); 6903 } 6904 6905 return new (Context) 6906 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6907 } 6908 6909 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6910 // This is declared to take (const void*, ...) and can take two 6911 // optional constant int args. 6912 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6913 unsigned NumArgs = TheCall->getNumArgs(); 6914 6915 if (NumArgs > 3) 6916 return Diag(TheCall->getEndLoc(), 6917 diag::err_typecheck_call_too_many_args_at_most) 6918 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6919 6920 // Argument 0 is checked for us and the remaining arguments must be 6921 // constant integers. 6922 for (unsigned i = 1; i != NumArgs; ++i) 6923 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6924 return true; 6925 6926 return false; 6927 } 6928 6929 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 6930 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 6931 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 6932 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 6933 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6934 if (checkArgCount(*this, TheCall, 1)) 6935 return true; 6936 Expr *Arg = TheCall->getArg(0); 6937 if (Arg->isInstantiationDependent()) 6938 return false; 6939 6940 QualType ArgTy = Arg->getType(); 6941 if (!ArgTy->hasFloatingRepresentation()) 6942 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 6943 << ArgTy; 6944 if (Arg->isLValue()) { 6945 ExprResult FirstArg = DefaultLvalueConversion(Arg); 6946 TheCall->setArg(0, FirstArg.get()); 6947 } 6948 TheCall->setType(TheCall->getArg(0)->getType()); 6949 return false; 6950 } 6951 6952 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6953 // __assume does not evaluate its arguments, and should warn if its argument 6954 // has side effects. 6955 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6956 Expr *Arg = TheCall->getArg(0); 6957 if (Arg->isInstantiationDependent()) return false; 6958 6959 if (Arg->HasSideEffects(Context)) 6960 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6961 << Arg->getSourceRange() 6962 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6963 6964 return false; 6965 } 6966 6967 /// Handle __builtin_alloca_with_align. This is declared 6968 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6969 /// than 8. 6970 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6971 // The alignment must be a constant integer. 6972 Expr *Arg = TheCall->getArg(1); 6973 6974 // We can't check the value of a dependent argument. 6975 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6976 if (const auto *UE = 6977 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6978 if (UE->getKind() == UETT_AlignOf || 6979 UE->getKind() == UETT_PreferredAlignOf) 6980 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6981 << Arg->getSourceRange(); 6982 6983 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6984 6985 if (!Result.isPowerOf2()) 6986 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6987 << Arg->getSourceRange(); 6988 6989 if (Result < Context.getCharWidth()) 6990 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6991 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6992 6993 if (Result > std::numeric_limits<int32_t>::max()) 6994 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6995 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6996 } 6997 6998 return false; 6999 } 7000 7001 /// Handle __builtin_assume_aligned. This is declared 7002 /// as (const void*, size_t, ...) and can take one optional constant int arg. 7003 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 7004 unsigned NumArgs = TheCall->getNumArgs(); 7005 7006 if (NumArgs > 3) 7007 return Diag(TheCall->getEndLoc(), 7008 diag::err_typecheck_call_too_many_args_at_most) 7009 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 7010 7011 // The alignment must be a constant integer. 7012 Expr *Arg = TheCall->getArg(1); 7013 7014 // We can't check the value of a dependent argument. 7015 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 7016 llvm::APSInt Result; 7017 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7018 return true; 7019 7020 if (!Result.isPowerOf2()) 7021 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 7022 << Arg->getSourceRange(); 7023 7024 if (Result > Sema::MaximumAlignment) 7025 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 7026 << Arg->getSourceRange() << Sema::MaximumAlignment; 7027 } 7028 7029 if (NumArgs > 2) { 7030 ExprResult Arg(TheCall->getArg(2)); 7031 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 7032 Context.getSizeType(), false); 7033 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 7034 if (Arg.isInvalid()) return true; 7035 TheCall->setArg(2, Arg.get()); 7036 } 7037 7038 return false; 7039 } 7040 7041 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 7042 unsigned BuiltinID = 7043 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 7044 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 7045 7046 unsigned NumArgs = TheCall->getNumArgs(); 7047 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 7048 if (NumArgs < NumRequiredArgs) { 7049 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 7050 << 0 /* function call */ << NumRequiredArgs << NumArgs 7051 << TheCall->getSourceRange(); 7052 } 7053 if (NumArgs >= NumRequiredArgs + 0x100) { 7054 return Diag(TheCall->getEndLoc(), 7055 diag::err_typecheck_call_too_many_args_at_most) 7056 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 7057 << TheCall->getSourceRange(); 7058 } 7059 unsigned i = 0; 7060 7061 // For formatting call, check buffer arg. 7062 if (!IsSizeCall) { 7063 ExprResult Arg(TheCall->getArg(i)); 7064 InitializedEntity Entity = InitializedEntity::InitializeParameter( 7065 Context, Context.VoidPtrTy, false); 7066 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 7067 if (Arg.isInvalid()) 7068 return true; 7069 TheCall->setArg(i, Arg.get()); 7070 i++; 7071 } 7072 7073 // Check string literal arg. 7074 unsigned FormatIdx = i; 7075 { 7076 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 7077 if (Arg.isInvalid()) 7078 return true; 7079 TheCall->setArg(i, Arg.get()); 7080 i++; 7081 } 7082 7083 // Make sure variadic args are scalar. 7084 unsigned FirstDataArg = i; 7085 while (i < NumArgs) { 7086 ExprResult Arg = DefaultVariadicArgumentPromotion( 7087 TheCall->getArg(i), VariadicFunction, nullptr); 7088 if (Arg.isInvalid()) 7089 return true; 7090 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 7091 if (ArgSize.getQuantity() >= 0x100) { 7092 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 7093 << i << (int)ArgSize.getQuantity() << 0xff 7094 << TheCall->getSourceRange(); 7095 } 7096 TheCall->setArg(i, Arg.get()); 7097 i++; 7098 } 7099 7100 // Check formatting specifiers. NOTE: We're only doing this for the non-size 7101 // call to avoid duplicate diagnostics. 7102 if (!IsSizeCall) { 7103 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 7104 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 7105 bool Success = CheckFormatArguments( 7106 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 7107 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 7108 CheckedVarArgs); 7109 if (!Success) 7110 return true; 7111 } 7112 7113 if (IsSizeCall) { 7114 TheCall->setType(Context.getSizeType()); 7115 } else { 7116 TheCall->setType(Context.VoidPtrTy); 7117 } 7118 return false; 7119 } 7120 7121 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 7122 /// TheCall is a constant expression. 7123 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 7124 llvm::APSInt &Result) { 7125 Expr *Arg = TheCall->getArg(ArgNum); 7126 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 7127 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 7128 7129 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 7130 7131 Optional<llvm::APSInt> R; 7132 if (!(R = Arg->getIntegerConstantExpr(Context))) 7133 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 7134 << FDecl->getDeclName() << Arg->getSourceRange(); 7135 Result = *R; 7136 return false; 7137 } 7138 7139 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 7140 /// TheCall is a constant expression in the range [Low, High]. 7141 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 7142 int Low, int High, bool RangeIsError) { 7143 if (isConstantEvaluated()) 7144 return false; 7145 llvm::APSInt Result; 7146 7147 // We can't check the value of a dependent argument. 7148 Expr *Arg = TheCall->getArg(ArgNum); 7149 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7150 return false; 7151 7152 // Check constant-ness first. 7153 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7154 return true; 7155 7156 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 7157 if (RangeIsError) 7158 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 7159 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 7160 else 7161 // Defer the warning until we know if the code will be emitted so that 7162 // dead code can ignore this. 7163 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 7164 PDiag(diag::warn_argument_invalid_range) 7165 << toString(Result, 10) << Low << High 7166 << Arg->getSourceRange()); 7167 } 7168 7169 return false; 7170 } 7171 7172 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 7173 /// TheCall is a constant expression is a multiple of Num.. 7174 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 7175 unsigned Num) { 7176 llvm::APSInt Result; 7177 7178 // We can't check the value of a dependent argument. 7179 Expr *Arg = TheCall->getArg(ArgNum); 7180 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7181 return false; 7182 7183 // Check constant-ness first. 7184 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7185 return true; 7186 7187 if (Result.getSExtValue() % Num != 0) 7188 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 7189 << Num << Arg->getSourceRange(); 7190 7191 return false; 7192 } 7193 7194 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 7195 /// constant expression representing a power of 2. 7196 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 7197 llvm::APSInt Result; 7198 7199 // We can't check the value of a dependent argument. 7200 Expr *Arg = TheCall->getArg(ArgNum); 7201 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7202 return false; 7203 7204 // Check constant-ness first. 7205 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7206 return true; 7207 7208 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 7209 // and only if x is a power of 2. 7210 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 7211 return false; 7212 7213 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 7214 << Arg->getSourceRange(); 7215 } 7216 7217 static bool IsShiftedByte(llvm::APSInt Value) { 7218 if (Value.isNegative()) 7219 return false; 7220 7221 // Check if it's a shifted byte, by shifting it down 7222 while (true) { 7223 // If the value fits in the bottom byte, the check passes. 7224 if (Value < 0x100) 7225 return true; 7226 7227 // Otherwise, if the value has _any_ bits in the bottom byte, the check 7228 // fails. 7229 if ((Value & 0xFF) != 0) 7230 return false; 7231 7232 // If the bottom 8 bits are all 0, but something above that is nonzero, 7233 // then shifting the value right by 8 bits won't affect whether it's a 7234 // shifted byte or not. So do that, and go round again. 7235 Value >>= 8; 7236 } 7237 } 7238 7239 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 7240 /// a constant expression representing an arbitrary byte value shifted left by 7241 /// a multiple of 8 bits. 7242 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 7243 unsigned ArgBits) { 7244 llvm::APSInt Result; 7245 7246 // We can't check the value of a dependent argument. 7247 Expr *Arg = TheCall->getArg(ArgNum); 7248 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7249 return false; 7250 7251 // Check constant-ness first. 7252 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7253 return true; 7254 7255 // Truncate to the given size. 7256 Result = Result.getLoBits(ArgBits); 7257 Result.setIsUnsigned(true); 7258 7259 if (IsShiftedByte(Result)) 7260 return false; 7261 7262 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 7263 << Arg->getSourceRange(); 7264 } 7265 7266 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 7267 /// TheCall is a constant expression representing either a shifted byte value, 7268 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 7269 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 7270 /// Arm MVE intrinsics. 7271 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 7272 int ArgNum, 7273 unsigned ArgBits) { 7274 llvm::APSInt Result; 7275 7276 // We can't check the value of a dependent argument. 7277 Expr *Arg = TheCall->getArg(ArgNum); 7278 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7279 return false; 7280 7281 // Check constant-ness first. 7282 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7283 return true; 7284 7285 // Truncate to the given size. 7286 Result = Result.getLoBits(ArgBits); 7287 Result.setIsUnsigned(true); 7288 7289 // Check to see if it's in either of the required forms. 7290 if (IsShiftedByte(Result) || 7291 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 7292 return false; 7293 7294 return Diag(TheCall->getBeginLoc(), 7295 diag::err_argument_not_shifted_byte_or_xxff) 7296 << Arg->getSourceRange(); 7297 } 7298 7299 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 7300 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 7301 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 7302 if (checkArgCount(*this, TheCall, 2)) 7303 return true; 7304 Expr *Arg0 = TheCall->getArg(0); 7305 Expr *Arg1 = TheCall->getArg(1); 7306 7307 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7308 if (FirstArg.isInvalid()) 7309 return true; 7310 QualType FirstArgType = FirstArg.get()->getType(); 7311 if (!FirstArgType->isAnyPointerType()) 7312 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7313 << "first" << FirstArgType << Arg0->getSourceRange(); 7314 TheCall->setArg(0, FirstArg.get()); 7315 7316 ExprResult SecArg = DefaultLvalueConversion(Arg1); 7317 if (SecArg.isInvalid()) 7318 return true; 7319 QualType SecArgType = SecArg.get()->getType(); 7320 if (!SecArgType->isIntegerType()) 7321 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7322 << "second" << SecArgType << Arg1->getSourceRange(); 7323 7324 // Derive the return type from the pointer argument. 7325 TheCall->setType(FirstArgType); 7326 return false; 7327 } 7328 7329 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 7330 if (checkArgCount(*this, TheCall, 2)) 7331 return true; 7332 7333 Expr *Arg0 = TheCall->getArg(0); 7334 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7335 if (FirstArg.isInvalid()) 7336 return true; 7337 QualType FirstArgType = FirstArg.get()->getType(); 7338 if (!FirstArgType->isAnyPointerType()) 7339 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7340 << "first" << FirstArgType << Arg0->getSourceRange(); 7341 TheCall->setArg(0, FirstArg.get()); 7342 7343 // Derive the return type from the pointer argument. 7344 TheCall->setType(FirstArgType); 7345 7346 // Second arg must be an constant in range [0,15] 7347 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7348 } 7349 7350 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 7351 if (checkArgCount(*this, TheCall, 2)) 7352 return true; 7353 Expr *Arg0 = TheCall->getArg(0); 7354 Expr *Arg1 = TheCall->getArg(1); 7355 7356 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7357 if (FirstArg.isInvalid()) 7358 return true; 7359 QualType FirstArgType = FirstArg.get()->getType(); 7360 if (!FirstArgType->isAnyPointerType()) 7361 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7362 << "first" << FirstArgType << Arg0->getSourceRange(); 7363 7364 QualType SecArgType = Arg1->getType(); 7365 if (!SecArgType->isIntegerType()) 7366 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7367 << "second" << SecArgType << Arg1->getSourceRange(); 7368 TheCall->setType(Context.IntTy); 7369 return false; 7370 } 7371 7372 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7373 BuiltinID == AArch64::BI__builtin_arm_stg) { 7374 if (checkArgCount(*this, TheCall, 1)) 7375 return true; 7376 Expr *Arg0 = TheCall->getArg(0); 7377 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7378 if (FirstArg.isInvalid()) 7379 return true; 7380 7381 QualType FirstArgType = FirstArg.get()->getType(); 7382 if (!FirstArgType->isAnyPointerType()) 7383 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7384 << "first" << FirstArgType << Arg0->getSourceRange(); 7385 TheCall->setArg(0, FirstArg.get()); 7386 7387 // Derive the return type from the pointer argument. 7388 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 7389 TheCall->setType(FirstArgType); 7390 return false; 7391 } 7392 7393 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 7394 Expr *ArgA = TheCall->getArg(0); 7395 Expr *ArgB = TheCall->getArg(1); 7396 7397 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 7398 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 7399 7400 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 7401 return true; 7402 7403 QualType ArgTypeA = ArgExprA.get()->getType(); 7404 QualType ArgTypeB = ArgExprB.get()->getType(); 7405 7406 auto isNull = [&] (Expr *E) -> bool { 7407 return E->isNullPointerConstant( 7408 Context, Expr::NPC_ValueDependentIsNotNull); }; 7409 7410 // argument should be either a pointer or null 7411 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 7412 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7413 << "first" << ArgTypeA << ArgA->getSourceRange(); 7414 7415 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 7416 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7417 << "second" << ArgTypeB << ArgB->getSourceRange(); 7418 7419 // Ensure Pointee types are compatible 7420 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 7421 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 7422 QualType pointeeA = ArgTypeA->getPointeeType(); 7423 QualType pointeeB = ArgTypeB->getPointeeType(); 7424 if (!Context.typesAreCompatible( 7425 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 7426 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 7427 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 7428 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 7429 << ArgB->getSourceRange(); 7430 } 7431 } 7432 7433 // at least one argument should be pointer type 7434 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 7435 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 7436 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 7437 7438 if (isNull(ArgA)) // adopt type of the other pointer 7439 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 7440 7441 if (isNull(ArgB)) 7442 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 7443 7444 TheCall->setArg(0, ArgExprA.get()); 7445 TheCall->setArg(1, ArgExprB.get()); 7446 TheCall->setType(Context.LongLongTy); 7447 return false; 7448 } 7449 assert(false && "Unhandled ARM MTE intrinsic"); 7450 return true; 7451 } 7452 7453 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 7454 /// TheCall is an ARM/AArch64 special register string literal. 7455 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 7456 int ArgNum, unsigned ExpectedFieldNum, 7457 bool AllowName) { 7458 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 7459 BuiltinID == ARM::BI__builtin_arm_wsr64 || 7460 BuiltinID == ARM::BI__builtin_arm_rsr || 7461 BuiltinID == ARM::BI__builtin_arm_rsrp || 7462 BuiltinID == ARM::BI__builtin_arm_wsr || 7463 BuiltinID == ARM::BI__builtin_arm_wsrp; 7464 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 7465 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 7466 BuiltinID == AArch64::BI__builtin_arm_rsr || 7467 BuiltinID == AArch64::BI__builtin_arm_rsrp || 7468 BuiltinID == AArch64::BI__builtin_arm_wsr || 7469 BuiltinID == AArch64::BI__builtin_arm_wsrp; 7470 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 7471 7472 // We can't check the value of a dependent argument. 7473 Expr *Arg = TheCall->getArg(ArgNum); 7474 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7475 return false; 7476 7477 // Check if the argument is a string literal. 7478 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 7479 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 7480 << Arg->getSourceRange(); 7481 7482 // Check the type of special register given. 7483 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 7484 SmallVector<StringRef, 6> Fields; 7485 Reg.split(Fields, ":"); 7486 7487 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 7488 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7489 << Arg->getSourceRange(); 7490 7491 // If the string is the name of a register then we cannot check that it is 7492 // valid here but if the string is of one the forms described in ACLE then we 7493 // can check that the supplied fields are integers and within the valid 7494 // ranges. 7495 if (Fields.size() > 1) { 7496 bool FiveFields = Fields.size() == 5; 7497 7498 bool ValidString = true; 7499 if (IsARMBuiltin) { 7500 ValidString &= Fields[0].startswith_insensitive("cp") || 7501 Fields[0].startswith_insensitive("p"); 7502 if (ValidString) 7503 Fields[0] = Fields[0].drop_front( 7504 Fields[0].startswith_insensitive("cp") ? 2 : 1); 7505 7506 ValidString &= Fields[2].startswith_insensitive("c"); 7507 if (ValidString) 7508 Fields[2] = Fields[2].drop_front(1); 7509 7510 if (FiveFields) { 7511 ValidString &= Fields[3].startswith_insensitive("c"); 7512 if (ValidString) 7513 Fields[3] = Fields[3].drop_front(1); 7514 } 7515 } 7516 7517 SmallVector<int, 5> Ranges; 7518 if (FiveFields) 7519 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 7520 else 7521 Ranges.append({15, 7, 15}); 7522 7523 for (unsigned i=0; i<Fields.size(); ++i) { 7524 int IntField; 7525 ValidString &= !Fields[i].getAsInteger(10, IntField); 7526 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7527 } 7528 7529 if (!ValidString) 7530 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7531 << Arg->getSourceRange(); 7532 } else if (IsAArch64Builtin && Fields.size() == 1) { 7533 // If the register name is one of those that appear in the condition below 7534 // and the special register builtin being used is one of the write builtins, 7535 // then we require that the argument provided for writing to the register 7536 // is an integer constant expression. This is because it will be lowered to 7537 // an MSR (immediate) instruction, so we need to know the immediate at 7538 // compile time. 7539 if (TheCall->getNumArgs() != 2) 7540 return false; 7541 7542 std::string RegLower = Reg.lower(); 7543 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7544 RegLower != "pan" && RegLower != "uao") 7545 return false; 7546 7547 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7548 } 7549 7550 return false; 7551 } 7552 7553 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7554 /// Emit an error and return true on failure; return false on success. 7555 /// TypeStr is a string containing the type descriptor of the value returned by 7556 /// the builtin and the descriptors of the expected type of the arguments. 7557 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID, 7558 const char *TypeStr) { 7559 7560 assert((TypeStr[0] != '\0') && 7561 "Invalid types in PPC MMA builtin declaration"); 7562 7563 switch (BuiltinID) { 7564 default: 7565 // This function is called in CheckPPCBuiltinFunctionCall where the 7566 // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here 7567 // we are isolating the pair vector memop builtins that can be used with mma 7568 // off so the default case is every builtin that requires mma and paired 7569 // vector memops. 7570 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7571 diag::err_ppc_builtin_only_on_arch, "10") || 7572 SemaFeatureCheck(*this, TheCall, "mma", 7573 diag::err_ppc_builtin_only_on_arch, "10")) 7574 return true; 7575 break; 7576 case PPC::BI__builtin_vsx_lxvp: 7577 case PPC::BI__builtin_vsx_stxvp: 7578 case PPC::BI__builtin_vsx_assemble_pair: 7579 case PPC::BI__builtin_vsx_disassemble_pair: 7580 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7581 diag::err_ppc_builtin_only_on_arch, "10")) 7582 return true; 7583 break; 7584 } 7585 7586 unsigned Mask = 0; 7587 unsigned ArgNum = 0; 7588 7589 // The first type in TypeStr is the type of the value returned by the 7590 // builtin. So we first read that type and change the type of TheCall. 7591 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7592 TheCall->setType(type); 7593 7594 while (*TypeStr != '\0') { 7595 Mask = 0; 7596 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7597 if (ArgNum >= TheCall->getNumArgs()) { 7598 ArgNum++; 7599 break; 7600 } 7601 7602 Expr *Arg = TheCall->getArg(ArgNum); 7603 QualType PassedType = Arg->getType(); 7604 QualType StrippedRVType = PassedType.getCanonicalType(); 7605 7606 // Strip Restrict/Volatile qualifiers. 7607 if (StrippedRVType.isRestrictQualified() || 7608 StrippedRVType.isVolatileQualified()) 7609 StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType(); 7610 7611 // The only case where the argument type and expected type are allowed to 7612 // mismatch is if the argument type is a non-void pointer (or array) and 7613 // expected type is a void pointer. 7614 if (StrippedRVType != ExpectedType) 7615 if (!(ExpectedType->isVoidPointerType() && 7616 (StrippedRVType->isPointerType() || StrippedRVType->isArrayType()))) 7617 return Diag(Arg->getBeginLoc(), 7618 diag::err_typecheck_convert_incompatible) 7619 << PassedType << ExpectedType << 1 << 0 << 0; 7620 7621 // If the value of the Mask is not 0, we have a constraint in the size of 7622 // the integer argument so here we ensure the argument is a constant that 7623 // is in the valid range. 7624 if (Mask != 0 && 7625 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7626 return true; 7627 7628 ArgNum++; 7629 } 7630 7631 // In case we exited early from the previous loop, there are other types to 7632 // read from TypeStr. So we need to read them all to ensure we have the right 7633 // number of arguments in TheCall and if it is not the case, to display a 7634 // better error message. 7635 while (*TypeStr != '\0') { 7636 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7637 ArgNum++; 7638 } 7639 if (checkArgCount(*this, TheCall, ArgNum)) 7640 return true; 7641 7642 return false; 7643 } 7644 7645 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7646 /// This checks that the target supports __builtin_longjmp and 7647 /// that val is a constant 1. 7648 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7649 if (!Context.getTargetInfo().hasSjLjLowering()) 7650 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7651 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7652 7653 Expr *Arg = TheCall->getArg(1); 7654 llvm::APSInt Result; 7655 7656 // TODO: This is less than ideal. Overload this to take a value. 7657 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7658 return true; 7659 7660 if (Result != 1) 7661 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7662 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7663 7664 return false; 7665 } 7666 7667 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7668 /// This checks that the target supports __builtin_setjmp. 7669 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7670 if (!Context.getTargetInfo().hasSjLjLowering()) 7671 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7672 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7673 return false; 7674 } 7675 7676 namespace { 7677 7678 class UncoveredArgHandler { 7679 enum { Unknown = -1, AllCovered = -2 }; 7680 7681 signed FirstUncoveredArg = Unknown; 7682 SmallVector<const Expr *, 4> DiagnosticExprs; 7683 7684 public: 7685 UncoveredArgHandler() = default; 7686 7687 bool hasUncoveredArg() const { 7688 return (FirstUncoveredArg >= 0); 7689 } 7690 7691 unsigned getUncoveredArg() const { 7692 assert(hasUncoveredArg() && "no uncovered argument"); 7693 return FirstUncoveredArg; 7694 } 7695 7696 void setAllCovered() { 7697 // A string has been found with all arguments covered, so clear out 7698 // the diagnostics. 7699 DiagnosticExprs.clear(); 7700 FirstUncoveredArg = AllCovered; 7701 } 7702 7703 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7704 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7705 7706 // Don't update if a previous string covers all arguments. 7707 if (FirstUncoveredArg == AllCovered) 7708 return; 7709 7710 // UncoveredArgHandler tracks the highest uncovered argument index 7711 // and with it all the strings that match this index. 7712 if (NewFirstUncoveredArg == FirstUncoveredArg) 7713 DiagnosticExprs.push_back(StrExpr); 7714 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7715 DiagnosticExprs.clear(); 7716 DiagnosticExprs.push_back(StrExpr); 7717 FirstUncoveredArg = NewFirstUncoveredArg; 7718 } 7719 } 7720 7721 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7722 }; 7723 7724 enum StringLiteralCheckType { 7725 SLCT_NotALiteral, 7726 SLCT_UncheckedLiteral, 7727 SLCT_CheckedLiteral 7728 }; 7729 7730 } // namespace 7731 7732 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7733 BinaryOperatorKind BinOpKind, 7734 bool AddendIsRight) { 7735 unsigned BitWidth = Offset.getBitWidth(); 7736 unsigned AddendBitWidth = Addend.getBitWidth(); 7737 // There might be negative interim results. 7738 if (Addend.isUnsigned()) { 7739 Addend = Addend.zext(++AddendBitWidth); 7740 Addend.setIsSigned(true); 7741 } 7742 // Adjust the bit width of the APSInts. 7743 if (AddendBitWidth > BitWidth) { 7744 Offset = Offset.sext(AddendBitWidth); 7745 BitWidth = AddendBitWidth; 7746 } else if (BitWidth > AddendBitWidth) { 7747 Addend = Addend.sext(BitWidth); 7748 } 7749 7750 bool Ov = false; 7751 llvm::APSInt ResOffset = Offset; 7752 if (BinOpKind == BO_Add) 7753 ResOffset = Offset.sadd_ov(Addend, Ov); 7754 else { 7755 assert(AddendIsRight && BinOpKind == BO_Sub && 7756 "operator must be add or sub with addend on the right"); 7757 ResOffset = Offset.ssub_ov(Addend, Ov); 7758 } 7759 7760 // We add an offset to a pointer here so we should support an offset as big as 7761 // possible. 7762 if (Ov) { 7763 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7764 "index (intermediate) result too big"); 7765 Offset = Offset.sext(2 * BitWidth); 7766 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7767 return; 7768 } 7769 7770 Offset = ResOffset; 7771 } 7772 7773 namespace { 7774 7775 // This is a wrapper class around StringLiteral to support offsetted string 7776 // literals as format strings. It takes the offset into account when returning 7777 // the string and its length or the source locations to display notes correctly. 7778 class FormatStringLiteral { 7779 const StringLiteral *FExpr; 7780 int64_t Offset; 7781 7782 public: 7783 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7784 : FExpr(fexpr), Offset(Offset) {} 7785 7786 StringRef getString() const { 7787 return FExpr->getString().drop_front(Offset); 7788 } 7789 7790 unsigned getByteLength() const { 7791 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7792 } 7793 7794 unsigned getLength() const { return FExpr->getLength() - Offset; } 7795 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7796 7797 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7798 7799 QualType getType() const { return FExpr->getType(); } 7800 7801 bool isAscii() const { return FExpr->isAscii(); } 7802 bool isWide() const { return FExpr->isWide(); } 7803 bool isUTF8() const { return FExpr->isUTF8(); } 7804 bool isUTF16() const { return FExpr->isUTF16(); } 7805 bool isUTF32() const { return FExpr->isUTF32(); } 7806 bool isPascal() const { return FExpr->isPascal(); } 7807 7808 SourceLocation getLocationOfByte( 7809 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7810 const TargetInfo &Target, unsigned *StartToken = nullptr, 7811 unsigned *StartTokenByteOffset = nullptr) const { 7812 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7813 StartToken, StartTokenByteOffset); 7814 } 7815 7816 SourceLocation getBeginLoc() const LLVM_READONLY { 7817 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7818 } 7819 7820 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7821 }; 7822 7823 } // namespace 7824 7825 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7826 const Expr *OrigFormatExpr, 7827 ArrayRef<const Expr *> Args, 7828 bool HasVAListArg, unsigned format_idx, 7829 unsigned firstDataArg, 7830 Sema::FormatStringType Type, 7831 bool inFunctionCall, 7832 Sema::VariadicCallType CallType, 7833 llvm::SmallBitVector &CheckedVarArgs, 7834 UncoveredArgHandler &UncoveredArg, 7835 bool IgnoreStringsWithoutSpecifiers); 7836 7837 // Determine if an expression is a string literal or constant string. 7838 // If this function returns false on the arguments to a function expecting a 7839 // format string, we will usually need to emit a warning. 7840 // True string literals are then checked by CheckFormatString. 7841 static StringLiteralCheckType 7842 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7843 bool HasVAListArg, unsigned format_idx, 7844 unsigned firstDataArg, Sema::FormatStringType Type, 7845 Sema::VariadicCallType CallType, bool InFunctionCall, 7846 llvm::SmallBitVector &CheckedVarArgs, 7847 UncoveredArgHandler &UncoveredArg, 7848 llvm::APSInt Offset, 7849 bool IgnoreStringsWithoutSpecifiers = false) { 7850 if (S.isConstantEvaluated()) 7851 return SLCT_NotALiteral; 7852 tryAgain: 7853 assert(Offset.isSigned() && "invalid offset"); 7854 7855 if (E->isTypeDependent() || E->isValueDependent()) 7856 return SLCT_NotALiteral; 7857 7858 E = E->IgnoreParenCasts(); 7859 7860 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7861 // Technically -Wformat-nonliteral does not warn about this case. 7862 // The behavior of printf and friends in this case is implementation 7863 // dependent. Ideally if the format string cannot be null then 7864 // it should have a 'nonnull' attribute in the function prototype. 7865 return SLCT_UncheckedLiteral; 7866 7867 switch (E->getStmtClass()) { 7868 case Stmt::BinaryConditionalOperatorClass: 7869 case Stmt::ConditionalOperatorClass: { 7870 // The expression is a literal if both sub-expressions were, and it was 7871 // completely checked only if both sub-expressions were checked. 7872 const AbstractConditionalOperator *C = 7873 cast<AbstractConditionalOperator>(E); 7874 7875 // Determine whether it is necessary to check both sub-expressions, for 7876 // example, because the condition expression is a constant that can be 7877 // evaluated at compile time. 7878 bool CheckLeft = true, CheckRight = true; 7879 7880 bool Cond; 7881 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7882 S.isConstantEvaluated())) { 7883 if (Cond) 7884 CheckRight = false; 7885 else 7886 CheckLeft = false; 7887 } 7888 7889 // We need to maintain the offsets for the right and the left hand side 7890 // separately to check if every possible indexed expression is a valid 7891 // string literal. They might have different offsets for different string 7892 // literals in the end. 7893 StringLiteralCheckType Left; 7894 if (!CheckLeft) 7895 Left = SLCT_UncheckedLiteral; 7896 else { 7897 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7898 HasVAListArg, format_idx, firstDataArg, 7899 Type, CallType, InFunctionCall, 7900 CheckedVarArgs, UncoveredArg, Offset, 7901 IgnoreStringsWithoutSpecifiers); 7902 if (Left == SLCT_NotALiteral || !CheckRight) { 7903 return Left; 7904 } 7905 } 7906 7907 StringLiteralCheckType Right = checkFormatStringExpr( 7908 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7909 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7910 IgnoreStringsWithoutSpecifiers); 7911 7912 return (CheckLeft && Left < Right) ? Left : Right; 7913 } 7914 7915 case Stmt::ImplicitCastExprClass: 7916 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7917 goto tryAgain; 7918 7919 case Stmt::OpaqueValueExprClass: 7920 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7921 E = src; 7922 goto tryAgain; 7923 } 7924 return SLCT_NotALiteral; 7925 7926 case Stmt::PredefinedExprClass: 7927 // While __func__, etc., are technically not string literals, they 7928 // cannot contain format specifiers and thus are not a security 7929 // liability. 7930 return SLCT_UncheckedLiteral; 7931 7932 case Stmt::DeclRefExprClass: { 7933 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7934 7935 // As an exception, do not flag errors for variables binding to 7936 // const string literals. 7937 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7938 bool isConstant = false; 7939 QualType T = DR->getType(); 7940 7941 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7942 isConstant = AT->getElementType().isConstant(S.Context); 7943 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7944 isConstant = T.isConstant(S.Context) && 7945 PT->getPointeeType().isConstant(S.Context); 7946 } else if (T->isObjCObjectPointerType()) { 7947 // In ObjC, there is usually no "const ObjectPointer" type, 7948 // so don't check if the pointee type is constant. 7949 isConstant = T.isConstant(S.Context); 7950 } 7951 7952 if (isConstant) { 7953 if (const Expr *Init = VD->getAnyInitializer()) { 7954 // Look through initializers like const char c[] = { "foo" } 7955 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7956 if (InitList->isStringLiteralInit()) 7957 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7958 } 7959 return checkFormatStringExpr(S, Init, Args, 7960 HasVAListArg, format_idx, 7961 firstDataArg, Type, CallType, 7962 /*InFunctionCall*/ false, CheckedVarArgs, 7963 UncoveredArg, Offset); 7964 } 7965 } 7966 7967 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7968 // special check to see if the format string is a function parameter 7969 // of the function calling the printf function. If the function 7970 // has an attribute indicating it is a printf-like function, then we 7971 // should suppress warnings concerning non-literals being used in a call 7972 // to a vprintf function. For example: 7973 // 7974 // void 7975 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7976 // va_list ap; 7977 // va_start(ap, fmt); 7978 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7979 // ... 7980 // } 7981 if (HasVAListArg) { 7982 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7983 if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) { 7984 int PVIndex = PV->getFunctionScopeIndex() + 1; 7985 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) { 7986 // adjust for implicit parameter 7987 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) 7988 if (MD->isInstance()) 7989 ++PVIndex; 7990 // We also check if the formats are compatible. 7991 // We can't pass a 'scanf' string to a 'printf' function. 7992 if (PVIndex == PVFormat->getFormatIdx() && 7993 Type == S.GetFormatStringType(PVFormat)) 7994 return SLCT_UncheckedLiteral; 7995 } 7996 } 7997 } 7998 } 7999 } 8000 8001 return SLCT_NotALiteral; 8002 } 8003 8004 case Stmt::CallExprClass: 8005 case Stmt::CXXMemberCallExprClass: { 8006 const CallExpr *CE = cast<CallExpr>(E); 8007 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 8008 bool IsFirst = true; 8009 StringLiteralCheckType CommonResult; 8010 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 8011 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 8012 StringLiteralCheckType Result = checkFormatStringExpr( 8013 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 8014 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8015 IgnoreStringsWithoutSpecifiers); 8016 if (IsFirst) { 8017 CommonResult = Result; 8018 IsFirst = false; 8019 } 8020 } 8021 if (!IsFirst) 8022 return CommonResult; 8023 8024 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 8025 unsigned BuiltinID = FD->getBuiltinID(); 8026 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 8027 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 8028 const Expr *Arg = CE->getArg(0); 8029 return checkFormatStringExpr(S, Arg, Args, 8030 HasVAListArg, format_idx, 8031 firstDataArg, Type, CallType, 8032 InFunctionCall, CheckedVarArgs, 8033 UncoveredArg, Offset, 8034 IgnoreStringsWithoutSpecifiers); 8035 } 8036 } 8037 } 8038 8039 return SLCT_NotALiteral; 8040 } 8041 case Stmt::ObjCMessageExprClass: { 8042 const auto *ME = cast<ObjCMessageExpr>(E); 8043 if (const auto *MD = ME->getMethodDecl()) { 8044 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 8045 // As a special case heuristic, if we're using the method -[NSBundle 8046 // localizedStringForKey:value:table:], ignore any key strings that lack 8047 // format specifiers. The idea is that if the key doesn't have any 8048 // format specifiers then its probably just a key to map to the 8049 // localized strings. If it does have format specifiers though, then its 8050 // likely that the text of the key is the format string in the 8051 // programmer's language, and should be checked. 8052 const ObjCInterfaceDecl *IFace; 8053 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 8054 IFace->getIdentifier()->isStr("NSBundle") && 8055 MD->getSelector().isKeywordSelector( 8056 {"localizedStringForKey", "value", "table"})) { 8057 IgnoreStringsWithoutSpecifiers = true; 8058 } 8059 8060 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 8061 return checkFormatStringExpr( 8062 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 8063 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8064 IgnoreStringsWithoutSpecifiers); 8065 } 8066 } 8067 8068 return SLCT_NotALiteral; 8069 } 8070 case Stmt::ObjCStringLiteralClass: 8071 case Stmt::StringLiteralClass: { 8072 const StringLiteral *StrE = nullptr; 8073 8074 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 8075 StrE = ObjCFExpr->getString(); 8076 else 8077 StrE = cast<StringLiteral>(E); 8078 8079 if (StrE) { 8080 if (Offset.isNegative() || Offset > StrE->getLength()) { 8081 // TODO: It would be better to have an explicit warning for out of 8082 // bounds literals. 8083 return SLCT_NotALiteral; 8084 } 8085 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 8086 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 8087 firstDataArg, Type, InFunctionCall, CallType, 8088 CheckedVarArgs, UncoveredArg, 8089 IgnoreStringsWithoutSpecifiers); 8090 return SLCT_CheckedLiteral; 8091 } 8092 8093 return SLCT_NotALiteral; 8094 } 8095 case Stmt::BinaryOperatorClass: { 8096 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 8097 8098 // A string literal + an int offset is still a string literal. 8099 if (BinOp->isAdditiveOp()) { 8100 Expr::EvalResult LResult, RResult; 8101 8102 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 8103 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8104 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 8105 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8106 8107 if (LIsInt != RIsInt) { 8108 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 8109 8110 if (LIsInt) { 8111 if (BinOpKind == BO_Add) { 8112 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 8113 E = BinOp->getRHS(); 8114 goto tryAgain; 8115 } 8116 } else { 8117 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 8118 E = BinOp->getLHS(); 8119 goto tryAgain; 8120 } 8121 } 8122 } 8123 8124 return SLCT_NotALiteral; 8125 } 8126 case Stmt::UnaryOperatorClass: { 8127 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 8128 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 8129 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 8130 Expr::EvalResult IndexResult; 8131 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 8132 Expr::SE_NoSideEffects, 8133 S.isConstantEvaluated())) { 8134 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 8135 /*RHS is int*/ true); 8136 E = ASE->getBase(); 8137 goto tryAgain; 8138 } 8139 } 8140 8141 return SLCT_NotALiteral; 8142 } 8143 8144 default: 8145 return SLCT_NotALiteral; 8146 } 8147 } 8148 8149 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 8150 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 8151 .Case("scanf", FST_Scanf) 8152 .Cases("printf", "printf0", FST_Printf) 8153 .Cases("NSString", "CFString", FST_NSString) 8154 .Case("strftime", FST_Strftime) 8155 .Case("strfmon", FST_Strfmon) 8156 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 8157 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 8158 .Case("os_trace", FST_OSLog) 8159 .Case("os_log", FST_OSLog) 8160 .Default(FST_Unknown); 8161 } 8162 8163 /// CheckFormatArguments - Check calls to printf and scanf (and similar 8164 /// functions) for correct use of format strings. 8165 /// Returns true if a format string has been fully checked. 8166 bool Sema::CheckFormatArguments(const FormatAttr *Format, 8167 ArrayRef<const Expr *> Args, 8168 bool IsCXXMember, 8169 VariadicCallType CallType, 8170 SourceLocation Loc, SourceRange Range, 8171 llvm::SmallBitVector &CheckedVarArgs) { 8172 FormatStringInfo FSI; 8173 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 8174 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 8175 FSI.FirstDataArg, GetFormatStringType(Format), 8176 CallType, Loc, Range, CheckedVarArgs); 8177 return false; 8178 } 8179 8180 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 8181 bool HasVAListArg, unsigned format_idx, 8182 unsigned firstDataArg, FormatStringType Type, 8183 VariadicCallType CallType, 8184 SourceLocation Loc, SourceRange Range, 8185 llvm::SmallBitVector &CheckedVarArgs) { 8186 // CHECK: printf/scanf-like function is called with no format string. 8187 if (format_idx >= Args.size()) { 8188 Diag(Loc, diag::warn_missing_format_string) << Range; 8189 return false; 8190 } 8191 8192 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 8193 8194 // CHECK: format string is not a string literal. 8195 // 8196 // Dynamically generated format strings are difficult to 8197 // automatically vet at compile time. Requiring that format strings 8198 // are string literals: (1) permits the checking of format strings by 8199 // the compiler and thereby (2) can practically remove the source of 8200 // many format string exploits. 8201 8202 // Format string can be either ObjC string (e.g. @"%d") or 8203 // C string (e.g. "%d") 8204 // ObjC string uses the same format specifiers as C string, so we can use 8205 // the same format string checking logic for both ObjC and C strings. 8206 UncoveredArgHandler UncoveredArg; 8207 StringLiteralCheckType CT = 8208 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 8209 format_idx, firstDataArg, Type, CallType, 8210 /*IsFunctionCall*/ true, CheckedVarArgs, 8211 UncoveredArg, 8212 /*no string offset*/ llvm::APSInt(64, false) = 0); 8213 8214 // Generate a diagnostic where an uncovered argument is detected. 8215 if (UncoveredArg.hasUncoveredArg()) { 8216 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 8217 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 8218 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 8219 } 8220 8221 if (CT != SLCT_NotALiteral) 8222 // Literal format string found, check done! 8223 return CT == SLCT_CheckedLiteral; 8224 8225 // Strftime is particular as it always uses a single 'time' argument, 8226 // so it is safe to pass a non-literal string. 8227 if (Type == FST_Strftime) 8228 return false; 8229 8230 // Do not emit diag when the string param is a macro expansion and the 8231 // format is either NSString or CFString. This is a hack to prevent 8232 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 8233 // which are usually used in place of NS and CF string literals. 8234 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 8235 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 8236 return false; 8237 8238 // If there are no arguments specified, warn with -Wformat-security, otherwise 8239 // warn only with -Wformat-nonliteral. 8240 if (Args.size() == firstDataArg) { 8241 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 8242 << OrigFormatExpr->getSourceRange(); 8243 switch (Type) { 8244 default: 8245 break; 8246 case FST_Kprintf: 8247 case FST_FreeBSDKPrintf: 8248 case FST_Printf: 8249 Diag(FormatLoc, diag::note_format_security_fixit) 8250 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 8251 break; 8252 case FST_NSString: 8253 Diag(FormatLoc, diag::note_format_security_fixit) 8254 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 8255 break; 8256 } 8257 } else { 8258 Diag(FormatLoc, diag::warn_format_nonliteral) 8259 << OrigFormatExpr->getSourceRange(); 8260 } 8261 return false; 8262 } 8263 8264 namespace { 8265 8266 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 8267 protected: 8268 Sema &S; 8269 const FormatStringLiteral *FExpr; 8270 const Expr *OrigFormatExpr; 8271 const Sema::FormatStringType FSType; 8272 const unsigned FirstDataArg; 8273 const unsigned NumDataArgs; 8274 const char *Beg; // Start of format string. 8275 const bool HasVAListArg; 8276 ArrayRef<const Expr *> Args; 8277 unsigned FormatIdx; 8278 llvm::SmallBitVector CoveredArgs; 8279 bool usesPositionalArgs = false; 8280 bool atFirstArg = true; 8281 bool inFunctionCall; 8282 Sema::VariadicCallType CallType; 8283 llvm::SmallBitVector &CheckedVarArgs; 8284 UncoveredArgHandler &UncoveredArg; 8285 8286 public: 8287 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 8288 const Expr *origFormatExpr, 8289 const Sema::FormatStringType type, unsigned firstDataArg, 8290 unsigned numDataArgs, const char *beg, bool hasVAListArg, 8291 ArrayRef<const Expr *> Args, unsigned formatIdx, 8292 bool inFunctionCall, Sema::VariadicCallType callType, 8293 llvm::SmallBitVector &CheckedVarArgs, 8294 UncoveredArgHandler &UncoveredArg) 8295 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 8296 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 8297 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 8298 inFunctionCall(inFunctionCall), CallType(callType), 8299 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 8300 CoveredArgs.resize(numDataArgs); 8301 CoveredArgs.reset(); 8302 } 8303 8304 void DoneProcessing(); 8305 8306 void HandleIncompleteSpecifier(const char *startSpecifier, 8307 unsigned specifierLen) override; 8308 8309 void HandleInvalidLengthModifier( 8310 const analyze_format_string::FormatSpecifier &FS, 8311 const analyze_format_string::ConversionSpecifier &CS, 8312 const char *startSpecifier, unsigned specifierLen, 8313 unsigned DiagID); 8314 8315 void HandleNonStandardLengthModifier( 8316 const analyze_format_string::FormatSpecifier &FS, 8317 const char *startSpecifier, unsigned specifierLen); 8318 8319 void HandleNonStandardConversionSpecifier( 8320 const analyze_format_string::ConversionSpecifier &CS, 8321 const char *startSpecifier, unsigned specifierLen); 8322 8323 void HandlePosition(const char *startPos, unsigned posLen) override; 8324 8325 void HandleInvalidPosition(const char *startSpecifier, 8326 unsigned specifierLen, 8327 analyze_format_string::PositionContext p) override; 8328 8329 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 8330 8331 void HandleNullChar(const char *nullCharacter) override; 8332 8333 template <typename Range> 8334 static void 8335 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 8336 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 8337 bool IsStringLocation, Range StringRange, 8338 ArrayRef<FixItHint> Fixit = None); 8339 8340 protected: 8341 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 8342 const char *startSpec, 8343 unsigned specifierLen, 8344 const char *csStart, unsigned csLen); 8345 8346 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 8347 const char *startSpec, 8348 unsigned specifierLen); 8349 8350 SourceRange getFormatStringRange(); 8351 CharSourceRange getSpecifierRange(const char *startSpecifier, 8352 unsigned specifierLen); 8353 SourceLocation getLocationOfByte(const char *x); 8354 8355 const Expr *getDataArg(unsigned i) const; 8356 8357 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 8358 const analyze_format_string::ConversionSpecifier &CS, 8359 const char *startSpecifier, unsigned specifierLen, 8360 unsigned argIndex); 8361 8362 template <typename Range> 8363 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 8364 bool IsStringLocation, Range StringRange, 8365 ArrayRef<FixItHint> Fixit = None); 8366 }; 8367 8368 } // namespace 8369 8370 SourceRange CheckFormatHandler::getFormatStringRange() { 8371 return OrigFormatExpr->getSourceRange(); 8372 } 8373 8374 CharSourceRange CheckFormatHandler:: 8375 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 8376 SourceLocation Start = getLocationOfByte(startSpecifier); 8377 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 8378 8379 // Advance the end SourceLocation by one due to half-open ranges. 8380 End = End.getLocWithOffset(1); 8381 8382 return CharSourceRange::getCharRange(Start, End); 8383 } 8384 8385 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 8386 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 8387 S.getLangOpts(), S.Context.getTargetInfo()); 8388 } 8389 8390 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 8391 unsigned specifierLen){ 8392 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 8393 getLocationOfByte(startSpecifier), 8394 /*IsStringLocation*/true, 8395 getSpecifierRange(startSpecifier, specifierLen)); 8396 } 8397 8398 void CheckFormatHandler::HandleInvalidLengthModifier( 8399 const analyze_format_string::FormatSpecifier &FS, 8400 const analyze_format_string::ConversionSpecifier &CS, 8401 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 8402 using namespace analyze_format_string; 8403 8404 const LengthModifier &LM = FS.getLengthModifier(); 8405 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8406 8407 // See if we know how to fix this length modifier. 8408 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8409 if (FixedLM) { 8410 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8411 getLocationOfByte(LM.getStart()), 8412 /*IsStringLocation*/true, 8413 getSpecifierRange(startSpecifier, specifierLen)); 8414 8415 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8416 << FixedLM->toString() 8417 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8418 8419 } else { 8420 FixItHint Hint; 8421 if (DiagID == diag::warn_format_nonsensical_length) 8422 Hint = FixItHint::CreateRemoval(LMRange); 8423 8424 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8425 getLocationOfByte(LM.getStart()), 8426 /*IsStringLocation*/true, 8427 getSpecifierRange(startSpecifier, specifierLen), 8428 Hint); 8429 } 8430 } 8431 8432 void CheckFormatHandler::HandleNonStandardLengthModifier( 8433 const analyze_format_string::FormatSpecifier &FS, 8434 const char *startSpecifier, unsigned specifierLen) { 8435 using namespace analyze_format_string; 8436 8437 const LengthModifier &LM = FS.getLengthModifier(); 8438 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8439 8440 // See if we know how to fix this length modifier. 8441 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8442 if (FixedLM) { 8443 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8444 << LM.toString() << 0, 8445 getLocationOfByte(LM.getStart()), 8446 /*IsStringLocation*/true, 8447 getSpecifierRange(startSpecifier, specifierLen)); 8448 8449 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8450 << FixedLM->toString() 8451 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8452 8453 } else { 8454 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8455 << LM.toString() << 0, 8456 getLocationOfByte(LM.getStart()), 8457 /*IsStringLocation*/true, 8458 getSpecifierRange(startSpecifier, specifierLen)); 8459 } 8460 } 8461 8462 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 8463 const analyze_format_string::ConversionSpecifier &CS, 8464 const char *startSpecifier, unsigned specifierLen) { 8465 using namespace analyze_format_string; 8466 8467 // See if we know how to fix this conversion specifier. 8468 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 8469 if (FixedCS) { 8470 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8471 << CS.toString() << /*conversion specifier*/1, 8472 getLocationOfByte(CS.getStart()), 8473 /*IsStringLocation*/true, 8474 getSpecifierRange(startSpecifier, specifierLen)); 8475 8476 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 8477 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 8478 << FixedCS->toString() 8479 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 8480 } else { 8481 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8482 << CS.toString() << /*conversion specifier*/1, 8483 getLocationOfByte(CS.getStart()), 8484 /*IsStringLocation*/true, 8485 getSpecifierRange(startSpecifier, specifierLen)); 8486 } 8487 } 8488 8489 void CheckFormatHandler::HandlePosition(const char *startPos, 8490 unsigned posLen) { 8491 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 8492 getLocationOfByte(startPos), 8493 /*IsStringLocation*/true, 8494 getSpecifierRange(startPos, posLen)); 8495 } 8496 8497 void 8498 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 8499 analyze_format_string::PositionContext p) { 8500 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 8501 << (unsigned) p, 8502 getLocationOfByte(startPos), /*IsStringLocation*/true, 8503 getSpecifierRange(startPos, posLen)); 8504 } 8505 8506 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 8507 unsigned posLen) { 8508 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 8509 getLocationOfByte(startPos), 8510 /*IsStringLocation*/true, 8511 getSpecifierRange(startPos, posLen)); 8512 } 8513 8514 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 8515 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 8516 // The presence of a null character is likely an error. 8517 EmitFormatDiagnostic( 8518 S.PDiag(diag::warn_printf_format_string_contains_null_char), 8519 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 8520 getFormatStringRange()); 8521 } 8522 } 8523 8524 // Note that this may return NULL if there was an error parsing or building 8525 // one of the argument expressions. 8526 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 8527 return Args[FirstDataArg + i]; 8528 } 8529 8530 void CheckFormatHandler::DoneProcessing() { 8531 // Does the number of data arguments exceed the number of 8532 // format conversions in the format string? 8533 if (!HasVAListArg) { 8534 // Find any arguments that weren't covered. 8535 CoveredArgs.flip(); 8536 signed notCoveredArg = CoveredArgs.find_first(); 8537 if (notCoveredArg >= 0) { 8538 assert((unsigned)notCoveredArg < NumDataArgs); 8539 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 8540 } else { 8541 UncoveredArg.setAllCovered(); 8542 } 8543 } 8544 } 8545 8546 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 8547 const Expr *ArgExpr) { 8548 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 8549 "Invalid state"); 8550 8551 if (!ArgExpr) 8552 return; 8553 8554 SourceLocation Loc = ArgExpr->getBeginLoc(); 8555 8556 if (S.getSourceManager().isInSystemMacro(Loc)) 8557 return; 8558 8559 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8560 for (auto E : DiagnosticExprs) 8561 PDiag << E->getSourceRange(); 8562 8563 CheckFormatHandler::EmitFormatDiagnostic( 8564 S, IsFunctionCall, DiagnosticExprs[0], 8565 PDiag, Loc, /*IsStringLocation*/false, 8566 DiagnosticExprs[0]->getSourceRange()); 8567 } 8568 8569 bool 8570 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8571 SourceLocation Loc, 8572 const char *startSpec, 8573 unsigned specifierLen, 8574 const char *csStart, 8575 unsigned csLen) { 8576 bool keepGoing = true; 8577 if (argIndex < NumDataArgs) { 8578 // Consider the argument coverered, even though the specifier doesn't 8579 // make sense. 8580 CoveredArgs.set(argIndex); 8581 } 8582 else { 8583 // If argIndex exceeds the number of data arguments we 8584 // don't issue a warning because that is just a cascade of warnings (and 8585 // they may have intended '%%' anyway). We don't want to continue processing 8586 // the format string after this point, however, as we will like just get 8587 // gibberish when trying to match arguments. 8588 keepGoing = false; 8589 } 8590 8591 StringRef Specifier(csStart, csLen); 8592 8593 // If the specifier in non-printable, it could be the first byte of a UTF-8 8594 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8595 // hex value. 8596 std::string CodePointStr; 8597 if (!llvm::sys::locale::isPrint(*csStart)) { 8598 llvm::UTF32 CodePoint; 8599 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8600 const llvm::UTF8 *E = 8601 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8602 llvm::ConversionResult Result = 8603 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8604 8605 if (Result != llvm::conversionOK) { 8606 unsigned char FirstChar = *csStart; 8607 CodePoint = (llvm::UTF32)FirstChar; 8608 } 8609 8610 llvm::raw_string_ostream OS(CodePointStr); 8611 if (CodePoint < 256) 8612 OS << "\\x" << llvm::format("%02x", CodePoint); 8613 else if (CodePoint <= 0xFFFF) 8614 OS << "\\u" << llvm::format("%04x", CodePoint); 8615 else 8616 OS << "\\U" << llvm::format("%08x", CodePoint); 8617 OS.flush(); 8618 Specifier = CodePointStr; 8619 } 8620 8621 EmitFormatDiagnostic( 8622 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8623 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8624 8625 return keepGoing; 8626 } 8627 8628 void 8629 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8630 const char *startSpec, 8631 unsigned specifierLen) { 8632 EmitFormatDiagnostic( 8633 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8634 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8635 } 8636 8637 bool 8638 CheckFormatHandler::CheckNumArgs( 8639 const analyze_format_string::FormatSpecifier &FS, 8640 const analyze_format_string::ConversionSpecifier &CS, 8641 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8642 8643 if (argIndex >= NumDataArgs) { 8644 PartialDiagnostic PDiag = FS.usesPositionalArg() 8645 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8646 << (argIndex+1) << NumDataArgs) 8647 : S.PDiag(diag::warn_printf_insufficient_data_args); 8648 EmitFormatDiagnostic( 8649 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8650 getSpecifierRange(startSpecifier, specifierLen)); 8651 8652 // Since more arguments than conversion tokens are given, by extension 8653 // all arguments are covered, so mark this as so. 8654 UncoveredArg.setAllCovered(); 8655 return false; 8656 } 8657 return true; 8658 } 8659 8660 template<typename Range> 8661 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8662 SourceLocation Loc, 8663 bool IsStringLocation, 8664 Range StringRange, 8665 ArrayRef<FixItHint> FixIt) { 8666 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8667 Loc, IsStringLocation, StringRange, FixIt); 8668 } 8669 8670 /// If the format string is not within the function call, emit a note 8671 /// so that the function call and string are in diagnostic messages. 8672 /// 8673 /// \param InFunctionCall if true, the format string is within the function 8674 /// call and only one diagnostic message will be produced. Otherwise, an 8675 /// extra note will be emitted pointing to location of the format string. 8676 /// 8677 /// \param ArgumentExpr the expression that is passed as the format string 8678 /// argument in the function call. Used for getting locations when two 8679 /// diagnostics are emitted. 8680 /// 8681 /// \param PDiag the callee should already have provided any strings for the 8682 /// diagnostic message. This function only adds locations and fixits 8683 /// to diagnostics. 8684 /// 8685 /// \param Loc primary location for diagnostic. If two diagnostics are 8686 /// required, one will be at Loc and a new SourceLocation will be created for 8687 /// the other one. 8688 /// 8689 /// \param IsStringLocation if true, Loc points to the format string should be 8690 /// used for the note. Otherwise, Loc points to the argument list and will 8691 /// be used with PDiag. 8692 /// 8693 /// \param StringRange some or all of the string to highlight. This is 8694 /// templated so it can accept either a CharSourceRange or a SourceRange. 8695 /// 8696 /// \param FixIt optional fix it hint for the format string. 8697 template <typename Range> 8698 void CheckFormatHandler::EmitFormatDiagnostic( 8699 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8700 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8701 Range StringRange, ArrayRef<FixItHint> FixIt) { 8702 if (InFunctionCall) { 8703 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8704 D << StringRange; 8705 D << FixIt; 8706 } else { 8707 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8708 << ArgumentExpr->getSourceRange(); 8709 8710 const Sema::SemaDiagnosticBuilder &Note = 8711 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8712 diag::note_format_string_defined); 8713 8714 Note << StringRange; 8715 Note << FixIt; 8716 } 8717 } 8718 8719 //===--- CHECK: Printf format string checking ------------------------------===// 8720 8721 namespace { 8722 8723 class CheckPrintfHandler : public CheckFormatHandler { 8724 public: 8725 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8726 const Expr *origFormatExpr, 8727 const Sema::FormatStringType type, unsigned firstDataArg, 8728 unsigned numDataArgs, bool isObjC, const char *beg, 8729 bool hasVAListArg, ArrayRef<const Expr *> Args, 8730 unsigned formatIdx, bool inFunctionCall, 8731 Sema::VariadicCallType CallType, 8732 llvm::SmallBitVector &CheckedVarArgs, 8733 UncoveredArgHandler &UncoveredArg) 8734 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8735 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8736 inFunctionCall, CallType, CheckedVarArgs, 8737 UncoveredArg) {} 8738 8739 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8740 8741 /// Returns true if '%@' specifiers are allowed in the format string. 8742 bool allowsObjCArg() const { 8743 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8744 FSType == Sema::FST_OSTrace; 8745 } 8746 8747 bool HandleInvalidPrintfConversionSpecifier( 8748 const analyze_printf::PrintfSpecifier &FS, 8749 const char *startSpecifier, 8750 unsigned specifierLen) override; 8751 8752 void handleInvalidMaskType(StringRef MaskType) override; 8753 8754 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8755 const char *startSpecifier, 8756 unsigned specifierLen) override; 8757 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8758 const char *StartSpecifier, 8759 unsigned SpecifierLen, 8760 const Expr *E); 8761 8762 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8763 const char *startSpecifier, unsigned specifierLen); 8764 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8765 const analyze_printf::OptionalAmount &Amt, 8766 unsigned type, 8767 const char *startSpecifier, unsigned specifierLen); 8768 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8769 const analyze_printf::OptionalFlag &flag, 8770 const char *startSpecifier, unsigned specifierLen); 8771 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8772 const analyze_printf::OptionalFlag &ignoredFlag, 8773 const analyze_printf::OptionalFlag &flag, 8774 const char *startSpecifier, unsigned specifierLen); 8775 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8776 const Expr *E); 8777 8778 void HandleEmptyObjCModifierFlag(const char *startFlag, 8779 unsigned flagLen) override; 8780 8781 void HandleInvalidObjCModifierFlag(const char *startFlag, 8782 unsigned flagLen) override; 8783 8784 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8785 const char *flagsEnd, 8786 const char *conversionPosition) 8787 override; 8788 }; 8789 8790 } // namespace 8791 8792 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8793 const analyze_printf::PrintfSpecifier &FS, 8794 const char *startSpecifier, 8795 unsigned specifierLen) { 8796 const analyze_printf::PrintfConversionSpecifier &CS = 8797 FS.getConversionSpecifier(); 8798 8799 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8800 getLocationOfByte(CS.getStart()), 8801 startSpecifier, specifierLen, 8802 CS.getStart(), CS.getLength()); 8803 } 8804 8805 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8806 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8807 } 8808 8809 bool CheckPrintfHandler::HandleAmount( 8810 const analyze_format_string::OptionalAmount &Amt, 8811 unsigned k, const char *startSpecifier, 8812 unsigned specifierLen) { 8813 if (Amt.hasDataArgument()) { 8814 if (!HasVAListArg) { 8815 unsigned argIndex = Amt.getArgIndex(); 8816 if (argIndex >= NumDataArgs) { 8817 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8818 << k, 8819 getLocationOfByte(Amt.getStart()), 8820 /*IsStringLocation*/true, 8821 getSpecifierRange(startSpecifier, specifierLen)); 8822 // Don't do any more checking. We will just emit 8823 // spurious errors. 8824 return false; 8825 } 8826 8827 // Type check the data argument. It should be an 'int'. 8828 // Although not in conformance with C99, we also allow the argument to be 8829 // an 'unsigned int' as that is a reasonably safe case. GCC also 8830 // doesn't emit a warning for that case. 8831 CoveredArgs.set(argIndex); 8832 const Expr *Arg = getDataArg(argIndex); 8833 if (!Arg) 8834 return false; 8835 8836 QualType T = Arg->getType(); 8837 8838 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8839 assert(AT.isValid()); 8840 8841 if (!AT.matchesType(S.Context, T)) { 8842 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8843 << k << AT.getRepresentativeTypeName(S.Context) 8844 << T << Arg->getSourceRange(), 8845 getLocationOfByte(Amt.getStart()), 8846 /*IsStringLocation*/true, 8847 getSpecifierRange(startSpecifier, specifierLen)); 8848 // Don't do any more checking. We will just emit 8849 // spurious errors. 8850 return false; 8851 } 8852 } 8853 } 8854 return true; 8855 } 8856 8857 void CheckPrintfHandler::HandleInvalidAmount( 8858 const analyze_printf::PrintfSpecifier &FS, 8859 const analyze_printf::OptionalAmount &Amt, 8860 unsigned type, 8861 const char *startSpecifier, 8862 unsigned specifierLen) { 8863 const analyze_printf::PrintfConversionSpecifier &CS = 8864 FS.getConversionSpecifier(); 8865 8866 FixItHint fixit = 8867 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8868 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8869 Amt.getConstantLength())) 8870 : FixItHint(); 8871 8872 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8873 << type << CS.toString(), 8874 getLocationOfByte(Amt.getStart()), 8875 /*IsStringLocation*/true, 8876 getSpecifierRange(startSpecifier, specifierLen), 8877 fixit); 8878 } 8879 8880 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8881 const analyze_printf::OptionalFlag &flag, 8882 const char *startSpecifier, 8883 unsigned specifierLen) { 8884 // Warn about pointless flag with a fixit removal. 8885 const analyze_printf::PrintfConversionSpecifier &CS = 8886 FS.getConversionSpecifier(); 8887 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8888 << flag.toString() << CS.toString(), 8889 getLocationOfByte(flag.getPosition()), 8890 /*IsStringLocation*/true, 8891 getSpecifierRange(startSpecifier, specifierLen), 8892 FixItHint::CreateRemoval( 8893 getSpecifierRange(flag.getPosition(), 1))); 8894 } 8895 8896 void CheckPrintfHandler::HandleIgnoredFlag( 8897 const analyze_printf::PrintfSpecifier &FS, 8898 const analyze_printf::OptionalFlag &ignoredFlag, 8899 const analyze_printf::OptionalFlag &flag, 8900 const char *startSpecifier, 8901 unsigned specifierLen) { 8902 // Warn about ignored flag with a fixit removal. 8903 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8904 << ignoredFlag.toString() << flag.toString(), 8905 getLocationOfByte(ignoredFlag.getPosition()), 8906 /*IsStringLocation*/true, 8907 getSpecifierRange(startSpecifier, specifierLen), 8908 FixItHint::CreateRemoval( 8909 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8910 } 8911 8912 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8913 unsigned flagLen) { 8914 // Warn about an empty flag. 8915 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8916 getLocationOfByte(startFlag), 8917 /*IsStringLocation*/true, 8918 getSpecifierRange(startFlag, flagLen)); 8919 } 8920 8921 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8922 unsigned flagLen) { 8923 // Warn about an invalid flag. 8924 auto Range = getSpecifierRange(startFlag, flagLen); 8925 StringRef flag(startFlag, flagLen); 8926 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8927 getLocationOfByte(startFlag), 8928 /*IsStringLocation*/true, 8929 Range, FixItHint::CreateRemoval(Range)); 8930 } 8931 8932 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8933 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8934 // Warn about using '[...]' without a '@' conversion. 8935 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8936 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8937 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8938 getLocationOfByte(conversionPosition), 8939 /*IsStringLocation*/true, 8940 Range, FixItHint::CreateRemoval(Range)); 8941 } 8942 8943 // Determines if the specified is a C++ class or struct containing 8944 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8945 // "c_str()"). 8946 template<typename MemberKind> 8947 static llvm::SmallPtrSet<MemberKind*, 1> 8948 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8949 const RecordType *RT = Ty->getAs<RecordType>(); 8950 llvm::SmallPtrSet<MemberKind*, 1> Results; 8951 8952 if (!RT) 8953 return Results; 8954 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8955 if (!RD || !RD->getDefinition()) 8956 return Results; 8957 8958 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8959 Sema::LookupMemberName); 8960 R.suppressDiagnostics(); 8961 8962 // We just need to include all members of the right kind turned up by the 8963 // filter, at this point. 8964 if (S.LookupQualifiedName(R, RT->getDecl())) 8965 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8966 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8967 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8968 Results.insert(FK); 8969 } 8970 return Results; 8971 } 8972 8973 /// Check if we could call '.c_str()' on an object. 8974 /// 8975 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8976 /// allow the call, or if it would be ambiguous). 8977 bool Sema::hasCStrMethod(const Expr *E) { 8978 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8979 8980 MethodSet Results = 8981 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8982 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8983 MI != ME; ++MI) 8984 if ((*MI)->getMinRequiredArguments() == 0) 8985 return true; 8986 return false; 8987 } 8988 8989 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8990 // better diagnostic if so. AT is assumed to be valid. 8991 // Returns true when a c_str() conversion method is found. 8992 bool CheckPrintfHandler::checkForCStrMembers( 8993 const analyze_printf::ArgType &AT, const Expr *E) { 8994 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8995 8996 MethodSet Results = 8997 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8998 8999 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 9000 MI != ME; ++MI) { 9001 const CXXMethodDecl *Method = *MI; 9002 if (Method->getMinRequiredArguments() == 0 && 9003 AT.matchesType(S.Context, Method->getReturnType())) { 9004 // FIXME: Suggest parens if the expression needs them. 9005 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 9006 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 9007 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 9008 return true; 9009 } 9010 } 9011 9012 return false; 9013 } 9014 9015 bool 9016 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 9017 &FS, 9018 const char *startSpecifier, 9019 unsigned specifierLen) { 9020 using namespace analyze_format_string; 9021 using namespace analyze_printf; 9022 9023 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 9024 9025 if (FS.consumesDataArgument()) { 9026 if (atFirstArg) { 9027 atFirstArg = false; 9028 usesPositionalArgs = FS.usesPositionalArg(); 9029 } 9030 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9031 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9032 startSpecifier, specifierLen); 9033 return false; 9034 } 9035 } 9036 9037 // First check if the field width, precision, and conversion specifier 9038 // have matching data arguments. 9039 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 9040 startSpecifier, specifierLen)) { 9041 return false; 9042 } 9043 9044 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 9045 startSpecifier, specifierLen)) { 9046 return false; 9047 } 9048 9049 if (!CS.consumesDataArgument()) { 9050 // FIXME: Technically specifying a precision or field width here 9051 // makes no sense. Worth issuing a warning at some point. 9052 return true; 9053 } 9054 9055 // Consume the argument. 9056 unsigned argIndex = FS.getArgIndex(); 9057 if (argIndex < NumDataArgs) { 9058 // The check to see if the argIndex is valid will come later. 9059 // We set the bit here because we may exit early from this 9060 // function if we encounter some other error. 9061 CoveredArgs.set(argIndex); 9062 } 9063 9064 // FreeBSD kernel extensions. 9065 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 9066 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 9067 // We need at least two arguments. 9068 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 9069 return false; 9070 9071 // Claim the second argument. 9072 CoveredArgs.set(argIndex + 1); 9073 9074 // Type check the first argument (int for %b, pointer for %D) 9075 const Expr *Ex = getDataArg(argIndex); 9076 const analyze_printf::ArgType &AT = 9077 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 9078 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 9079 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 9080 EmitFormatDiagnostic( 9081 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9082 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 9083 << false << Ex->getSourceRange(), 9084 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9085 getSpecifierRange(startSpecifier, specifierLen)); 9086 9087 // Type check the second argument (char * for both %b and %D) 9088 Ex = getDataArg(argIndex + 1); 9089 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 9090 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 9091 EmitFormatDiagnostic( 9092 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9093 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 9094 << false << Ex->getSourceRange(), 9095 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9096 getSpecifierRange(startSpecifier, specifierLen)); 9097 9098 return true; 9099 } 9100 9101 // Check for using an Objective-C specific conversion specifier 9102 // in a non-ObjC literal. 9103 if (!allowsObjCArg() && CS.isObjCArg()) { 9104 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9105 specifierLen); 9106 } 9107 9108 // %P can only be used with os_log. 9109 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 9110 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9111 specifierLen); 9112 } 9113 9114 // %n is not allowed with os_log. 9115 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 9116 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 9117 getLocationOfByte(CS.getStart()), 9118 /*IsStringLocation*/ false, 9119 getSpecifierRange(startSpecifier, specifierLen)); 9120 9121 return true; 9122 } 9123 9124 // Only scalars are allowed for os_trace. 9125 if (FSType == Sema::FST_OSTrace && 9126 (CS.getKind() == ConversionSpecifier::PArg || 9127 CS.getKind() == ConversionSpecifier::sArg || 9128 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 9129 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9130 specifierLen); 9131 } 9132 9133 // Check for use of public/private annotation outside of os_log(). 9134 if (FSType != Sema::FST_OSLog) { 9135 if (FS.isPublic().isSet()) { 9136 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9137 << "public", 9138 getLocationOfByte(FS.isPublic().getPosition()), 9139 /*IsStringLocation*/ false, 9140 getSpecifierRange(startSpecifier, specifierLen)); 9141 } 9142 if (FS.isPrivate().isSet()) { 9143 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9144 << "private", 9145 getLocationOfByte(FS.isPrivate().getPosition()), 9146 /*IsStringLocation*/ false, 9147 getSpecifierRange(startSpecifier, specifierLen)); 9148 } 9149 } 9150 9151 // Check for invalid use of field width 9152 if (!FS.hasValidFieldWidth()) { 9153 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 9154 startSpecifier, specifierLen); 9155 } 9156 9157 // Check for invalid use of precision 9158 if (!FS.hasValidPrecision()) { 9159 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 9160 startSpecifier, specifierLen); 9161 } 9162 9163 // Precision is mandatory for %P specifier. 9164 if (CS.getKind() == ConversionSpecifier::PArg && 9165 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 9166 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 9167 getLocationOfByte(startSpecifier), 9168 /*IsStringLocation*/ false, 9169 getSpecifierRange(startSpecifier, specifierLen)); 9170 } 9171 9172 // Check each flag does not conflict with any other component. 9173 if (!FS.hasValidThousandsGroupingPrefix()) 9174 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 9175 if (!FS.hasValidLeadingZeros()) 9176 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 9177 if (!FS.hasValidPlusPrefix()) 9178 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 9179 if (!FS.hasValidSpacePrefix()) 9180 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 9181 if (!FS.hasValidAlternativeForm()) 9182 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 9183 if (!FS.hasValidLeftJustified()) 9184 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 9185 9186 // Check that flags are not ignored by another flag 9187 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 9188 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 9189 startSpecifier, specifierLen); 9190 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 9191 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 9192 startSpecifier, specifierLen); 9193 9194 // Check the length modifier is valid with the given conversion specifier. 9195 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9196 S.getLangOpts())) 9197 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9198 diag::warn_format_nonsensical_length); 9199 else if (!FS.hasStandardLengthModifier()) 9200 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9201 else if (!FS.hasStandardLengthConversionCombination()) 9202 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9203 diag::warn_format_non_standard_conversion_spec); 9204 9205 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9206 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9207 9208 // The remaining checks depend on the data arguments. 9209 if (HasVAListArg) 9210 return true; 9211 9212 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9213 return false; 9214 9215 const Expr *Arg = getDataArg(argIndex); 9216 if (!Arg) 9217 return true; 9218 9219 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 9220 } 9221 9222 static bool requiresParensToAddCast(const Expr *E) { 9223 // FIXME: We should have a general way to reason about operator 9224 // precedence and whether parens are actually needed here. 9225 // Take care of a few common cases where they aren't. 9226 const Expr *Inside = E->IgnoreImpCasts(); 9227 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 9228 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 9229 9230 switch (Inside->getStmtClass()) { 9231 case Stmt::ArraySubscriptExprClass: 9232 case Stmt::CallExprClass: 9233 case Stmt::CharacterLiteralClass: 9234 case Stmt::CXXBoolLiteralExprClass: 9235 case Stmt::DeclRefExprClass: 9236 case Stmt::FloatingLiteralClass: 9237 case Stmt::IntegerLiteralClass: 9238 case Stmt::MemberExprClass: 9239 case Stmt::ObjCArrayLiteralClass: 9240 case Stmt::ObjCBoolLiteralExprClass: 9241 case Stmt::ObjCBoxedExprClass: 9242 case Stmt::ObjCDictionaryLiteralClass: 9243 case Stmt::ObjCEncodeExprClass: 9244 case Stmt::ObjCIvarRefExprClass: 9245 case Stmt::ObjCMessageExprClass: 9246 case Stmt::ObjCPropertyRefExprClass: 9247 case Stmt::ObjCStringLiteralClass: 9248 case Stmt::ObjCSubscriptRefExprClass: 9249 case Stmt::ParenExprClass: 9250 case Stmt::StringLiteralClass: 9251 case Stmt::UnaryOperatorClass: 9252 return false; 9253 default: 9254 return true; 9255 } 9256 } 9257 9258 static std::pair<QualType, StringRef> 9259 shouldNotPrintDirectly(const ASTContext &Context, 9260 QualType IntendedTy, 9261 const Expr *E) { 9262 // Use a 'while' to peel off layers of typedefs. 9263 QualType TyTy = IntendedTy; 9264 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 9265 StringRef Name = UserTy->getDecl()->getName(); 9266 QualType CastTy = llvm::StringSwitch<QualType>(Name) 9267 .Case("CFIndex", Context.getNSIntegerType()) 9268 .Case("NSInteger", Context.getNSIntegerType()) 9269 .Case("NSUInteger", Context.getNSUIntegerType()) 9270 .Case("SInt32", Context.IntTy) 9271 .Case("UInt32", Context.UnsignedIntTy) 9272 .Default(QualType()); 9273 9274 if (!CastTy.isNull()) 9275 return std::make_pair(CastTy, Name); 9276 9277 TyTy = UserTy->desugar(); 9278 } 9279 9280 // Strip parens if necessary. 9281 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 9282 return shouldNotPrintDirectly(Context, 9283 PE->getSubExpr()->getType(), 9284 PE->getSubExpr()); 9285 9286 // If this is a conditional expression, then its result type is constructed 9287 // via usual arithmetic conversions and thus there might be no necessary 9288 // typedef sugar there. Recurse to operands to check for NSInteger & 9289 // Co. usage condition. 9290 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9291 QualType TrueTy, FalseTy; 9292 StringRef TrueName, FalseName; 9293 9294 std::tie(TrueTy, TrueName) = 9295 shouldNotPrintDirectly(Context, 9296 CO->getTrueExpr()->getType(), 9297 CO->getTrueExpr()); 9298 std::tie(FalseTy, FalseName) = 9299 shouldNotPrintDirectly(Context, 9300 CO->getFalseExpr()->getType(), 9301 CO->getFalseExpr()); 9302 9303 if (TrueTy == FalseTy) 9304 return std::make_pair(TrueTy, TrueName); 9305 else if (TrueTy.isNull()) 9306 return std::make_pair(FalseTy, FalseName); 9307 else if (FalseTy.isNull()) 9308 return std::make_pair(TrueTy, TrueName); 9309 } 9310 9311 return std::make_pair(QualType(), StringRef()); 9312 } 9313 9314 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 9315 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 9316 /// type do not count. 9317 static bool 9318 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 9319 QualType From = ICE->getSubExpr()->getType(); 9320 QualType To = ICE->getType(); 9321 // It's an integer promotion if the destination type is the promoted 9322 // source type. 9323 if (ICE->getCastKind() == CK_IntegralCast && 9324 From->isPromotableIntegerType() && 9325 S.Context.getPromotedIntegerType(From) == To) 9326 return true; 9327 // Look through vector types, since we do default argument promotion for 9328 // those in OpenCL. 9329 if (const auto *VecTy = From->getAs<ExtVectorType>()) 9330 From = VecTy->getElementType(); 9331 if (const auto *VecTy = To->getAs<ExtVectorType>()) 9332 To = VecTy->getElementType(); 9333 // It's a floating promotion if the source type is a lower rank. 9334 return ICE->getCastKind() == CK_FloatingCast && 9335 S.Context.getFloatingTypeOrder(From, To) < 0; 9336 } 9337 9338 bool 9339 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9340 const char *StartSpecifier, 9341 unsigned SpecifierLen, 9342 const Expr *E) { 9343 using namespace analyze_format_string; 9344 using namespace analyze_printf; 9345 9346 // Now type check the data expression that matches the 9347 // format specifier. 9348 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 9349 if (!AT.isValid()) 9350 return true; 9351 9352 QualType ExprTy = E->getType(); 9353 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 9354 ExprTy = TET->getUnderlyingExpr()->getType(); 9355 } 9356 9357 // Diagnose attempts to print a boolean value as a character. Unlike other 9358 // -Wformat diagnostics, this is fine from a type perspective, but it still 9359 // doesn't make sense. 9360 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 9361 E->isKnownToHaveBooleanValue()) { 9362 const CharSourceRange &CSR = 9363 getSpecifierRange(StartSpecifier, SpecifierLen); 9364 SmallString<4> FSString; 9365 llvm::raw_svector_ostream os(FSString); 9366 FS.toString(os); 9367 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 9368 << FSString, 9369 E->getExprLoc(), false, CSR); 9370 return true; 9371 } 9372 9373 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 9374 if (Match == analyze_printf::ArgType::Match) 9375 return true; 9376 9377 // Look through argument promotions for our error message's reported type. 9378 // This includes the integral and floating promotions, but excludes array 9379 // and function pointer decay (seeing that an argument intended to be a 9380 // string has type 'char [6]' is probably more confusing than 'char *') and 9381 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 9382 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9383 if (isArithmeticArgumentPromotion(S, ICE)) { 9384 E = ICE->getSubExpr(); 9385 ExprTy = E->getType(); 9386 9387 // Check if we didn't match because of an implicit cast from a 'char' 9388 // or 'short' to an 'int'. This is done because printf is a varargs 9389 // function. 9390 if (ICE->getType() == S.Context.IntTy || 9391 ICE->getType() == S.Context.UnsignedIntTy) { 9392 // All further checking is done on the subexpression 9393 const analyze_printf::ArgType::MatchKind ImplicitMatch = 9394 AT.matchesType(S.Context, ExprTy); 9395 if (ImplicitMatch == analyze_printf::ArgType::Match) 9396 return true; 9397 if (ImplicitMatch == ArgType::NoMatchPedantic || 9398 ImplicitMatch == ArgType::NoMatchTypeConfusion) 9399 Match = ImplicitMatch; 9400 } 9401 } 9402 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 9403 // Special case for 'a', which has type 'int' in C. 9404 // Note, however, that we do /not/ want to treat multibyte constants like 9405 // 'MooV' as characters! This form is deprecated but still exists. In 9406 // addition, don't treat expressions as of type 'char' if one byte length 9407 // modifier is provided. 9408 if (ExprTy == S.Context.IntTy && 9409 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 9410 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 9411 ExprTy = S.Context.CharTy; 9412 } 9413 9414 // Look through enums to their underlying type. 9415 bool IsEnum = false; 9416 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 9417 ExprTy = EnumTy->getDecl()->getIntegerType(); 9418 IsEnum = true; 9419 } 9420 9421 // %C in an Objective-C context prints a unichar, not a wchar_t. 9422 // If the argument is an integer of some kind, believe the %C and suggest 9423 // a cast instead of changing the conversion specifier. 9424 QualType IntendedTy = ExprTy; 9425 if (isObjCContext() && 9426 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 9427 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 9428 !ExprTy->isCharType()) { 9429 // 'unichar' is defined as a typedef of unsigned short, but we should 9430 // prefer using the typedef if it is visible. 9431 IntendedTy = S.Context.UnsignedShortTy; 9432 9433 // While we are here, check if the value is an IntegerLiteral that happens 9434 // to be within the valid range. 9435 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 9436 const llvm::APInt &V = IL->getValue(); 9437 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 9438 return true; 9439 } 9440 9441 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 9442 Sema::LookupOrdinaryName); 9443 if (S.LookupName(Result, S.getCurScope())) { 9444 NamedDecl *ND = Result.getFoundDecl(); 9445 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 9446 if (TD->getUnderlyingType() == IntendedTy) 9447 IntendedTy = S.Context.getTypedefType(TD); 9448 } 9449 } 9450 } 9451 9452 // Special-case some of Darwin's platform-independence types by suggesting 9453 // casts to primitive types that are known to be large enough. 9454 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 9455 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 9456 QualType CastTy; 9457 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 9458 if (!CastTy.isNull()) { 9459 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 9460 // (long in ASTContext). Only complain to pedants. 9461 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 9462 (AT.isSizeT() || AT.isPtrdiffT()) && 9463 AT.matchesType(S.Context, CastTy)) 9464 Match = ArgType::NoMatchPedantic; 9465 IntendedTy = CastTy; 9466 ShouldNotPrintDirectly = true; 9467 } 9468 } 9469 9470 // We may be able to offer a FixItHint if it is a supported type. 9471 PrintfSpecifier fixedFS = FS; 9472 bool Success = 9473 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 9474 9475 if (Success) { 9476 // Get the fix string from the fixed format specifier 9477 SmallString<16> buf; 9478 llvm::raw_svector_ostream os(buf); 9479 fixedFS.toString(os); 9480 9481 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 9482 9483 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 9484 unsigned Diag; 9485 switch (Match) { 9486 case ArgType::Match: llvm_unreachable("expected non-matching"); 9487 case ArgType::NoMatchPedantic: 9488 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9489 break; 9490 case ArgType::NoMatchTypeConfusion: 9491 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9492 break; 9493 case ArgType::NoMatch: 9494 Diag = diag::warn_format_conversion_argument_type_mismatch; 9495 break; 9496 } 9497 9498 // In this case, the specifier is wrong and should be changed to match 9499 // the argument. 9500 EmitFormatDiagnostic(S.PDiag(Diag) 9501 << AT.getRepresentativeTypeName(S.Context) 9502 << IntendedTy << IsEnum << E->getSourceRange(), 9503 E->getBeginLoc(), 9504 /*IsStringLocation*/ false, SpecRange, 9505 FixItHint::CreateReplacement(SpecRange, os.str())); 9506 } else { 9507 // The canonical type for formatting this value is different from the 9508 // actual type of the expression. (This occurs, for example, with Darwin's 9509 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 9510 // should be printed as 'long' for 64-bit compatibility.) 9511 // Rather than emitting a normal format/argument mismatch, we want to 9512 // add a cast to the recommended type (and correct the format string 9513 // if necessary). 9514 SmallString<16> CastBuf; 9515 llvm::raw_svector_ostream CastFix(CastBuf); 9516 CastFix << "("; 9517 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 9518 CastFix << ")"; 9519 9520 SmallVector<FixItHint,4> Hints; 9521 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 9522 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 9523 9524 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 9525 // If there's already a cast present, just replace it. 9526 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 9527 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 9528 9529 } else if (!requiresParensToAddCast(E)) { 9530 // If the expression has high enough precedence, 9531 // just write the C-style cast. 9532 Hints.push_back( 9533 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9534 } else { 9535 // Otherwise, add parens around the expression as well as the cast. 9536 CastFix << "("; 9537 Hints.push_back( 9538 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9539 9540 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 9541 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 9542 } 9543 9544 if (ShouldNotPrintDirectly) { 9545 // The expression has a type that should not be printed directly. 9546 // We extract the name from the typedef because we don't want to show 9547 // the underlying type in the diagnostic. 9548 StringRef Name; 9549 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 9550 Name = TypedefTy->getDecl()->getName(); 9551 else 9552 Name = CastTyName; 9553 unsigned Diag = Match == ArgType::NoMatchPedantic 9554 ? diag::warn_format_argument_needs_cast_pedantic 9555 : diag::warn_format_argument_needs_cast; 9556 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 9557 << E->getSourceRange(), 9558 E->getBeginLoc(), /*IsStringLocation=*/false, 9559 SpecRange, Hints); 9560 } else { 9561 // In this case, the expression could be printed using a different 9562 // specifier, but we've decided that the specifier is probably correct 9563 // and we should cast instead. Just use the normal warning message. 9564 EmitFormatDiagnostic( 9565 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9566 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9567 << E->getSourceRange(), 9568 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9569 } 9570 } 9571 } else { 9572 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9573 SpecifierLen); 9574 // Since the warning for passing non-POD types to variadic functions 9575 // was deferred until now, we emit a warning for non-POD 9576 // arguments here. 9577 switch (S.isValidVarArgType(ExprTy)) { 9578 case Sema::VAK_Valid: 9579 case Sema::VAK_ValidInCXX11: { 9580 unsigned Diag; 9581 switch (Match) { 9582 case ArgType::Match: llvm_unreachable("expected non-matching"); 9583 case ArgType::NoMatchPedantic: 9584 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9585 break; 9586 case ArgType::NoMatchTypeConfusion: 9587 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9588 break; 9589 case ArgType::NoMatch: 9590 Diag = diag::warn_format_conversion_argument_type_mismatch; 9591 break; 9592 } 9593 9594 EmitFormatDiagnostic( 9595 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9596 << IsEnum << CSR << E->getSourceRange(), 9597 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9598 break; 9599 } 9600 case Sema::VAK_Undefined: 9601 case Sema::VAK_MSVCUndefined: 9602 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9603 << S.getLangOpts().CPlusPlus11 << ExprTy 9604 << CallType 9605 << AT.getRepresentativeTypeName(S.Context) << CSR 9606 << E->getSourceRange(), 9607 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9608 checkForCStrMembers(AT, E); 9609 break; 9610 9611 case Sema::VAK_Invalid: 9612 if (ExprTy->isObjCObjectType()) 9613 EmitFormatDiagnostic( 9614 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9615 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9616 << AT.getRepresentativeTypeName(S.Context) << CSR 9617 << E->getSourceRange(), 9618 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9619 else 9620 // FIXME: If this is an initializer list, suggest removing the braces 9621 // or inserting a cast to the target type. 9622 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9623 << isa<InitListExpr>(E) << ExprTy << CallType 9624 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9625 break; 9626 } 9627 9628 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9629 "format string specifier index out of range"); 9630 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9631 } 9632 9633 return true; 9634 } 9635 9636 //===--- CHECK: Scanf format string checking ------------------------------===// 9637 9638 namespace { 9639 9640 class CheckScanfHandler : public CheckFormatHandler { 9641 public: 9642 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9643 const Expr *origFormatExpr, Sema::FormatStringType type, 9644 unsigned firstDataArg, unsigned numDataArgs, 9645 const char *beg, bool hasVAListArg, 9646 ArrayRef<const Expr *> Args, unsigned formatIdx, 9647 bool inFunctionCall, Sema::VariadicCallType CallType, 9648 llvm::SmallBitVector &CheckedVarArgs, 9649 UncoveredArgHandler &UncoveredArg) 9650 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9651 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9652 inFunctionCall, CallType, CheckedVarArgs, 9653 UncoveredArg) {} 9654 9655 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9656 const char *startSpecifier, 9657 unsigned specifierLen) override; 9658 9659 bool HandleInvalidScanfConversionSpecifier( 9660 const analyze_scanf::ScanfSpecifier &FS, 9661 const char *startSpecifier, 9662 unsigned specifierLen) override; 9663 9664 void HandleIncompleteScanList(const char *start, const char *end) override; 9665 }; 9666 9667 } // namespace 9668 9669 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9670 const char *end) { 9671 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9672 getLocationOfByte(end), /*IsStringLocation*/true, 9673 getSpecifierRange(start, end - start)); 9674 } 9675 9676 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9677 const analyze_scanf::ScanfSpecifier &FS, 9678 const char *startSpecifier, 9679 unsigned specifierLen) { 9680 const analyze_scanf::ScanfConversionSpecifier &CS = 9681 FS.getConversionSpecifier(); 9682 9683 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9684 getLocationOfByte(CS.getStart()), 9685 startSpecifier, specifierLen, 9686 CS.getStart(), CS.getLength()); 9687 } 9688 9689 bool CheckScanfHandler::HandleScanfSpecifier( 9690 const analyze_scanf::ScanfSpecifier &FS, 9691 const char *startSpecifier, 9692 unsigned specifierLen) { 9693 using namespace analyze_scanf; 9694 using namespace analyze_format_string; 9695 9696 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9697 9698 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9699 // be used to decide if we are using positional arguments consistently. 9700 if (FS.consumesDataArgument()) { 9701 if (atFirstArg) { 9702 atFirstArg = false; 9703 usesPositionalArgs = FS.usesPositionalArg(); 9704 } 9705 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9706 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9707 startSpecifier, specifierLen); 9708 return false; 9709 } 9710 } 9711 9712 // Check if the field with is non-zero. 9713 const OptionalAmount &Amt = FS.getFieldWidth(); 9714 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9715 if (Amt.getConstantAmount() == 0) { 9716 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9717 Amt.getConstantLength()); 9718 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9719 getLocationOfByte(Amt.getStart()), 9720 /*IsStringLocation*/true, R, 9721 FixItHint::CreateRemoval(R)); 9722 } 9723 } 9724 9725 if (!FS.consumesDataArgument()) { 9726 // FIXME: Technically specifying a precision or field width here 9727 // makes no sense. Worth issuing a warning at some point. 9728 return true; 9729 } 9730 9731 // Consume the argument. 9732 unsigned argIndex = FS.getArgIndex(); 9733 if (argIndex < NumDataArgs) { 9734 // The check to see if the argIndex is valid will come later. 9735 // We set the bit here because we may exit early from this 9736 // function if we encounter some other error. 9737 CoveredArgs.set(argIndex); 9738 } 9739 9740 // Check the length modifier is valid with the given conversion specifier. 9741 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9742 S.getLangOpts())) 9743 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9744 diag::warn_format_nonsensical_length); 9745 else if (!FS.hasStandardLengthModifier()) 9746 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9747 else if (!FS.hasStandardLengthConversionCombination()) 9748 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9749 diag::warn_format_non_standard_conversion_spec); 9750 9751 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9752 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9753 9754 // The remaining checks depend on the data arguments. 9755 if (HasVAListArg) 9756 return true; 9757 9758 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9759 return false; 9760 9761 // Check that the argument type matches the format specifier. 9762 const Expr *Ex = getDataArg(argIndex); 9763 if (!Ex) 9764 return true; 9765 9766 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9767 9768 if (!AT.isValid()) { 9769 return true; 9770 } 9771 9772 analyze_format_string::ArgType::MatchKind Match = 9773 AT.matchesType(S.Context, Ex->getType()); 9774 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9775 if (Match == analyze_format_string::ArgType::Match) 9776 return true; 9777 9778 ScanfSpecifier fixedFS = FS; 9779 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9780 S.getLangOpts(), S.Context); 9781 9782 unsigned Diag = 9783 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9784 : diag::warn_format_conversion_argument_type_mismatch; 9785 9786 if (Success) { 9787 // Get the fix string from the fixed format specifier. 9788 SmallString<128> buf; 9789 llvm::raw_svector_ostream os(buf); 9790 fixedFS.toString(os); 9791 9792 EmitFormatDiagnostic( 9793 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9794 << Ex->getType() << false << Ex->getSourceRange(), 9795 Ex->getBeginLoc(), 9796 /*IsStringLocation*/ false, 9797 getSpecifierRange(startSpecifier, specifierLen), 9798 FixItHint::CreateReplacement( 9799 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9800 } else { 9801 EmitFormatDiagnostic(S.PDiag(Diag) 9802 << AT.getRepresentativeTypeName(S.Context) 9803 << Ex->getType() << false << Ex->getSourceRange(), 9804 Ex->getBeginLoc(), 9805 /*IsStringLocation*/ false, 9806 getSpecifierRange(startSpecifier, specifierLen)); 9807 } 9808 9809 return true; 9810 } 9811 9812 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9813 const Expr *OrigFormatExpr, 9814 ArrayRef<const Expr *> Args, 9815 bool HasVAListArg, unsigned format_idx, 9816 unsigned firstDataArg, 9817 Sema::FormatStringType Type, 9818 bool inFunctionCall, 9819 Sema::VariadicCallType CallType, 9820 llvm::SmallBitVector &CheckedVarArgs, 9821 UncoveredArgHandler &UncoveredArg, 9822 bool IgnoreStringsWithoutSpecifiers) { 9823 // CHECK: is the format string a wide literal? 9824 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9825 CheckFormatHandler::EmitFormatDiagnostic( 9826 S, inFunctionCall, Args[format_idx], 9827 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9828 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9829 return; 9830 } 9831 9832 // Str - The format string. NOTE: this is NOT null-terminated! 9833 StringRef StrRef = FExpr->getString(); 9834 const char *Str = StrRef.data(); 9835 // Account for cases where the string literal is truncated in a declaration. 9836 const ConstantArrayType *T = 9837 S.Context.getAsConstantArrayType(FExpr->getType()); 9838 assert(T && "String literal not of constant array type!"); 9839 size_t TypeSize = T->getSize().getZExtValue(); 9840 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9841 const unsigned numDataArgs = Args.size() - firstDataArg; 9842 9843 if (IgnoreStringsWithoutSpecifiers && 9844 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9845 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9846 return; 9847 9848 // Emit a warning if the string literal is truncated and does not contain an 9849 // embedded null character. 9850 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) { 9851 CheckFormatHandler::EmitFormatDiagnostic( 9852 S, inFunctionCall, Args[format_idx], 9853 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9854 FExpr->getBeginLoc(), 9855 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9856 return; 9857 } 9858 9859 // CHECK: empty format string? 9860 if (StrLen == 0 && numDataArgs > 0) { 9861 CheckFormatHandler::EmitFormatDiagnostic( 9862 S, inFunctionCall, Args[format_idx], 9863 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9864 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9865 return; 9866 } 9867 9868 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9869 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9870 Type == Sema::FST_OSTrace) { 9871 CheckPrintfHandler H( 9872 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9873 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9874 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9875 CheckedVarArgs, UncoveredArg); 9876 9877 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9878 S.getLangOpts(), 9879 S.Context.getTargetInfo(), 9880 Type == Sema::FST_FreeBSDKPrintf)) 9881 H.DoneProcessing(); 9882 } else if (Type == Sema::FST_Scanf) { 9883 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9884 numDataArgs, Str, HasVAListArg, Args, format_idx, 9885 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9886 9887 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9888 S.getLangOpts(), 9889 S.Context.getTargetInfo())) 9890 H.DoneProcessing(); 9891 } // TODO: handle other formats 9892 } 9893 9894 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9895 // Str - The format string. NOTE: this is NOT null-terminated! 9896 StringRef StrRef = FExpr->getString(); 9897 const char *Str = StrRef.data(); 9898 // Account for cases where the string literal is truncated in a declaration. 9899 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9900 assert(T && "String literal not of constant array type!"); 9901 size_t TypeSize = T->getSize().getZExtValue(); 9902 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9903 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9904 getLangOpts(), 9905 Context.getTargetInfo()); 9906 } 9907 9908 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9909 9910 // Returns the related absolute value function that is larger, of 0 if one 9911 // does not exist. 9912 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9913 switch (AbsFunction) { 9914 default: 9915 return 0; 9916 9917 case Builtin::BI__builtin_abs: 9918 return Builtin::BI__builtin_labs; 9919 case Builtin::BI__builtin_labs: 9920 return Builtin::BI__builtin_llabs; 9921 case Builtin::BI__builtin_llabs: 9922 return 0; 9923 9924 case Builtin::BI__builtin_fabsf: 9925 return Builtin::BI__builtin_fabs; 9926 case Builtin::BI__builtin_fabs: 9927 return Builtin::BI__builtin_fabsl; 9928 case Builtin::BI__builtin_fabsl: 9929 return 0; 9930 9931 case Builtin::BI__builtin_cabsf: 9932 return Builtin::BI__builtin_cabs; 9933 case Builtin::BI__builtin_cabs: 9934 return Builtin::BI__builtin_cabsl; 9935 case Builtin::BI__builtin_cabsl: 9936 return 0; 9937 9938 case Builtin::BIabs: 9939 return Builtin::BIlabs; 9940 case Builtin::BIlabs: 9941 return Builtin::BIllabs; 9942 case Builtin::BIllabs: 9943 return 0; 9944 9945 case Builtin::BIfabsf: 9946 return Builtin::BIfabs; 9947 case Builtin::BIfabs: 9948 return Builtin::BIfabsl; 9949 case Builtin::BIfabsl: 9950 return 0; 9951 9952 case Builtin::BIcabsf: 9953 return Builtin::BIcabs; 9954 case Builtin::BIcabs: 9955 return Builtin::BIcabsl; 9956 case Builtin::BIcabsl: 9957 return 0; 9958 } 9959 } 9960 9961 // Returns the argument type of the absolute value function. 9962 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9963 unsigned AbsType) { 9964 if (AbsType == 0) 9965 return QualType(); 9966 9967 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9968 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9969 if (Error != ASTContext::GE_None) 9970 return QualType(); 9971 9972 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9973 if (!FT) 9974 return QualType(); 9975 9976 if (FT->getNumParams() != 1) 9977 return QualType(); 9978 9979 return FT->getParamType(0); 9980 } 9981 9982 // Returns the best absolute value function, or zero, based on type and 9983 // current absolute value function. 9984 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9985 unsigned AbsFunctionKind) { 9986 unsigned BestKind = 0; 9987 uint64_t ArgSize = Context.getTypeSize(ArgType); 9988 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9989 Kind = getLargerAbsoluteValueFunction(Kind)) { 9990 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9991 if (Context.getTypeSize(ParamType) >= ArgSize) { 9992 if (BestKind == 0) 9993 BestKind = Kind; 9994 else if (Context.hasSameType(ParamType, ArgType)) { 9995 BestKind = Kind; 9996 break; 9997 } 9998 } 9999 } 10000 return BestKind; 10001 } 10002 10003 enum AbsoluteValueKind { 10004 AVK_Integer, 10005 AVK_Floating, 10006 AVK_Complex 10007 }; 10008 10009 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 10010 if (T->isIntegralOrEnumerationType()) 10011 return AVK_Integer; 10012 if (T->isRealFloatingType()) 10013 return AVK_Floating; 10014 if (T->isAnyComplexType()) 10015 return AVK_Complex; 10016 10017 llvm_unreachable("Type not integer, floating, or complex"); 10018 } 10019 10020 // Changes the absolute value function to a different type. Preserves whether 10021 // the function is a builtin. 10022 static unsigned changeAbsFunction(unsigned AbsKind, 10023 AbsoluteValueKind ValueKind) { 10024 switch (ValueKind) { 10025 case AVK_Integer: 10026 switch (AbsKind) { 10027 default: 10028 return 0; 10029 case Builtin::BI__builtin_fabsf: 10030 case Builtin::BI__builtin_fabs: 10031 case Builtin::BI__builtin_fabsl: 10032 case Builtin::BI__builtin_cabsf: 10033 case Builtin::BI__builtin_cabs: 10034 case Builtin::BI__builtin_cabsl: 10035 return Builtin::BI__builtin_abs; 10036 case Builtin::BIfabsf: 10037 case Builtin::BIfabs: 10038 case Builtin::BIfabsl: 10039 case Builtin::BIcabsf: 10040 case Builtin::BIcabs: 10041 case Builtin::BIcabsl: 10042 return Builtin::BIabs; 10043 } 10044 case AVK_Floating: 10045 switch (AbsKind) { 10046 default: 10047 return 0; 10048 case Builtin::BI__builtin_abs: 10049 case Builtin::BI__builtin_labs: 10050 case Builtin::BI__builtin_llabs: 10051 case Builtin::BI__builtin_cabsf: 10052 case Builtin::BI__builtin_cabs: 10053 case Builtin::BI__builtin_cabsl: 10054 return Builtin::BI__builtin_fabsf; 10055 case Builtin::BIabs: 10056 case Builtin::BIlabs: 10057 case Builtin::BIllabs: 10058 case Builtin::BIcabsf: 10059 case Builtin::BIcabs: 10060 case Builtin::BIcabsl: 10061 return Builtin::BIfabsf; 10062 } 10063 case AVK_Complex: 10064 switch (AbsKind) { 10065 default: 10066 return 0; 10067 case Builtin::BI__builtin_abs: 10068 case Builtin::BI__builtin_labs: 10069 case Builtin::BI__builtin_llabs: 10070 case Builtin::BI__builtin_fabsf: 10071 case Builtin::BI__builtin_fabs: 10072 case Builtin::BI__builtin_fabsl: 10073 return Builtin::BI__builtin_cabsf; 10074 case Builtin::BIabs: 10075 case Builtin::BIlabs: 10076 case Builtin::BIllabs: 10077 case Builtin::BIfabsf: 10078 case Builtin::BIfabs: 10079 case Builtin::BIfabsl: 10080 return Builtin::BIcabsf; 10081 } 10082 } 10083 llvm_unreachable("Unable to convert function"); 10084 } 10085 10086 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 10087 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 10088 if (!FnInfo) 10089 return 0; 10090 10091 switch (FDecl->getBuiltinID()) { 10092 default: 10093 return 0; 10094 case Builtin::BI__builtin_abs: 10095 case Builtin::BI__builtin_fabs: 10096 case Builtin::BI__builtin_fabsf: 10097 case Builtin::BI__builtin_fabsl: 10098 case Builtin::BI__builtin_labs: 10099 case Builtin::BI__builtin_llabs: 10100 case Builtin::BI__builtin_cabs: 10101 case Builtin::BI__builtin_cabsf: 10102 case Builtin::BI__builtin_cabsl: 10103 case Builtin::BIabs: 10104 case Builtin::BIlabs: 10105 case Builtin::BIllabs: 10106 case Builtin::BIfabs: 10107 case Builtin::BIfabsf: 10108 case Builtin::BIfabsl: 10109 case Builtin::BIcabs: 10110 case Builtin::BIcabsf: 10111 case Builtin::BIcabsl: 10112 return FDecl->getBuiltinID(); 10113 } 10114 llvm_unreachable("Unknown Builtin type"); 10115 } 10116 10117 // If the replacement is valid, emit a note with replacement function. 10118 // Additionally, suggest including the proper header if not already included. 10119 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 10120 unsigned AbsKind, QualType ArgType) { 10121 bool EmitHeaderHint = true; 10122 const char *HeaderName = nullptr; 10123 const char *FunctionName = nullptr; 10124 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 10125 FunctionName = "std::abs"; 10126 if (ArgType->isIntegralOrEnumerationType()) { 10127 HeaderName = "cstdlib"; 10128 } else if (ArgType->isRealFloatingType()) { 10129 HeaderName = "cmath"; 10130 } else { 10131 llvm_unreachable("Invalid Type"); 10132 } 10133 10134 // Lookup all std::abs 10135 if (NamespaceDecl *Std = S.getStdNamespace()) { 10136 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 10137 R.suppressDiagnostics(); 10138 S.LookupQualifiedName(R, Std); 10139 10140 for (const auto *I : R) { 10141 const FunctionDecl *FDecl = nullptr; 10142 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 10143 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 10144 } else { 10145 FDecl = dyn_cast<FunctionDecl>(I); 10146 } 10147 if (!FDecl) 10148 continue; 10149 10150 // Found std::abs(), check that they are the right ones. 10151 if (FDecl->getNumParams() != 1) 10152 continue; 10153 10154 // Check that the parameter type can handle the argument. 10155 QualType ParamType = FDecl->getParamDecl(0)->getType(); 10156 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 10157 S.Context.getTypeSize(ArgType) <= 10158 S.Context.getTypeSize(ParamType)) { 10159 // Found a function, don't need the header hint. 10160 EmitHeaderHint = false; 10161 break; 10162 } 10163 } 10164 } 10165 } else { 10166 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 10167 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 10168 10169 if (HeaderName) { 10170 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 10171 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 10172 R.suppressDiagnostics(); 10173 S.LookupName(R, S.getCurScope()); 10174 10175 if (R.isSingleResult()) { 10176 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 10177 if (FD && FD->getBuiltinID() == AbsKind) { 10178 EmitHeaderHint = false; 10179 } else { 10180 return; 10181 } 10182 } else if (!R.empty()) { 10183 return; 10184 } 10185 } 10186 } 10187 10188 S.Diag(Loc, diag::note_replace_abs_function) 10189 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 10190 10191 if (!HeaderName) 10192 return; 10193 10194 if (!EmitHeaderHint) 10195 return; 10196 10197 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 10198 << FunctionName; 10199 } 10200 10201 template <std::size_t StrLen> 10202 static bool IsStdFunction(const FunctionDecl *FDecl, 10203 const char (&Str)[StrLen]) { 10204 if (!FDecl) 10205 return false; 10206 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 10207 return false; 10208 if (!FDecl->isInStdNamespace()) 10209 return false; 10210 10211 return true; 10212 } 10213 10214 // Warn when using the wrong abs() function. 10215 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 10216 const FunctionDecl *FDecl) { 10217 if (Call->getNumArgs() != 1) 10218 return; 10219 10220 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 10221 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 10222 if (AbsKind == 0 && !IsStdAbs) 10223 return; 10224 10225 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10226 QualType ParamType = Call->getArg(0)->getType(); 10227 10228 // Unsigned types cannot be negative. Suggest removing the absolute value 10229 // function call. 10230 if (ArgType->isUnsignedIntegerType()) { 10231 const char *FunctionName = 10232 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 10233 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 10234 Diag(Call->getExprLoc(), diag::note_remove_abs) 10235 << FunctionName 10236 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 10237 return; 10238 } 10239 10240 // Taking the absolute value of a pointer is very suspicious, they probably 10241 // wanted to index into an array, dereference a pointer, call a function, etc. 10242 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 10243 unsigned DiagType = 0; 10244 if (ArgType->isFunctionType()) 10245 DiagType = 1; 10246 else if (ArgType->isArrayType()) 10247 DiagType = 2; 10248 10249 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 10250 return; 10251 } 10252 10253 // std::abs has overloads which prevent most of the absolute value problems 10254 // from occurring. 10255 if (IsStdAbs) 10256 return; 10257 10258 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 10259 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 10260 10261 // The argument and parameter are the same kind. Check if they are the right 10262 // size. 10263 if (ArgValueKind == ParamValueKind) { 10264 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 10265 return; 10266 10267 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 10268 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 10269 << FDecl << ArgType << ParamType; 10270 10271 if (NewAbsKind == 0) 10272 return; 10273 10274 emitReplacement(*this, Call->getExprLoc(), 10275 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10276 return; 10277 } 10278 10279 // ArgValueKind != ParamValueKind 10280 // The wrong type of absolute value function was used. Attempt to find the 10281 // proper one. 10282 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 10283 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 10284 if (NewAbsKind == 0) 10285 return; 10286 10287 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 10288 << FDecl << ParamValueKind << ArgValueKind; 10289 10290 emitReplacement(*this, Call->getExprLoc(), 10291 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10292 } 10293 10294 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 10295 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 10296 const FunctionDecl *FDecl) { 10297 if (!Call || !FDecl) return; 10298 10299 // Ignore template specializations and macros. 10300 if (inTemplateInstantiation()) return; 10301 if (Call->getExprLoc().isMacroID()) return; 10302 10303 // Only care about the one template argument, two function parameter std::max 10304 if (Call->getNumArgs() != 2) return; 10305 if (!IsStdFunction(FDecl, "max")) return; 10306 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 10307 if (!ArgList) return; 10308 if (ArgList->size() != 1) return; 10309 10310 // Check that template type argument is unsigned integer. 10311 const auto& TA = ArgList->get(0); 10312 if (TA.getKind() != TemplateArgument::Type) return; 10313 QualType ArgType = TA.getAsType(); 10314 if (!ArgType->isUnsignedIntegerType()) return; 10315 10316 // See if either argument is a literal zero. 10317 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 10318 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 10319 if (!MTE) return false; 10320 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 10321 if (!Num) return false; 10322 if (Num->getValue() != 0) return false; 10323 return true; 10324 }; 10325 10326 const Expr *FirstArg = Call->getArg(0); 10327 const Expr *SecondArg = Call->getArg(1); 10328 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 10329 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 10330 10331 // Only warn when exactly one argument is zero. 10332 if (IsFirstArgZero == IsSecondArgZero) return; 10333 10334 SourceRange FirstRange = FirstArg->getSourceRange(); 10335 SourceRange SecondRange = SecondArg->getSourceRange(); 10336 10337 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 10338 10339 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 10340 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 10341 10342 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 10343 SourceRange RemovalRange; 10344 if (IsFirstArgZero) { 10345 RemovalRange = SourceRange(FirstRange.getBegin(), 10346 SecondRange.getBegin().getLocWithOffset(-1)); 10347 } else { 10348 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 10349 SecondRange.getEnd()); 10350 } 10351 10352 Diag(Call->getExprLoc(), diag::note_remove_max_call) 10353 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 10354 << FixItHint::CreateRemoval(RemovalRange); 10355 } 10356 10357 //===--- CHECK: Standard memory functions ---------------------------------===// 10358 10359 /// Takes the expression passed to the size_t parameter of functions 10360 /// such as memcmp, strncat, etc and warns if it's a comparison. 10361 /// 10362 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 10363 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 10364 IdentifierInfo *FnName, 10365 SourceLocation FnLoc, 10366 SourceLocation RParenLoc) { 10367 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 10368 if (!Size) 10369 return false; 10370 10371 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 10372 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 10373 return false; 10374 10375 SourceRange SizeRange = Size->getSourceRange(); 10376 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 10377 << SizeRange << FnName; 10378 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 10379 << FnName 10380 << FixItHint::CreateInsertion( 10381 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 10382 << FixItHint::CreateRemoval(RParenLoc); 10383 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 10384 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 10385 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 10386 ")"); 10387 10388 return true; 10389 } 10390 10391 /// Determine whether the given type is or contains a dynamic class type 10392 /// (e.g., whether it has a vtable). 10393 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 10394 bool &IsContained) { 10395 // Look through array types while ignoring qualifiers. 10396 const Type *Ty = T->getBaseElementTypeUnsafe(); 10397 IsContained = false; 10398 10399 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 10400 RD = RD ? RD->getDefinition() : nullptr; 10401 if (!RD || RD->isInvalidDecl()) 10402 return nullptr; 10403 10404 if (RD->isDynamicClass()) 10405 return RD; 10406 10407 // Check all the fields. If any bases were dynamic, the class is dynamic. 10408 // It's impossible for a class to transitively contain itself by value, so 10409 // infinite recursion is impossible. 10410 for (auto *FD : RD->fields()) { 10411 bool SubContained; 10412 if (const CXXRecordDecl *ContainedRD = 10413 getContainedDynamicClass(FD->getType(), SubContained)) { 10414 IsContained = true; 10415 return ContainedRD; 10416 } 10417 } 10418 10419 return nullptr; 10420 } 10421 10422 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 10423 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 10424 if (Unary->getKind() == UETT_SizeOf) 10425 return Unary; 10426 return nullptr; 10427 } 10428 10429 /// If E is a sizeof expression, returns its argument expression, 10430 /// otherwise returns NULL. 10431 static const Expr *getSizeOfExprArg(const Expr *E) { 10432 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10433 if (!SizeOf->isArgumentType()) 10434 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 10435 return nullptr; 10436 } 10437 10438 /// If E is a sizeof expression, returns its argument type. 10439 static QualType getSizeOfArgType(const Expr *E) { 10440 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10441 return SizeOf->getTypeOfArgument(); 10442 return QualType(); 10443 } 10444 10445 namespace { 10446 10447 struct SearchNonTrivialToInitializeField 10448 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 10449 using Super = 10450 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 10451 10452 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 10453 10454 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 10455 SourceLocation SL) { 10456 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10457 asDerived().visitArray(PDIK, AT, SL); 10458 return; 10459 } 10460 10461 Super::visitWithKind(PDIK, FT, SL); 10462 } 10463 10464 void visitARCStrong(QualType FT, SourceLocation SL) { 10465 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10466 } 10467 void visitARCWeak(QualType FT, SourceLocation SL) { 10468 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10469 } 10470 void visitStruct(QualType FT, SourceLocation SL) { 10471 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10472 visit(FD->getType(), FD->getLocation()); 10473 } 10474 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 10475 const ArrayType *AT, SourceLocation SL) { 10476 visit(getContext().getBaseElementType(AT), SL); 10477 } 10478 void visitTrivial(QualType FT, SourceLocation SL) {} 10479 10480 static void diag(QualType RT, const Expr *E, Sema &S) { 10481 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 10482 } 10483 10484 ASTContext &getContext() { return S.getASTContext(); } 10485 10486 const Expr *E; 10487 Sema &S; 10488 }; 10489 10490 struct SearchNonTrivialToCopyField 10491 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 10492 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 10493 10494 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 10495 10496 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 10497 SourceLocation SL) { 10498 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10499 asDerived().visitArray(PCK, AT, SL); 10500 return; 10501 } 10502 10503 Super::visitWithKind(PCK, FT, SL); 10504 } 10505 10506 void visitARCStrong(QualType FT, SourceLocation SL) { 10507 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10508 } 10509 void visitARCWeak(QualType FT, SourceLocation SL) { 10510 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10511 } 10512 void visitStruct(QualType FT, SourceLocation SL) { 10513 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10514 visit(FD->getType(), FD->getLocation()); 10515 } 10516 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 10517 SourceLocation SL) { 10518 visit(getContext().getBaseElementType(AT), SL); 10519 } 10520 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 10521 SourceLocation SL) {} 10522 void visitTrivial(QualType FT, SourceLocation SL) {} 10523 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 10524 10525 static void diag(QualType RT, const Expr *E, Sema &S) { 10526 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 10527 } 10528 10529 ASTContext &getContext() { return S.getASTContext(); } 10530 10531 const Expr *E; 10532 Sema &S; 10533 }; 10534 10535 } 10536 10537 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 10538 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 10539 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 10540 10541 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 10542 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 10543 return false; 10544 10545 return doesExprLikelyComputeSize(BO->getLHS()) || 10546 doesExprLikelyComputeSize(BO->getRHS()); 10547 } 10548 10549 return getAsSizeOfExpr(SizeofExpr) != nullptr; 10550 } 10551 10552 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 10553 /// 10554 /// \code 10555 /// #define MACRO 0 10556 /// foo(MACRO); 10557 /// foo(0); 10558 /// \endcode 10559 /// 10560 /// This should return true for the first call to foo, but not for the second 10561 /// (regardless of whether foo is a macro or function). 10562 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10563 SourceLocation CallLoc, 10564 SourceLocation ArgLoc) { 10565 if (!CallLoc.isMacroID()) 10566 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10567 10568 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10569 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10570 } 10571 10572 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10573 /// last two arguments transposed. 10574 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10575 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10576 return; 10577 10578 const Expr *SizeArg = 10579 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10580 10581 auto isLiteralZero = [](const Expr *E) { 10582 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10583 }; 10584 10585 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10586 SourceLocation CallLoc = Call->getRParenLoc(); 10587 SourceManager &SM = S.getSourceManager(); 10588 if (isLiteralZero(SizeArg) && 10589 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10590 10591 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10592 10593 // Some platforms #define bzero to __builtin_memset. See if this is the 10594 // case, and if so, emit a better diagnostic. 10595 if (BId == Builtin::BIbzero || 10596 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10597 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10598 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10599 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10600 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10601 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10602 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10603 } 10604 return; 10605 } 10606 10607 // If the second argument to a memset is a sizeof expression and the third 10608 // isn't, this is also likely an error. This should catch 10609 // 'memset(buf, sizeof(buf), 0xff)'. 10610 if (BId == Builtin::BImemset && 10611 doesExprLikelyComputeSize(Call->getArg(1)) && 10612 !doesExprLikelyComputeSize(Call->getArg(2))) { 10613 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10614 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10615 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10616 return; 10617 } 10618 } 10619 10620 /// Check for dangerous or invalid arguments to memset(). 10621 /// 10622 /// This issues warnings on known problematic, dangerous or unspecified 10623 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10624 /// function calls. 10625 /// 10626 /// \param Call The call expression to diagnose. 10627 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10628 unsigned BId, 10629 IdentifierInfo *FnName) { 10630 assert(BId != 0); 10631 10632 // It is possible to have a non-standard definition of memset. Validate 10633 // we have enough arguments, and if not, abort further checking. 10634 unsigned ExpectedNumArgs = 10635 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10636 if (Call->getNumArgs() < ExpectedNumArgs) 10637 return; 10638 10639 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10640 BId == Builtin::BIstrndup ? 1 : 2); 10641 unsigned LenArg = 10642 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10643 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10644 10645 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10646 Call->getBeginLoc(), Call->getRParenLoc())) 10647 return; 10648 10649 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10650 CheckMemaccessSize(*this, BId, Call); 10651 10652 // We have special checking when the length is a sizeof expression. 10653 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10654 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10655 llvm::FoldingSetNodeID SizeOfArgID; 10656 10657 // Although widely used, 'bzero' is not a standard function. Be more strict 10658 // with the argument types before allowing diagnostics and only allow the 10659 // form bzero(ptr, sizeof(...)). 10660 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10661 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10662 return; 10663 10664 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10665 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10666 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10667 10668 QualType DestTy = Dest->getType(); 10669 QualType PointeeTy; 10670 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10671 PointeeTy = DestPtrTy->getPointeeType(); 10672 10673 // Never warn about void type pointers. This can be used to suppress 10674 // false positives. 10675 if (PointeeTy->isVoidType()) 10676 continue; 10677 10678 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10679 // actually comparing the expressions for equality. Because computing the 10680 // expression IDs can be expensive, we only do this if the diagnostic is 10681 // enabled. 10682 if (SizeOfArg && 10683 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10684 SizeOfArg->getExprLoc())) { 10685 // We only compute IDs for expressions if the warning is enabled, and 10686 // cache the sizeof arg's ID. 10687 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10688 SizeOfArg->Profile(SizeOfArgID, Context, true); 10689 llvm::FoldingSetNodeID DestID; 10690 Dest->Profile(DestID, Context, true); 10691 if (DestID == SizeOfArgID) { 10692 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10693 // over sizeof(src) as well. 10694 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10695 StringRef ReadableName = FnName->getName(); 10696 10697 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10698 if (UnaryOp->getOpcode() == UO_AddrOf) 10699 ActionIdx = 1; // If its an address-of operator, just remove it. 10700 if (!PointeeTy->isIncompleteType() && 10701 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10702 ActionIdx = 2; // If the pointee's size is sizeof(char), 10703 // suggest an explicit length. 10704 10705 // If the function is defined as a builtin macro, do not show macro 10706 // expansion. 10707 SourceLocation SL = SizeOfArg->getExprLoc(); 10708 SourceRange DSR = Dest->getSourceRange(); 10709 SourceRange SSR = SizeOfArg->getSourceRange(); 10710 SourceManager &SM = getSourceManager(); 10711 10712 if (SM.isMacroArgExpansion(SL)) { 10713 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10714 SL = SM.getSpellingLoc(SL); 10715 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10716 SM.getSpellingLoc(DSR.getEnd())); 10717 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10718 SM.getSpellingLoc(SSR.getEnd())); 10719 } 10720 10721 DiagRuntimeBehavior(SL, SizeOfArg, 10722 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10723 << ReadableName 10724 << PointeeTy 10725 << DestTy 10726 << DSR 10727 << SSR); 10728 DiagRuntimeBehavior(SL, SizeOfArg, 10729 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10730 << ActionIdx 10731 << SSR); 10732 10733 break; 10734 } 10735 } 10736 10737 // Also check for cases where the sizeof argument is the exact same 10738 // type as the memory argument, and where it points to a user-defined 10739 // record type. 10740 if (SizeOfArgTy != QualType()) { 10741 if (PointeeTy->isRecordType() && 10742 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10743 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10744 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10745 << FnName << SizeOfArgTy << ArgIdx 10746 << PointeeTy << Dest->getSourceRange() 10747 << LenExpr->getSourceRange()); 10748 break; 10749 } 10750 } 10751 } else if (DestTy->isArrayType()) { 10752 PointeeTy = DestTy; 10753 } 10754 10755 if (PointeeTy == QualType()) 10756 continue; 10757 10758 // Always complain about dynamic classes. 10759 bool IsContained; 10760 if (const CXXRecordDecl *ContainedRD = 10761 getContainedDynamicClass(PointeeTy, IsContained)) { 10762 10763 unsigned OperationType = 0; 10764 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10765 // "overwritten" if we're warning about the destination for any call 10766 // but memcmp; otherwise a verb appropriate to the call. 10767 if (ArgIdx != 0 || IsCmp) { 10768 if (BId == Builtin::BImemcpy) 10769 OperationType = 1; 10770 else if(BId == Builtin::BImemmove) 10771 OperationType = 2; 10772 else if (IsCmp) 10773 OperationType = 3; 10774 } 10775 10776 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10777 PDiag(diag::warn_dyn_class_memaccess) 10778 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10779 << IsContained << ContainedRD << OperationType 10780 << Call->getCallee()->getSourceRange()); 10781 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10782 BId != Builtin::BImemset) 10783 DiagRuntimeBehavior( 10784 Dest->getExprLoc(), Dest, 10785 PDiag(diag::warn_arc_object_memaccess) 10786 << ArgIdx << FnName << PointeeTy 10787 << Call->getCallee()->getSourceRange()); 10788 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10789 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10790 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10791 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10792 PDiag(diag::warn_cstruct_memaccess) 10793 << ArgIdx << FnName << PointeeTy << 0); 10794 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10795 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10796 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10797 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10798 PDiag(diag::warn_cstruct_memaccess) 10799 << ArgIdx << FnName << PointeeTy << 1); 10800 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10801 } else { 10802 continue; 10803 } 10804 } else 10805 continue; 10806 10807 DiagRuntimeBehavior( 10808 Dest->getExprLoc(), Dest, 10809 PDiag(diag::note_bad_memaccess_silence) 10810 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10811 break; 10812 } 10813 } 10814 10815 // A little helper routine: ignore addition and subtraction of integer literals. 10816 // This intentionally does not ignore all integer constant expressions because 10817 // we don't want to remove sizeof(). 10818 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10819 Ex = Ex->IgnoreParenCasts(); 10820 10821 while (true) { 10822 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10823 if (!BO || !BO->isAdditiveOp()) 10824 break; 10825 10826 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10827 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10828 10829 if (isa<IntegerLiteral>(RHS)) 10830 Ex = LHS; 10831 else if (isa<IntegerLiteral>(LHS)) 10832 Ex = RHS; 10833 else 10834 break; 10835 } 10836 10837 return Ex; 10838 } 10839 10840 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10841 ASTContext &Context) { 10842 // Only handle constant-sized or VLAs, but not flexible members. 10843 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10844 // Only issue the FIXIT for arrays of size > 1. 10845 if (CAT->getSize().getSExtValue() <= 1) 10846 return false; 10847 } else if (!Ty->isVariableArrayType()) { 10848 return false; 10849 } 10850 return true; 10851 } 10852 10853 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10854 // be the size of the source, instead of the destination. 10855 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10856 IdentifierInfo *FnName) { 10857 10858 // Don't crash if the user has the wrong number of arguments 10859 unsigned NumArgs = Call->getNumArgs(); 10860 if ((NumArgs != 3) && (NumArgs != 4)) 10861 return; 10862 10863 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10864 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10865 const Expr *CompareWithSrc = nullptr; 10866 10867 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10868 Call->getBeginLoc(), Call->getRParenLoc())) 10869 return; 10870 10871 // Look for 'strlcpy(dst, x, sizeof(x))' 10872 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10873 CompareWithSrc = Ex; 10874 else { 10875 // Look for 'strlcpy(dst, x, strlen(x))' 10876 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10877 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10878 SizeCall->getNumArgs() == 1) 10879 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10880 } 10881 } 10882 10883 if (!CompareWithSrc) 10884 return; 10885 10886 // Determine if the argument to sizeof/strlen is equal to the source 10887 // argument. In principle there's all kinds of things you could do 10888 // here, for instance creating an == expression and evaluating it with 10889 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10890 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10891 if (!SrcArgDRE) 10892 return; 10893 10894 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10895 if (!CompareWithSrcDRE || 10896 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10897 return; 10898 10899 const Expr *OriginalSizeArg = Call->getArg(2); 10900 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10901 << OriginalSizeArg->getSourceRange() << FnName; 10902 10903 // Output a FIXIT hint if the destination is an array (rather than a 10904 // pointer to an array). This could be enhanced to handle some 10905 // pointers if we know the actual size, like if DstArg is 'array+2' 10906 // we could say 'sizeof(array)-2'. 10907 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10908 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10909 return; 10910 10911 SmallString<128> sizeString; 10912 llvm::raw_svector_ostream OS(sizeString); 10913 OS << "sizeof("; 10914 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10915 OS << ")"; 10916 10917 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10918 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10919 OS.str()); 10920 } 10921 10922 /// Check if two expressions refer to the same declaration. 10923 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10924 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10925 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10926 return D1->getDecl() == D2->getDecl(); 10927 return false; 10928 } 10929 10930 static const Expr *getStrlenExprArg(const Expr *E) { 10931 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10932 const FunctionDecl *FD = CE->getDirectCallee(); 10933 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10934 return nullptr; 10935 return CE->getArg(0)->IgnoreParenCasts(); 10936 } 10937 return nullptr; 10938 } 10939 10940 // Warn on anti-patterns as the 'size' argument to strncat. 10941 // The correct size argument should look like following: 10942 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10943 void Sema::CheckStrncatArguments(const CallExpr *CE, 10944 IdentifierInfo *FnName) { 10945 // Don't crash if the user has the wrong number of arguments. 10946 if (CE->getNumArgs() < 3) 10947 return; 10948 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10949 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10950 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10951 10952 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10953 CE->getRParenLoc())) 10954 return; 10955 10956 // Identify common expressions, which are wrongly used as the size argument 10957 // to strncat and may lead to buffer overflows. 10958 unsigned PatternType = 0; 10959 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10960 // - sizeof(dst) 10961 if (referToTheSameDecl(SizeOfArg, DstArg)) 10962 PatternType = 1; 10963 // - sizeof(src) 10964 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10965 PatternType = 2; 10966 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10967 if (BE->getOpcode() == BO_Sub) { 10968 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10969 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10970 // - sizeof(dst) - strlen(dst) 10971 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10972 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10973 PatternType = 1; 10974 // - sizeof(src) - (anything) 10975 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10976 PatternType = 2; 10977 } 10978 } 10979 10980 if (PatternType == 0) 10981 return; 10982 10983 // Generate the diagnostic. 10984 SourceLocation SL = LenArg->getBeginLoc(); 10985 SourceRange SR = LenArg->getSourceRange(); 10986 SourceManager &SM = getSourceManager(); 10987 10988 // If the function is defined as a builtin macro, do not show macro expansion. 10989 if (SM.isMacroArgExpansion(SL)) { 10990 SL = SM.getSpellingLoc(SL); 10991 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10992 SM.getSpellingLoc(SR.getEnd())); 10993 } 10994 10995 // Check if the destination is an array (rather than a pointer to an array). 10996 QualType DstTy = DstArg->getType(); 10997 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10998 Context); 10999 if (!isKnownSizeArray) { 11000 if (PatternType == 1) 11001 Diag(SL, diag::warn_strncat_wrong_size) << SR; 11002 else 11003 Diag(SL, diag::warn_strncat_src_size) << SR; 11004 return; 11005 } 11006 11007 if (PatternType == 1) 11008 Diag(SL, diag::warn_strncat_large_size) << SR; 11009 else 11010 Diag(SL, diag::warn_strncat_src_size) << SR; 11011 11012 SmallString<128> sizeString; 11013 llvm::raw_svector_ostream OS(sizeString); 11014 OS << "sizeof("; 11015 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11016 OS << ") - "; 11017 OS << "strlen("; 11018 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11019 OS << ") - 1"; 11020 11021 Diag(SL, diag::note_strncat_wrong_size) 11022 << FixItHint::CreateReplacement(SR, OS.str()); 11023 } 11024 11025 namespace { 11026 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 11027 const UnaryOperator *UnaryExpr, const Decl *D) { 11028 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 11029 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 11030 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 11031 return; 11032 } 11033 } 11034 11035 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 11036 const UnaryOperator *UnaryExpr) { 11037 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 11038 const Decl *D = Lvalue->getDecl(); 11039 if (isa<DeclaratorDecl>(D)) 11040 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType()) 11041 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 11042 } 11043 11044 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 11045 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 11046 Lvalue->getMemberDecl()); 11047 } 11048 11049 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 11050 const UnaryOperator *UnaryExpr) { 11051 const auto *Lambda = dyn_cast<LambdaExpr>( 11052 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 11053 if (!Lambda) 11054 return; 11055 11056 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 11057 << CalleeName << 2 /*object: lambda expression*/; 11058 } 11059 11060 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 11061 const DeclRefExpr *Lvalue) { 11062 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 11063 if (Var == nullptr) 11064 return; 11065 11066 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 11067 << CalleeName << 0 /*object: */ << Var; 11068 } 11069 11070 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 11071 const CastExpr *Cast) { 11072 SmallString<128> SizeString; 11073 llvm::raw_svector_ostream OS(SizeString); 11074 11075 clang::CastKind Kind = Cast->getCastKind(); 11076 if (Kind == clang::CK_BitCast && 11077 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 11078 return; 11079 if (Kind == clang::CK_IntegralToPointer && 11080 !isa<IntegerLiteral>( 11081 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 11082 return; 11083 11084 switch (Cast->getCastKind()) { 11085 case clang::CK_BitCast: 11086 case clang::CK_IntegralToPointer: 11087 case clang::CK_FunctionToPointerDecay: 11088 OS << '\''; 11089 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 11090 OS << '\''; 11091 break; 11092 default: 11093 return; 11094 } 11095 11096 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 11097 << CalleeName << 0 /*object: */ << OS.str(); 11098 } 11099 } // namespace 11100 11101 /// Alerts the user that they are attempting to free a non-malloc'd object. 11102 void Sema::CheckFreeArguments(const CallExpr *E) { 11103 const std::string CalleeName = 11104 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 11105 11106 { // Prefer something that doesn't involve a cast to make things simpler. 11107 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 11108 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 11109 switch (UnaryExpr->getOpcode()) { 11110 case UnaryOperator::Opcode::UO_AddrOf: 11111 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 11112 case UnaryOperator::Opcode::UO_Plus: 11113 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 11114 default: 11115 break; 11116 } 11117 11118 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 11119 if (Lvalue->getType()->isArrayType()) 11120 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 11121 11122 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 11123 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 11124 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 11125 return; 11126 } 11127 11128 if (isa<BlockExpr>(Arg)) { 11129 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 11130 << CalleeName << 1 /*object: block*/; 11131 return; 11132 } 11133 } 11134 // Maybe the cast was important, check after the other cases. 11135 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 11136 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 11137 } 11138 11139 void 11140 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 11141 SourceLocation ReturnLoc, 11142 bool isObjCMethod, 11143 const AttrVec *Attrs, 11144 const FunctionDecl *FD) { 11145 // Check if the return value is null but should not be. 11146 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 11147 (!isObjCMethod && isNonNullType(Context, lhsType))) && 11148 CheckNonNullExpr(*this, RetValExp)) 11149 Diag(ReturnLoc, diag::warn_null_ret) 11150 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 11151 11152 // C++11 [basic.stc.dynamic.allocation]p4: 11153 // If an allocation function declared with a non-throwing 11154 // exception-specification fails to allocate storage, it shall return 11155 // a null pointer. Any other allocation function that fails to allocate 11156 // storage shall indicate failure only by throwing an exception [...] 11157 if (FD) { 11158 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 11159 if (Op == OO_New || Op == OO_Array_New) { 11160 const FunctionProtoType *Proto 11161 = FD->getType()->castAs<FunctionProtoType>(); 11162 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 11163 CheckNonNullExpr(*this, RetValExp)) 11164 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 11165 << FD << getLangOpts().CPlusPlus11; 11166 } 11167 } 11168 11169 // PPC MMA non-pointer types are not allowed as return type. Checking the type 11170 // here prevent the user from using a PPC MMA type as trailing return type. 11171 if (Context.getTargetInfo().getTriple().isPPC64()) 11172 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 11173 } 11174 11175 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 11176 11177 /// Check for comparisons of floating point operands using != and ==. 11178 /// Issue a warning if these are no self-comparisons, as they are not likely 11179 /// to do what the programmer intended. 11180 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 11181 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 11182 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 11183 11184 // Special case: check for x == x (which is OK). 11185 // Do not emit warnings for such cases. 11186 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 11187 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 11188 if (DRL->getDecl() == DRR->getDecl()) 11189 return; 11190 11191 // Special case: check for comparisons against literals that can be exactly 11192 // represented by APFloat. In such cases, do not emit a warning. This 11193 // is a heuristic: often comparison against such literals are used to 11194 // detect if a value in a variable has not changed. This clearly can 11195 // lead to false negatives. 11196 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 11197 if (FLL->isExact()) 11198 return; 11199 } else 11200 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 11201 if (FLR->isExact()) 11202 return; 11203 11204 // Check for comparisons with builtin types. 11205 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 11206 if (CL->getBuiltinCallee()) 11207 return; 11208 11209 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 11210 if (CR->getBuiltinCallee()) 11211 return; 11212 11213 // Emit the diagnostic. 11214 Diag(Loc, diag::warn_floatingpoint_eq) 11215 << LHS->getSourceRange() << RHS->getSourceRange(); 11216 } 11217 11218 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 11219 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 11220 11221 namespace { 11222 11223 /// Structure recording the 'active' range of an integer-valued 11224 /// expression. 11225 struct IntRange { 11226 /// The number of bits active in the int. Note that this includes exactly one 11227 /// sign bit if !NonNegative. 11228 unsigned Width; 11229 11230 /// True if the int is known not to have negative values. If so, all leading 11231 /// bits before Width are known zero, otherwise they are known to be the 11232 /// same as the MSB within Width. 11233 bool NonNegative; 11234 11235 IntRange(unsigned Width, bool NonNegative) 11236 : Width(Width), NonNegative(NonNegative) {} 11237 11238 /// Number of bits excluding the sign bit. 11239 unsigned valueBits() const { 11240 return NonNegative ? Width : Width - 1; 11241 } 11242 11243 /// Returns the range of the bool type. 11244 static IntRange forBoolType() { 11245 return IntRange(1, true); 11246 } 11247 11248 /// Returns the range of an opaque value of the given integral type. 11249 static IntRange forValueOfType(ASTContext &C, QualType T) { 11250 return forValueOfCanonicalType(C, 11251 T->getCanonicalTypeInternal().getTypePtr()); 11252 } 11253 11254 /// Returns the range of an opaque value of a canonical integral type. 11255 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 11256 assert(T->isCanonicalUnqualified()); 11257 11258 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11259 T = VT->getElementType().getTypePtr(); 11260 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11261 T = CT->getElementType().getTypePtr(); 11262 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11263 T = AT->getValueType().getTypePtr(); 11264 11265 if (!C.getLangOpts().CPlusPlus) { 11266 // For enum types in C code, use the underlying datatype. 11267 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11268 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 11269 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 11270 // For enum types in C++, use the known bit width of the enumerators. 11271 EnumDecl *Enum = ET->getDecl(); 11272 // In C++11, enums can have a fixed underlying type. Use this type to 11273 // compute the range. 11274 if (Enum->isFixed()) { 11275 return IntRange(C.getIntWidth(QualType(T, 0)), 11276 !ET->isSignedIntegerOrEnumerationType()); 11277 } 11278 11279 unsigned NumPositive = Enum->getNumPositiveBits(); 11280 unsigned NumNegative = Enum->getNumNegativeBits(); 11281 11282 if (NumNegative == 0) 11283 return IntRange(NumPositive, true/*NonNegative*/); 11284 else 11285 return IntRange(std::max(NumPositive + 1, NumNegative), 11286 false/*NonNegative*/); 11287 } 11288 11289 if (const auto *EIT = dyn_cast<BitIntType>(T)) 11290 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11291 11292 const BuiltinType *BT = cast<BuiltinType>(T); 11293 assert(BT->isInteger()); 11294 11295 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11296 } 11297 11298 /// Returns the "target" range of a canonical integral type, i.e. 11299 /// the range of values expressible in the type. 11300 /// 11301 /// This matches forValueOfCanonicalType except that enums have the 11302 /// full range of their type, not the range of their enumerators. 11303 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 11304 assert(T->isCanonicalUnqualified()); 11305 11306 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11307 T = VT->getElementType().getTypePtr(); 11308 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11309 T = CT->getElementType().getTypePtr(); 11310 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11311 T = AT->getValueType().getTypePtr(); 11312 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11313 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 11314 11315 if (const auto *EIT = dyn_cast<BitIntType>(T)) 11316 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11317 11318 const BuiltinType *BT = cast<BuiltinType>(T); 11319 assert(BT->isInteger()); 11320 11321 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11322 } 11323 11324 /// Returns the supremum of two ranges: i.e. their conservative merge. 11325 static IntRange join(IntRange L, IntRange R) { 11326 bool Unsigned = L.NonNegative && R.NonNegative; 11327 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 11328 L.NonNegative && R.NonNegative); 11329 } 11330 11331 /// Return the range of a bitwise-AND of the two ranges. 11332 static IntRange bit_and(IntRange L, IntRange R) { 11333 unsigned Bits = std::max(L.Width, R.Width); 11334 bool NonNegative = false; 11335 if (L.NonNegative) { 11336 Bits = std::min(Bits, L.Width); 11337 NonNegative = true; 11338 } 11339 if (R.NonNegative) { 11340 Bits = std::min(Bits, R.Width); 11341 NonNegative = true; 11342 } 11343 return IntRange(Bits, NonNegative); 11344 } 11345 11346 /// Return the range of a sum of the two ranges. 11347 static IntRange sum(IntRange L, IntRange R) { 11348 bool Unsigned = L.NonNegative && R.NonNegative; 11349 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 11350 Unsigned); 11351 } 11352 11353 /// Return the range of a difference of the two ranges. 11354 static IntRange difference(IntRange L, IntRange R) { 11355 // We need a 1-bit-wider range if: 11356 // 1) LHS can be negative: least value can be reduced. 11357 // 2) RHS can be negative: greatest value can be increased. 11358 bool CanWiden = !L.NonNegative || !R.NonNegative; 11359 bool Unsigned = L.NonNegative && R.Width == 0; 11360 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 11361 !Unsigned, 11362 Unsigned); 11363 } 11364 11365 /// Return the range of a product of the two ranges. 11366 static IntRange product(IntRange L, IntRange R) { 11367 // If both LHS and RHS can be negative, we can form 11368 // -2^L * -2^R = 2^(L + R) 11369 // which requires L + R + 1 value bits to represent. 11370 bool CanWiden = !L.NonNegative && !R.NonNegative; 11371 bool Unsigned = L.NonNegative && R.NonNegative; 11372 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 11373 Unsigned); 11374 } 11375 11376 /// Return the range of a remainder operation between the two ranges. 11377 static IntRange rem(IntRange L, IntRange R) { 11378 // The result of a remainder can't be larger than the result of 11379 // either side. The sign of the result is the sign of the LHS. 11380 bool Unsigned = L.NonNegative; 11381 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 11382 Unsigned); 11383 } 11384 }; 11385 11386 } // namespace 11387 11388 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 11389 unsigned MaxWidth) { 11390 if (value.isSigned() && value.isNegative()) 11391 return IntRange(value.getMinSignedBits(), false); 11392 11393 if (value.getBitWidth() > MaxWidth) 11394 value = value.trunc(MaxWidth); 11395 11396 // isNonNegative() just checks the sign bit without considering 11397 // signedness. 11398 return IntRange(value.getActiveBits(), true); 11399 } 11400 11401 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 11402 unsigned MaxWidth) { 11403 if (result.isInt()) 11404 return GetValueRange(C, result.getInt(), MaxWidth); 11405 11406 if (result.isVector()) { 11407 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 11408 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 11409 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 11410 R = IntRange::join(R, El); 11411 } 11412 return R; 11413 } 11414 11415 if (result.isComplexInt()) { 11416 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 11417 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 11418 return IntRange::join(R, I); 11419 } 11420 11421 // This can happen with lossless casts to intptr_t of "based" lvalues. 11422 // Assume it might use arbitrary bits. 11423 // FIXME: The only reason we need to pass the type in here is to get 11424 // the sign right on this one case. It would be nice if APValue 11425 // preserved this. 11426 assert(result.isLValue() || result.isAddrLabelDiff()); 11427 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 11428 } 11429 11430 static QualType GetExprType(const Expr *E) { 11431 QualType Ty = E->getType(); 11432 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 11433 Ty = AtomicRHS->getValueType(); 11434 return Ty; 11435 } 11436 11437 /// Pseudo-evaluate the given integer expression, estimating the 11438 /// range of values it might take. 11439 /// 11440 /// \param MaxWidth The width to which the value will be truncated. 11441 /// \param Approximate If \c true, return a likely range for the result: in 11442 /// particular, assume that arithmetic on narrower types doesn't leave 11443 /// those types. If \c false, return a range including all possible 11444 /// result values. 11445 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 11446 bool InConstantContext, bool Approximate) { 11447 E = E->IgnoreParens(); 11448 11449 // Try a full evaluation first. 11450 Expr::EvalResult result; 11451 if (E->EvaluateAsRValue(result, C, InConstantContext)) 11452 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 11453 11454 // I think we only want to look through implicit casts here; if the 11455 // user has an explicit widening cast, we should treat the value as 11456 // being of the new, wider type. 11457 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 11458 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 11459 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 11460 Approximate); 11461 11462 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 11463 11464 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 11465 CE->getCastKind() == CK_BooleanToSignedIntegral; 11466 11467 // Assume that non-integer casts can span the full range of the type. 11468 if (!isIntegerCast) 11469 return OutputTypeRange; 11470 11471 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 11472 std::min(MaxWidth, OutputTypeRange.Width), 11473 InConstantContext, Approximate); 11474 11475 // Bail out if the subexpr's range is as wide as the cast type. 11476 if (SubRange.Width >= OutputTypeRange.Width) 11477 return OutputTypeRange; 11478 11479 // Otherwise, we take the smaller width, and we're non-negative if 11480 // either the output type or the subexpr is. 11481 return IntRange(SubRange.Width, 11482 SubRange.NonNegative || OutputTypeRange.NonNegative); 11483 } 11484 11485 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11486 // If we can fold the condition, just take that operand. 11487 bool CondResult; 11488 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 11489 return GetExprRange(C, 11490 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 11491 MaxWidth, InConstantContext, Approximate); 11492 11493 // Otherwise, conservatively merge. 11494 // GetExprRange requires an integer expression, but a throw expression 11495 // results in a void type. 11496 Expr *E = CO->getTrueExpr(); 11497 IntRange L = E->getType()->isVoidType() 11498 ? IntRange{0, true} 11499 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11500 E = CO->getFalseExpr(); 11501 IntRange R = E->getType()->isVoidType() 11502 ? IntRange{0, true} 11503 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11504 return IntRange::join(L, R); 11505 } 11506 11507 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11508 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 11509 11510 switch (BO->getOpcode()) { 11511 case BO_Cmp: 11512 llvm_unreachable("builtin <=> should have class type"); 11513 11514 // Boolean-valued operations are single-bit and positive. 11515 case BO_LAnd: 11516 case BO_LOr: 11517 case BO_LT: 11518 case BO_GT: 11519 case BO_LE: 11520 case BO_GE: 11521 case BO_EQ: 11522 case BO_NE: 11523 return IntRange::forBoolType(); 11524 11525 // The type of the assignments is the type of the LHS, so the RHS 11526 // is not necessarily the same type. 11527 case BO_MulAssign: 11528 case BO_DivAssign: 11529 case BO_RemAssign: 11530 case BO_AddAssign: 11531 case BO_SubAssign: 11532 case BO_XorAssign: 11533 case BO_OrAssign: 11534 // TODO: bitfields? 11535 return IntRange::forValueOfType(C, GetExprType(E)); 11536 11537 // Simple assignments just pass through the RHS, which will have 11538 // been coerced to the LHS type. 11539 case BO_Assign: 11540 // TODO: bitfields? 11541 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11542 Approximate); 11543 11544 // Operations with opaque sources are black-listed. 11545 case BO_PtrMemD: 11546 case BO_PtrMemI: 11547 return IntRange::forValueOfType(C, GetExprType(E)); 11548 11549 // Bitwise-and uses the *infinum* of the two source ranges. 11550 case BO_And: 11551 case BO_AndAssign: 11552 Combine = IntRange::bit_and; 11553 break; 11554 11555 // Left shift gets black-listed based on a judgement call. 11556 case BO_Shl: 11557 // ...except that we want to treat '1 << (blah)' as logically 11558 // positive. It's an important idiom. 11559 if (IntegerLiteral *I 11560 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11561 if (I->getValue() == 1) { 11562 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11563 return IntRange(R.Width, /*NonNegative*/ true); 11564 } 11565 } 11566 LLVM_FALLTHROUGH; 11567 11568 case BO_ShlAssign: 11569 return IntRange::forValueOfType(C, GetExprType(E)); 11570 11571 // Right shift by a constant can narrow its left argument. 11572 case BO_Shr: 11573 case BO_ShrAssign: { 11574 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11575 Approximate); 11576 11577 // If the shift amount is a positive constant, drop the width by 11578 // that much. 11579 if (Optional<llvm::APSInt> shift = 11580 BO->getRHS()->getIntegerConstantExpr(C)) { 11581 if (shift->isNonNegative()) { 11582 unsigned zext = shift->getZExtValue(); 11583 if (zext >= L.Width) 11584 L.Width = (L.NonNegative ? 0 : 1); 11585 else 11586 L.Width -= zext; 11587 } 11588 } 11589 11590 return L; 11591 } 11592 11593 // Comma acts as its right operand. 11594 case BO_Comma: 11595 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11596 Approximate); 11597 11598 case BO_Add: 11599 if (!Approximate) 11600 Combine = IntRange::sum; 11601 break; 11602 11603 case BO_Sub: 11604 if (BO->getLHS()->getType()->isPointerType()) 11605 return IntRange::forValueOfType(C, GetExprType(E)); 11606 if (!Approximate) 11607 Combine = IntRange::difference; 11608 break; 11609 11610 case BO_Mul: 11611 if (!Approximate) 11612 Combine = IntRange::product; 11613 break; 11614 11615 // The width of a division result is mostly determined by the size 11616 // of the LHS. 11617 case BO_Div: { 11618 // Don't 'pre-truncate' the operands. 11619 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11620 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11621 Approximate); 11622 11623 // If the divisor is constant, use that. 11624 if (Optional<llvm::APSInt> divisor = 11625 BO->getRHS()->getIntegerConstantExpr(C)) { 11626 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11627 if (log2 >= L.Width) 11628 L.Width = (L.NonNegative ? 0 : 1); 11629 else 11630 L.Width = std::min(L.Width - log2, MaxWidth); 11631 return L; 11632 } 11633 11634 // Otherwise, just use the LHS's width. 11635 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11636 // could be -1. 11637 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11638 Approximate); 11639 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11640 } 11641 11642 case BO_Rem: 11643 Combine = IntRange::rem; 11644 break; 11645 11646 // The default behavior is okay for these. 11647 case BO_Xor: 11648 case BO_Or: 11649 break; 11650 } 11651 11652 // Combine the two ranges, but limit the result to the type in which we 11653 // performed the computation. 11654 QualType T = GetExprType(E); 11655 unsigned opWidth = C.getIntWidth(T); 11656 IntRange L = 11657 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11658 IntRange R = 11659 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11660 IntRange C = Combine(L, R); 11661 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11662 C.Width = std::min(C.Width, MaxWidth); 11663 return C; 11664 } 11665 11666 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11667 switch (UO->getOpcode()) { 11668 // Boolean-valued operations are white-listed. 11669 case UO_LNot: 11670 return IntRange::forBoolType(); 11671 11672 // Operations with opaque sources are black-listed. 11673 case UO_Deref: 11674 case UO_AddrOf: // should be impossible 11675 return IntRange::forValueOfType(C, GetExprType(E)); 11676 11677 default: 11678 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11679 Approximate); 11680 } 11681 } 11682 11683 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11684 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11685 Approximate); 11686 11687 if (const auto *BitField = E->getSourceBitField()) 11688 return IntRange(BitField->getBitWidthValue(C), 11689 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11690 11691 return IntRange::forValueOfType(C, GetExprType(E)); 11692 } 11693 11694 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11695 bool InConstantContext, bool Approximate) { 11696 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11697 Approximate); 11698 } 11699 11700 /// Checks whether the given value, which currently has the given 11701 /// source semantics, has the same value when coerced through the 11702 /// target semantics. 11703 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11704 const llvm::fltSemantics &Src, 11705 const llvm::fltSemantics &Tgt) { 11706 llvm::APFloat truncated = value; 11707 11708 bool ignored; 11709 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11710 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11711 11712 return truncated.bitwiseIsEqual(value); 11713 } 11714 11715 /// Checks whether the given value, which currently has the given 11716 /// source semantics, has the same value when coerced through the 11717 /// target semantics. 11718 /// 11719 /// The value might be a vector of floats (or a complex number). 11720 static bool IsSameFloatAfterCast(const APValue &value, 11721 const llvm::fltSemantics &Src, 11722 const llvm::fltSemantics &Tgt) { 11723 if (value.isFloat()) 11724 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11725 11726 if (value.isVector()) { 11727 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11728 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11729 return false; 11730 return true; 11731 } 11732 11733 assert(value.isComplexFloat()); 11734 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11735 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11736 } 11737 11738 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11739 bool IsListInit = false); 11740 11741 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11742 // Suppress cases where we are comparing against an enum constant. 11743 if (const DeclRefExpr *DR = 11744 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11745 if (isa<EnumConstantDecl>(DR->getDecl())) 11746 return true; 11747 11748 // Suppress cases where the value is expanded from a macro, unless that macro 11749 // is how a language represents a boolean literal. This is the case in both C 11750 // and Objective-C. 11751 SourceLocation BeginLoc = E->getBeginLoc(); 11752 if (BeginLoc.isMacroID()) { 11753 StringRef MacroName = Lexer::getImmediateMacroName( 11754 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11755 return MacroName != "YES" && MacroName != "NO" && 11756 MacroName != "true" && MacroName != "false"; 11757 } 11758 11759 return false; 11760 } 11761 11762 static bool isKnownToHaveUnsignedValue(Expr *E) { 11763 return E->getType()->isIntegerType() && 11764 (!E->getType()->isSignedIntegerType() || 11765 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11766 } 11767 11768 namespace { 11769 /// The promoted range of values of a type. In general this has the 11770 /// following structure: 11771 /// 11772 /// |-----------| . . . |-----------| 11773 /// ^ ^ ^ ^ 11774 /// Min HoleMin HoleMax Max 11775 /// 11776 /// ... where there is only a hole if a signed type is promoted to unsigned 11777 /// (in which case Min and Max are the smallest and largest representable 11778 /// values). 11779 struct PromotedRange { 11780 // Min, or HoleMax if there is a hole. 11781 llvm::APSInt PromotedMin; 11782 // Max, or HoleMin if there is a hole. 11783 llvm::APSInt PromotedMax; 11784 11785 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11786 if (R.Width == 0) 11787 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11788 else if (R.Width >= BitWidth && !Unsigned) { 11789 // Promotion made the type *narrower*. This happens when promoting 11790 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11791 // Treat all values of 'signed int' as being in range for now. 11792 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11793 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11794 } else { 11795 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11796 .extOrTrunc(BitWidth); 11797 PromotedMin.setIsUnsigned(Unsigned); 11798 11799 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11800 .extOrTrunc(BitWidth); 11801 PromotedMax.setIsUnsigned(Unsigned); 11802 } 11803 } 11804 11805 // Determine whether this range is contiguous (has no hole). 11806 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11807 11808 // Where a constant value is within the range. 11809 enum ComparisonResult { 11810 LT = 0x1, 11811 LE = 0x2, 11812 GT = 0x4, 11813 GE = 0x8, 11814 EQ = 0x10, 11815 NE = 0x20, 11816 InRangeFlag = 0x40, 11817 11818 Less = LE | LT | NE, 11819 Min = LE | InRangeFlag, 11820 InRange = InRangeFlag, 11821 Max = GE | InRangeFlag, 11822 Greater = GE | GT | NE, 11823 11824 OnlyValue = LE | GE | EQ | InRangeFlag, 11825 InHole = NE 11826 }; 11827 11828 ComparisonResult compare(const llvm::APSInt &Value) const { 11829 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11830 Value.isUnsigned() == PromotedMin.isUnsigned()); 11831 if (!isContiguous()) { 11832 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11833 if (Value.isMinValue()) return Min; 11834 if (Value.isMaxValue()) return Max; 11835 if (Value >= PromotedMin) return InRange; 11836 if (Value <= PromotedMax) return InRange; 11837 return InHole; 11838 } 11839 11840 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11841 case -1: return Less; 11842 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11843 case 1: 11844 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11845 case -1: return InRange; 11846 case 0: return Max; 11847 case 1: return Greater; 11848 } 11849 } 11850 11851 llvm_unreachable("impossible compare result"); 11852 } 11853 11854 static llvm::Optional<StringRef> 11855 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11856 if (Op == BO_Cmp) { 11857 ComparisonResult LTFlag = LT, GTFlag = GT; 11858 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11859 11860 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11861 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11862 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11863 return llvm::None; 11864 } 11865 11866 ComparisonResult TrueFlag, FalseFlag; 11867 if (Op == BO_EQ) { 11868 TrueFlag = EQ; 11869 FalseFlag = NE; 11870 } else if (Op == BO_NE) { 11871 TrueFlag = NE; 11872 FalseFlag = EQ; 11873 } else { 11874 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11875 TrueFlag = LT; 11876 FalseFlag = GE; 11877 } else { 11878 TrueFlag = GT; 11879 FalseFlag = LE; 11880 } 11881 if (Op == BO_GE || Op == BO_LE) 11882 std::swap(TrueFlag, FalseFlag); 11883 } 11884 if (R & TrueFlag) 11885 return StringRef("true"); 11886 if (R & FalseFlag) 11887 return StringRef("false"); 11888 return llvm::None; 11889 } 11890 }; 11891 } 11892 11893 static bool HasEnumType(Expr *E) { 11894 // Strip off implicit integral promotions. 11895 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11896 if (ICE->getCastKind() != CK_IntegralCast && 11897 ICE->getCastKind() != CK_NoOp) 11898 break; 11899 E = ICE->getSubExpr(); 11900 } 11901 11902 return E->getType()->isEnumeralType(); 11903 } 11904 11905 static int classifyConstantValue(Expr *Constant) { 11906 // The values of this enumeration are used in the diagnostics 11907 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11908 enum ConstantValueKind { 11909 Miscellaneous = 0, 11910 LiteralTrue, 11911 LiteralFalse 11912 }; 11913 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11914 return BL->getValue() ? ConstantValueKind::LiteralTrue 11915 : ConstantValueKind::LiteralFalse; 11916 return ConstantValueKind::Miscellaneous; 11917 } 11918 11919 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11920 Expr *Constant, Expr *Other, 11921 const llvm::APSInt &Value, 11922 bool RhsConstant) { 11923 if (S.inTemplateInstantiation()) 11924 return false; 11925 11926 Expr *OriginalOther = Other; 11927 11928 Constant = Constant->IgnoreParenImpCasts(); 11929 Other = Other->IgnoreParenImpCasts(); 11930 11931 // Suppress warnings on tautological comparisons between values of the same 11932 // enumeration type. There are only two ways we could warn on this: 11933 // - If the constant is outside the range of representable values of 11934 // the enumeration. In such a case, we should warn about the cast 11935 // to enumeration type, not about the comparison. 11936 // - If the constant is the maximum / minimum in-range value. For an 11937 // enumeratin type, such comparisons can be meaningful and useful. 11938 if (Constant->getType()->isEnumeralType() && 11939 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11940 return false; 11941 11942 IntRange OtherValueRange = GetExprRange( 11943 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11944 11945 QualType OtherT = Other->getType(); 11946 if (const auto *AT = OtherT->getAs<AtomicType>()) 11947 OtherT = AT->getValueType(); 11948 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11949 11950 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11951 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11952 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11953 S.NSAPIObj->isObjCBOOLType(OtherT) && 11954 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11955 11956 // Whether we're treating Other as being a bool because of the form of 11957 // expression despite it having another type (typically 'int' in C). 11958 bool OtherIsBooleanDespiteType = 11959 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11960 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11961 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11962 11963 // Check if all values in the range of possible values of this expression 11964 // lead to the same comparison outcome. 11965 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11966 Value.isUnsigned()); 11967 auto Cmp = OtherPromotedValueRange.compare(Value); 11968 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11969 if (!Result) 11970 return false; 11971 11972 // Also consider the range determined by the type alone. This allows us to 11973 // classify the warning under the proper diagnostic group. 11974 bool TautologicalTypeCompare = false; 11975 { 11976 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11977 Value.isUnsigned()); 11978 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11979 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11980 RhsConstant)) { 11981 TautologicalTypeCompare = true; 11982 Cmp = TypeCmp; 11983 Result = TypeResult; 11984 } 11985 } 11986 11987 // Don't warn if the non-constant operand actually always evaluates to the 11988 // same value. 11989 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11990 return false; 11991 11992 // Suppress the diagnostic for an in-range comparison if the constant comes 11993 // from a macro or enumerator. We don't want to diagnose 11994 // 11995 // some_long_value <= INT_MAX 11996 // 11997 // when sizeof(int) == sizeof(long). 11998 bool InRange = Cmp & PromotedRange::InRangeFlag; 11999 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 12000 return false; 12001 12002 // A comparison of an unsigned bit-field against 0 is really a type problem, 12003 // even though at the type level the bit-field might promote to 'signed int'. 12004 if (Other->refersToBitField() && InRange && Value == 0 && 12005 Other->getType()->isUnsignedIntegerOrEnumerationType()) 12006 TautologicalTypeCompare = true; 12007 12008 // If this is a comparison to an enum constant, include that 12009 // constant in the diagnostic. 12010 const EnumConstantDecl *ED = nullptr; 12011 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 12012 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 12013 12014 // Should be enough for uint128 (39 decimal digits) 12015 SmallString<64> PrettySourceValue; 12016 llvm::raw_svector_ostream OS(PrettySourceValue); 12017 if (ED) { 12018 OS << '\'' << *ED << "' (" << Value << ")"; 12019 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 12020 Constant->IgnoreParenImpCasts())) { 12021 OS << (BL->getValue() ? "YES" : "NO"); 12022 } else { 12023 OS << Value; 12024 } 12025 12026 if (!TautologicalTypeCompare) { 12027 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 12028 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 12029 << E->getOpcodeStr() << OS.str() << *Result 12030 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 12031 return true; 12032 } 12033 12034 if (IsObjCSignedCharBool) { 12035 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12036 S.PDiag(diag::warn_tautological_compare_objc_bool) 12037 << OS.str() << *Result); 12038 return true; 12039 } 12040 12041 // FIXME: We use a somewhat different formatting for the in-range cases and 12042 // cases involving boolean values for historical reasons. We should pick a 12043 // consistent way of presenting these diagnostics. 12044 if (!InRange || Other->isKnownToHaveBooleanValue()) { 12045 12046 S.DiagRuntimeBehavior( 12047 E->getOperatorLoc(), E, 12048 S.PDiag(!InRange ? diag::warn_out_of_range_compare 12049 : diag::warn_tautological_bool_compare) 12050 << OS.str() << classifyConstantValue(Constant) << OtherT 12051 << OtherIsBooleanDespiteType << *Result 12052 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 12053 } else { 12054 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 12055 unsigned Diag = 12056 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 12057 ? (HasEnumType(OriginalOther) 12058 ? diag::warn_unsigned_enum_always_true_comparison 12059 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 12060 : diag::warn_unsigned_always_true_comparison) 12061 : diag::warn_tautological_constant_compare; 12062 12063 S.Diag(E->getOperatorLoc(), Diag) 12064 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 12065 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 12066 } 12067 12068 return true; 12069 } 12070 12071 /// Analyze the operands of the given comparison. Implements the 12072 /// fallback case from AnalyzeComparison. 12073 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 12074 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12075 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12076 } 12077 12078 /// Implements -Wsign-compare. 12079 /// 12080 /// \param E the binary operator to check for warnings 12081 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 12082 // The type the comparison is being performed in. 12083 QualType T = E->getLHS()->getType(); 12084 12085 // Only analyze comparison operators where both sides have been converted to 12086 // the same type. 12087 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 12088 return AnalyzeImpConvsInComparison(S, E); 12089 12090 // Don't analyze value-dependent comparisons directly. 12091 if (E->isValueDependent()) 12092 return AnalyzeImpConvsInComparison(S, E); 12093 12094 Expr *LHS = E->getLHS(); 12095 Expr *RHS = E->getRHS(); 12096 12097 if (T->isIntegralType(S.Context)) { 12098 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 12099 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 12100 12101 // We don't care about expressions whose result is a constant. 12102 if (RHSValue && LHSValue) 12103 return AnalyzeImpConvsInComparison(S, E); 12104 12105 // We only care about expressions where just one side is literal 12106 if ((bool)RHSValue ^ (bool)LHSValue) { 12107 // Is the constant on the RHS or LHS? 12108 const bool RhsConstant = (bool)RHSValue; 12109 Expr *Const = RhsConstant ? RHS : LHS; 12110 Expr *Other = RhsConstant ? LHS : RHS; 12111 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 12112 12113 // Check whether an integer constant comparison results in a value 12114 // of 'true' or 'false'. 12115 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 12116 return AnalyzeImpConvsInComparison(S, E); 12117 } 12118 } 12119 12120 if (!T->hasUnsignedIntegerRepresentation()) { 12121 // We don't do anything special if this isn't an unsigned integral 12122 // comparison: we're only interested in integral comparisons, and 12123 // signed comparisons only happen in cases we don't care to warn about. 12124 return AnalyzeImpConvsInComparison(S, E); 12125 } 12126 12127 LHS = LHS->IgnoreParenImpCasts(); 12128 RHS = RHS->IgnoreParenImpCasts(); 12129 12130 if (!S.getLangOpts().CPlusPlus) { 12131 // Avoid warning about comparison of integers with different signs when 12132 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 12133 // the type of `E`. 12134 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 12135 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12136 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 12137 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12138 } 12139 12140 // Check to see if one of the (unmodified) operands is of different 12141 // signedness. 12142 Expr *signedOperand, *unsignedOperand; 12143 if (LHS->getType()->hasSignedIntegerRepresentation()) { 12144 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 12145 "unsigned comparison between two signed integer expressions?"); 12146 signedOperand = LHS; 12147 unsignedOperand = RHS; 12148 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 12149 signedOperand = RHS; 12150 unsignedOperand = LHS; 12151 } else { 12152 return AnalyzeImpConvsInComparison(S, E); 12153 } 12154 12155 // Otherwise, calculate the effective range of the signed operand. 12156 IntRange signedRange = GetExprRange( 12157 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 12158 12159 // Go ahead and analyze implicit conversions in the operands. Note 12160 // that we skip the implicit conversions on both sides. 12161 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 12162 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 12163 12164 // If the signed range is non-negative, -Wsign-compare won't fire. 12165 if (signedRange.NonNegative) 12166 return; 12167 12168 // For (in)equality comparisons, if the unsigned operand is a 12169 // constant which cannot collide with a overflowed signed operand, 12170 // then reinterpreting the signed operand as unsigned will not 12171 // change the result of the comparison. 12172 if (E->isEqualityOp()) { 12173 unsigned comparisonWidth = S.Context.getIntWidth(T); 12174 IntRange unsignedRange = 12175 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 12176 /*Approximate*/ true); 12177 12178 // We should never be unable to prove that the unsigned operand is 12179 // non-negative. 12180 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 12181 12182 if (unsignedRange.Width < comparisonWidth) 12183 return; 12184 } 12185 12186 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12187 S.PDiag(diag::warn_mixed_sign_comparison) 12188 << LHS->getType() << RHS->getType() 12189 << LHS->getSourceRange() << RHS->getSourceRange()); 12190 } 12191 12192 /// Analyzes an attempt to assign the given value to a bitfield. 12193 /// 12194 /// Returns true if there was something fishy about the attempt. 12195 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 12196 SourceLocation InitLoc) { 12197 assert(Bitfield->isBitField()); 12198 if (Bitfield->isInvalidDecl()) 12199 return false; 12200 12201 // White-list bool bitfields. 12202 QualType BitfieldType = Bitfield->getType(); 12203 if (BitfieldType->isBooleanType()) 12204 return false; 12205 12206 if (BitfieldType->isEnumeralType()) { 12207 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 12208 // If the underlying enum type was not explicitly specified as an unsigned 12209 // type and the enum contain only positive values, MSVC++ will cause an 12210 // inconsistency by storing this as a signed type. 12211 if (S.getLangOpts().CPlusPlus11 && 12212 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 12213 BitfieldEnumDecl->getNumPositiveBits() > 0 && 12214 BitfieldEnumDecl->getNumNegativeBits() == 0) { 12215 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 12216 << BitfieldEnumDecl; 12217 } 12218 } 12219 12220 if (Bitfield->getType()->isBooleanType()) 12221 return false; 12222 12223 // Ignore value- or type-dependent expressions. 12224 if (Bitfield->getBitWidth()->isValueDependent() || 12225 Bitfield->getBitWidth()->isTypeDependent() || 12226 Init->isValueDependent() || 12227 Init->isTypeDependent()) 12228 return false; 12229 12230 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 12231 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 12232 12233 Expr::EvalResult Result; 12234 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 12235 Expr::SE_AllowSideEffects)) { 12236 // The RHS is not constant. If the RHS has an enum type, make sure the 12237 // bitfield is wide enough to hold all the values of the enum without 12238 // truncation. 12239 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 12240 EnumDecl *ED = EnumTy->getDecl(); 12241 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 12242 12243 // Enum types are implicitly signed on Windows, so check if there are any 12244 // negative enumerators to see if the enum was intended to be signed or 12245 // not. 12246 bool SignedEnum = ED->getNumNegativeBits() > 0; 12247 12248 // Check for surprising sign changes when assigning enum values to a 12249 // bitfield of different signedness. If the bitfield is signed and we 12250 // have exactly the right number of bits to store this unsigned enum, 12251 // suggest changing the enum to an unsigned type. This typically happens 12252 // on Windows where unfixed enums always use an underlying type of 'int'. 12253 unsigned DiagID = 0; 12254 if (SignedEnum && !SignedBitfield) { 12255 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 12256 } else if (SignedBitfield && !SignedEnum && 12257 ED->getNumPositiveBits() == FieldWidth) { 12258 DiagID = diag::warn_signed_bitfield_enum_conversion; 12259 } 12260 12261 if (DiagID) { 12262 S.Diag(InitLoc, DiagID) << Bitfield << ED; 12263 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 12264 SourceRange TypeRange = 12265 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 12266 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 12267 << SignedEnum << TypeRange; 12268 } 12269 12270 // Compute the required bitwidth. If the enum has negative values, we need 12271 // one more bit than the normal number of positive bits to represent the 12272 // sign bit. 12273 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 12274 ED->getNumNegativeBits()) 12275 : ED->getNumPositiveBits(); 12276 12277 // Check the bitwidth. 12278 if (BitsNeeded > FieldWidth) { 12279 Expr *WidthExpr = Bitfield->getBitWidth(); 12280 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 12281 << Bitfield << ED; 12282 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 12283 << BitsNeeded << ED << WidthExpr->getSourceRange(); 12284 } 12285 } 12286 12287 return false; 12288 } 12289 12290 llvm::APSInt Value = Result.Val.getInt(); 12291 12292 unsigned OriginalWidth = Value.getBitWidth(); 12293 12294 if (!Value.isSigned() || Value.isNegative()) 12295 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 12296 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 12297 OriginalWidth = Value.getMinSignedBits(); 12298 12299 if (OriginalWidth <= FieldWidth) 12300 return false; 12301 12302 // Compute the value which the bitfield will contain. 12303 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 12304 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 12305 12306 // Check whether the stored value is equal to the original value. 12307 TruncatedValue = TruncatedValue.extend(OriginalWidth); 12308 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 12309 return false; 12310 12311 // Special-case bitfields of width 1: booleans are naturally 0/1, and 12312 // therefore don't strictly fit into a signed bitfield of width 1. 12313 if (FieldWidth == 1 && Value == 1) 12314 return false; 12315 12316 std::string PrettyValue = toString(Value, 10); 12317 std::string PrettyTrunc = toString(TruncatedValue, 10); 12318 12319 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 12320 << PrettyValue << PrettyTrunc << OriginalInit->getType() 12321 << Init->getSourceRange(); 12322 12323 return true; 12324 } 12325 12326 /// Analyze the given simple or compound assignment for warning-worthy 12327 /// operations. 12328 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 12329 // Just recurse on the LHS. 12330 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12331 12332 // We want to recurse on the RHS as normal unless we're assigning to 12333 // a bitfield. 12334 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 12335 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 12336 E->getOperatorLoc())) { 12337 // Recurse, ignoring any implicit conversions on the RHS. 12338 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 12339 E->getOperatorLoc()); 12340 } 12341 } 12342 12343 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12344 12345 // Diagnose implicitly sequentially-consistent atomic assignment. 12346 if (E->getLHS()->getType()->isAtomicType()) 12347 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12348 } 12349 12350 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12351 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 12352 SourceLocation CContext, unsigned diag, 12353 bool pruneControlFlow = false) { 12354 if (pruneControlFlow) { 12355 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12356 S.PDiag(diag) 12357 << SourceType << T << E->getSourceRange() 12358 << SourceRange(CContext)); 12359 return; 12360 } 12361 S.Diag(E->getExprLoc(), diag) 12362 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 12363 } 12364 12365 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12366 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 12367 SourceLocation CContext, 12368 unsigned diag, bool pruneControlFlow = false) { 12369 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 12370 } 12371 12372 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 12373 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 12374 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 12375 } 12376 12377 static void adornObjCBoolConversionDiagWithTernaryFixit( 12378 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 12379 Expr *Ignored = SourceExpr->IgnoreImplicit(); 12380 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 12381 Ignored = OVE->getSourceExpr(); 12382 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 12383 isa<BinaryOperator>(Ignored) || 12384 isa<CXXOperatorCallExpr>(Ignored); 12385 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 12386 if (NeedsParens) 12387 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 12388 << FixItHint::CreateInsertion(EndLoc, ")"); 12389 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 12390 } 12391 12392 /// Diagnose an implicit cast from a floating point value to an integer value. 12393 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 12394 SourceLocation CContext) { 12395 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 12396 const bool PruneWarnings = S.inTemplateInstantiation(); 12397 12398 Expr *InnerE = E->IgnoreParenImpCasts(); 12399 // We also want to warn on, e.g., "int i = -1.234" 12400 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 12401 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 12402 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 12403 12404 const bool IsLiteral = 12405 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 12406 12407 llvm::APFloat Value(0.0); 12408 bool IsConstant = 12409 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 12410 if (!IsConstant) { 12411 if (isObjCSignedCharBool(S, T)) { 12412 return adornObjCBoolConversionDiagWithTernaryFixit( 12413 S, E, 12414 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 12415 << E->getType()); 12416 } 12417 12418 return DiagnoseImpCast(S, E, T, CContext, 12419 diag::warn_impcast_float_integer, PruneWarnings); 12420 } 12421 12422 bool isExact = false; 12423 12424 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 12425 T->hasUnsignedIntegerRepresentation()); 12426 llvm::APFloat::opStatus Result = Value.convertToInteger( 12427 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 12428 12429 // FIXME: Force the precision of the source value down so we don't print 12430 // digits which are usually useless (we don't really care here if we 12431 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 12432 // would automatically print the shortest representation, but it's a bit 12433 // tricky to implement. 12434 SmallString<16> PrettySourceValue; 12435 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 12436 precision = (precision * 59 + 195) / 196; 12437 Value.toString(PrettySourceValue, precision); 12438 12439 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 12440 return adornObjCBoolConversionDiagWithTernaryFixit( 12441 S, E, 12442 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 12443 << PrettySourceValue); 12444 } 12445 12446 if (Result == llvm::APFloat::opOK && isExact) { 12447 if (IsLiteral) return; 12448 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 12449 PruneWarnings); 12450 } 12451 12452 // Conversion of a floating-point value to a non-bool integer where the 12453 // integral part cannot be represented by the integer type is undefined. 12454 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 12455 return DiagnoseImpCast( 12456 S, E, T, CContext, 12457 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 12458 : diag::warn_impcast_float_to_integer_out_of_range, 12459 PruneWarnings); 12460 12461 unsigned DiagID = 0; 12462 if (IsLiteral) { 12463 // Warn on floating point literal to integer. 12464 DiagID = diag::warn_impcast_literal_float_to_integer; 12465 } else if (IntegerValue == 0) { 12466 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 12467 return DiagnoseImpCast(S, E, T, CContext, 12468 diag::warn_impcast_float_integer, PruneWarnings); 12469 } 12470 // Warn on non-zero to zero conversion. 12471 DiagID = diag::warn_impcast_float_to_integer_zero; 12472 } else { 12473 if (IntegerValue.isUnsigned()) { 12474 if (!IntegerValue.isMaxValue()) { 12475 return DiagnoseImpCast(S, E, T, CContext, 12476 diag::warn_impcast_float_integer, PruneWarnings); 12477 } 12478 } else { // IntegerValue.isSigned() 12479 if (!IntegerValue.isMaxSignedValue() && 12480 !IntegerValue.isMinSignedValue()) { 12481 return DiagnoseImpCast(S, E, T, CContext, 12482 diag::warn_impcast_float_integer, PruneWarnings); 12483 } 12484 } 12485 // Warn on evaluatable floating point expression to integer conversion. 12486 DiagID = diag::warn_impcast_float_to_integer; 12487 } 12488 12489 SmallString<16> PrettyTargetValue; 12490 if (IsBool) 12491 PrettyTargetValue = Value.isZero() ? "false" : "true"; 12492 else 12493 IntegerValue.toString(PrettyTargetValue); 12494 12495 if (PruneWarnings) { 12496 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12497 S.PDiag(DiagID) 12498 << E->getType() << T.getUnqualifiedType() 12499 << PrettySourceValue << PrettyTargetValue 12500 << E->getSourceRange() << SourceRange(CContext)); 12501 } else { 12502 S.Diag(E->getExprLoc(), DiagID) 12503 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 12504 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 12505 } 12506 } 12507 12508 /// Analyze the given compound assignment for the possible losing of 12509 /// floating-point precision. 12510 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 12511 assert(isa<CompoundAssignOperator>(E) && 12512 "Must be compound assignment operation"); 12513 // Recurse on the LHS and RHS in here 12514 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12515 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12516 12517 if (E->getLHS()->getType()->isAtomicType()) 12518 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 12519 12520 // Now check the outermost expression 12521 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 12522 const auto *RBT = cast<CompoundAssignOperator>(E) 12523 ->getComputationResultType() 12524 ->getAs<BuiltinType>(); 12525 12526 // The below checks assume source is floating point. 12527 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 12528 12529 // If source is floating point but target is an integer. 12530 if (ResultBT->isInteger()) 12531 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 12532 E->getExprLoc(), diag::warn_impcast_float_integer); 12533 12534 if (!ResultBT->isFloatingPoint()) 12535 return; 12536 12537 // If both source and target are floating points, warn about losing precision. 12538 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12539 QualType(ResultBT, 0), QualType(RBT, 0)); 12540 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 12541 // warn about dropping FP rank. 12542 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 12543 diag::warn_impcast_float_result_precision); 12544 } 12545 12546 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 12547 IntRange Range) { 12548 if (!Range.Width) return "0"; 12549 12550 llvm::APSInt ValueInRange = Value; 12551 ValueInRange.setIsSigned(!Range.NonNegative); 12552 ValueInRange = ValueInRange.trunc(Range.Width); 12553 return toString(ValueInRange, 10); 12554 } 12555 12556 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 12557 if (!isa<ImplicitCastExpr>(Ex)) 12558 return false; 12559 12560 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12561 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12562 const Type *Source = 12563 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12564 if (Target->isDependentType()) 12565 return false; 12566 12567 const BuiltinType *FloatCandidateBT = 12568 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12569 const Type *BoolCandidateType = ToBool ? Target : Source; 12570 12571 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12572 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12573 } 12574 12575 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12576 SourceLocation CC) { 12577 unsigned NumArgs = TheCall->getNumArgs(); 12578 for (unsigned i = 0; i < NumArgs; ++i) { 12579 Expr *CurrA = TheCall->getArg(i); 12580 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12581 continue; 12582 12583 bool IsSwapped = ((i > 0) && 12584 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12585 IsSwapped |= ((i < (NumArgs - 1)) && 12586 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12587 if (IsSwapped) { 12588 // Warn on this floating-point to bool conversion. 12589 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12590 CurrA->getType(), CC, 12591 diag::warn_impcast_floating_point_to_bool); 12592 } 12593 } 12594 } 12595 12596 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12597 SourceLocation CC) { 12598 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12599 E->getExprLoc())) 12600 return; 12601 12602 // Don't warn on functions which have return type nullptr_t. 12603 if (isa<CallExpr>(E)) 12604 return; 12605 12606 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12607 const Expr::NullPointerConstantKind NullKind = 12608 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12609 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12610 return; 12611 12612 // Return if target type is a safe conversion. 12613 if (T->isAnyPointerType() || T->isBlockPointerType() || 12614 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12615 return; 12616 12617 SourceLocation Loc = E->getSourceRange().getBegin(); 12618 12619 // Venture through the macro stacks to get to the source of macro arguments. 12620 // The new location is a better location than the complete location that was 12621 // passed in. 12622 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12623 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12624 12625 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12626 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12627 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12628 Loc, S.SourceMgr, S.getLangOpts()); 12629 if (MacroName == "NULL") 12630 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12631 } 12632 12633 // Only warn if the null and context location are in the same macro expansion. 12634 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12635 return; 12636 12637 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12638 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12639 << FixItHint::CreateReplacement(Loc, 12640 S.getFixItZeroLiteralForType(T, Loc)); 12641 } 12642 12643 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12644 ObjCArrayLiteral *ArrayLiteral); 12645 12646 static void 12647 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12648 ObjCDictionaryLiteral *DictionaryLiteral); 12649 12650 /// Check a single element within a collection literal against the 12651 /// target element type. 12652 static void checkObjCCollectionLiteralElement(Sema &S, 12653 QualType TargetElementType, 12654 Expr *Element, 12655 unsigned ElementKind) { 12656 // Skip a bitcast to 'id' or qualified 'id'. 12657 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12658 if (ICE->getCastKind() == CK_BitCast && 12659 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12660 Element = ICE->getSubExpr(); 12661 } 12662 12663 QualType ElementType = Element->getType(); 12664 ExprResult ElementResult(Element); 12665 if (ElementType->getAs<ObjCObjectPointerType>() && 12666 S.CheckSingleAssignmentConstraints(TargetElementType, 12667 ElementResult, 12668 false, false) 12669 != Sema::Compatible) { 12670 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12671 << ElementType << ElementKind << TargetElementType 12672 << Element->getSourceRange(); 12673 } 12674 12675 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12676 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12677 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12678 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12679 } 12680 12681 /// Check an Objective-C array literal being converted to the given 12682 /// target type. 12683 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12684 ObjCArrayLiteral *ArrayLiteral) { 12685 if (!S.NSArrayDecl) 12686 return; 12687 12688 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12689 if (!TargetObjCPtr) 12690 return; 12691 12692 if (TargetObjCPtr->isUnspecialized() || 12693 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12694 != S.NSArrayDecl->getCanonicalDecl()) 12695 return; 12696 12697 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12698 if (TypeArgs.size() != 1) 12699 return; 12700 12701 QualType TargetElementType = TypeArgs[0]; 12702 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12703 checkObjCCollectionLiteralElement(S, TargetElementType, 12704 ArrayLiteral->getElement(I), 12705 0); 12706 } 12707 } 12708 12709 /// Check an Objective-C dictionary literal being converted to the given 12710 /// target type. 12711 static void 12712 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12713 ObjCDictionaryLiteral *DictionaryLiteral) { 12714 if (!S.NSDictionaryDecl) 12715 return; 12716 12717 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12718 if (!TargetObjCPtr) 12719 return; 12720 12721 if (TargetObjCPtr->isUnspecialized() || 12722 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12723 != S.NSDictionaryDecl->getCanonicalDecl()) 12724 return; 12725 12726 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12727 if (TypeArgs.size() != 2) 12728 return; 12729 12730 QualType TargetKeyType = TypeArgs[0]; 12731 QualType TargetObjectType = TypeArgs[1]; 12732 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12733 auto Element = DictionaryLiteral->getKeyValueElement(I); 12734 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12735 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12736 } 12737 } 12738 12739 // Helper function to filter out cases for constant width constant conversion. 12740 // Don't warn on char array initialization or for non-decimal values. 12741 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12742 SourceLocation CC) { 12743 // If initializing from a constant, and the constant starts with '0', 12744 // then it is a binary, octal, or hexadecimal. Allow these constants 12745 // to fill all the bits, even if there is a sign change. 12746 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12747 const char FirstLiteralCharacter = 12748 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12749 if (FirstLiteralCharacter == '0') 12750 return false; 12751 } 12752 12753 // If the CC location points to a '{', and the type is char, then assume 12754 // assume it is an array initialization. 12755 if (CC.isValid() && T->isCharType()) { 12756 const char FirstContextCharacter = 12757 S.getSourceManager().getCharacterData(CC)[0]; 12758 if (FirstContextCharacter == '{') 12759 return false; 12760 } 12761 12762 return true; 12763 } 12764 12765 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12766 const auto *IL = dyn_cast<IntegerLiteral>(E); 12767 if (!IL) { 12768 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12769 if (UO->getOpcode() == UO_Minus) 12770 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12771 } 12772 } 12773 12774 return IL; 12775 } 12776 12777 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12778 E = E->IgnoreParenImpCasts(); 12779 SourceLocation ExprLoc = E->getExprLoc(); 12780 12781 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12782 BinaryOperator::Opcode Opc = BO->getOpcode(); 12783 Expr::EvalResult Result; 12784 // Do not diagnose unsigned shifts. 12785 if (Opc == BO_Shl) { 12786 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12787 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12788 if (LHS && LHS->getValue() == 0) 12789 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12790 else if (!E->isValueDependent() && LHS && RHS && 12791 RHS->getValue().isNonNegative() && 12792 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12793 S.Diag(ExprLoc, diag::warn_left_shift_always) 12794 << (Result.Val.getInt() != 0); 12795 else if (E->getType()->isSignedIntegerType()) 12796 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12797 } 12798 } 12799 12800 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12801 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12802 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12803 if (!LHS || !RHS) 12804 return; 12805 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12806 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12807 // Do not diagnose common idioms. 12808 return; 12809 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12810 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12811 } 12812 } 12813 12814 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12815 SourceLocation CC, 12816 bool *ICContext = nullptr, 12817 bool IsListInit = false) { 12818 if (E->isTypeDependent() || E->isValueDependent()) return; 12819 12820 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12821 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12822 if (Source == Target) return; 12823 if (Target->isDependentType()) return; 12824 12825 // If the conversion context location is invalid don't complain. We also 12826 // don't want to emit a warning if the issue occurs from the expansion of 12827 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12828 // delay this check as long as possible. Once we detect we are in that 12829 // scenario, we just return. 12830 if (CC.isInvalid()) 12831 return; 12832 12833 if (Source->isAtomicType()) 12834 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12835 12836 // Diagnose implicit casts to bool. 12837 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12838 if (isa<StringLiteral>(E)) 12839 // Warn on string literal to bool. Checks for string literals in logical 12840 // and expressions, for instance, assert(0 && "error here"), are 12841 // prevented by a check in AnalyzeImplicitConversions(). 12842 return DiagnoseImpCast(S, E, T, CC, 12843 diag::warn_impcast_string_literal_to_bool); 12844 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12845 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12846 // This covers the literal expressions that evaluate to Objective-C 12847 // objects. 12848 return DiagnoseImpCast(S, E, T, CC, 12849 diag::warn_impcast_objective_c_literal_to_bool); 12850 } 12851 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12852 // Warn on pointer to bool conversion that is always true. 12853 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12854 SourceRange(CC)); 12855 } 12856 } 12857 12858 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12859 // is a typedef for signed char (macOS), then that constant value has to be 1 12860 // or 0. 12861 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12862 Expr::EvalResult Result; 12863 if (E->EvaluateAsInt(Result, S.getASTContext(), 12864 Expr::SE_AllowSideEffects)) { 12865 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12866 adornObjCBoolConversionDiagWithTernaryFixit( 12867 S, E, 12868 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12869 << toString(Result.Val.getInt(), 10)); 12870 } 12871 return; 12872 } 12873 } 12874 12875 // Check implicit casts from Objective-C collection literals to specialized 12876 // collection types, e.g., NSArray<NSString *> *. 12877 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12878 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12879 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12880 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12881 12882 // Strip vector types. 12883 if (isa<VectorType>(Source)) { 12884 if (Target->isVLSTBuiltinType() && 12885 (S.Context.areCompatibleSveTypes(QualType(Target, 0), 12886 QualType(Source, 0)) || 12887 S.Context.areLaxCompatibleSveTypes(QualType(Target, 0), 12888 QualType(Source, 0)))) 12889 return; 12890 12891 if (!isa<VectorType>(Target)) { 12892 if (S.SourceMgr.isInSystemMacro(CC)) 12893 return; 12894 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12895 } 12896 12897 // If the vector cast is cast between two vectors of the same size, it is 12898 // a bitcast, not a conversion. 12899 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12900 return; 12901 12902 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12903 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12904 } 12905 if (auto VecTy = dyn_cast<VectorType>(Target)) 12906 Target = VecTy->getElementType().getTypePtr(); 12907 12908 // Strip complex types. 12909 if (isa<ComplexType>(Source)) { 12910 if (!isa<ComplexType>(Target)) { 12911 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12912 return; 12913 12914 return DiagnoseImpCast(S, E, T, CC, 12915 S.getLangOpts().CPlusPlus 12916 ? diag::err_impcast_complex_scalar 12917 : diag::warn_impcast_complex_scalar); 12918 } 12919 12920 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12921 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12922 } 12923 12924 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12925 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12926 12927 // If the source is floating point... 12928 if (SourceBT && SourceBT->isFloatingPoint()) { 12929 // ...and the target is floating point... 12930 if (TargetBT && TargetBT->isFloatingPoint()) { 12931 // ...then warn if we're dropping FP rank. 12932 12933 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12934 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12935 if (Order > 0) { 12936 // Don't warn about float constants that are precisely 12937 // representable in the target type. 12938 Expr::EvalResult result; 12939 if (E->EvaluateAsRValue(result, S.Context)) { 12940 // Value might be a float, a float vector, or a float complex. 12941 if (IsSameFloatAfterCast(result.Val, 12942 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12943 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12944 return; 12945 } 12946 12947 if (S.SourceMgr.isInSystemMacro(CC)) 12948 return; 12949 12950 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12951 } 12952 // ... or possibly if we're increasing rank, too 12953 else if (Order < 0) { 12954 if (S.SourceMgr.isInSystemMacro(CC)) 12955 return; 12956 12957 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12958 } 12959 return; 12960 } 12961 12962 // If the target is integral, always warn. 12963 if (TargetBT && TargetBT->isInteger()) { 12964 if (S.SourceMgr.isInSystemMacro(CC)) 12965 return; 12966 12967 DiagnoseFloatingImpCast(S, E, T, CC); 12968 } 12969 12970 // Detect the case where a call result is converted from floating-point to 12971 // to bool, and the final argument to the call is converted from bool, to 12972 // discover this typo: 12973 // 12974 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12975 // 12976 // FIXME: This is an incredibly special case; is there some more general 12977 // way to detect this class of misplaced-parentheses bug? 12978 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12979 // Check last argument of function call to see if it is an 12980 // implicit cast from a type matching the type the result 12981 // is being cast to. 12982 CallExpr *CEx = cast<CallExpr>(E); 12983 if (unsigned NumArgs = CEx->getNumArgs()) { 12984 Expr *LastA = CEx->getArg(NumArgs - 1); 12985 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12986 if (isa<ImplicitCastExpr>(LastA) && 12987 InnerE->getType()->isBooleanType()) { 12988 // Warn on this floating-point to bool conversion 12989 DiagnoseImpCast(S, E, T, CC, 12990 diag::warn_impcast_floating_point_to_bool); 12991 } 12992 } 12993 } 12994 return; 12995 } 12996 12997 // Valid casts involving fixed point types should be accounted for here. 12998 if (Source->isFixedPointType()) { 12999 if (Target->isUnsaturatedFixedPointType()) { 13000 Expr::EvalResult Result; 13001 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 13002 S.isConstantEvaluated())) { 13003 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 13004 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 13005 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 13006 if (Value > MaxVal || Value < MinVal) { 13007 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13008 S.PDiag(diag::warn_impcast_fixed_point_range) 13009 << Value.toString() << T 13010 << E->getSourceRange() 13011 << clang::SourceRange(CC)); 13012 return; 13013 } 13014 } 13015 } else if (Target->isIntegerType()) { 13016 Expr::EvalResult Result; 13017 if (!S.isConstantEvaluated() && 13018 E->EvaluateAsFixedPoint(Result, S.Context, 13019 Expr::SE_AllowSideEffects)) { 13020 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 13021 13022 bool Overflowed; 13023 llvm::APSInt IntResult = FXResult.convertToInt( 13024 S.Context.getIntWidth(T), 13025 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 13026 13027 if (Overflowed) { 13028 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13029 S.PDiag(diag::warn_impcast_fixed_point_range) 13030 << FXResult.toString() << T 13031 << E->getSourceRange() 13032 << clang::SourceRange(CC)); 13033 return; 13034 } 13035 } 13036 } 13037 } else if (Target->isUnsaturatedFixedPointType()) { 13038 if (Source->isIntegerType()) { 13039 Expr::EvalResult Result; 13040 if (!S.isConstantEvaluated() && 13041 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 13042 llvm::APSInt Value = Result.Val.getInt(); 13043 13044 bool Overflowed; 13045 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 13046 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 13047 13048 if (Overflowed) { 13049 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13050 S.PDiag(diag::warn_impcast_fixed_point_range) 13051 << toString(Value, /*Radix=*/10) << T 13052 << E->getSourceRange() 13053 << clang::SourceRange(CC)); 13054 return; 13055 } 13056 } 13057 } 13058 } 13059 13060 // If we are casting an integer type to a floating point type without 13061 // initialization-list syntax, we might lose accuracy if the floating 13062 // point type has a narrower significand than the integer type. 13063 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 13064 TargetBT->isFloatingType() && !IsListInit) { 13065 // Determine the number of precision bits in the source integer type. 13066 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 13067 /*Approximate*/ true); 13068 unsigned int SourcePrecision = SourceRange.Width; 13069 13070 // Determine the number of precision bits in the 13071 // target floating point type. 13072 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 13073 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13074 13075 if (SourcePrecision > 0 && TargetPrecision > 0 && 13076 SourcePrecision > TargetPrecision) { 13077 13078 if (Optional<llvm::APSInt> SourceInt = 13079 E->getIntegerConstantExpr(S.Context)) { 13080 // If the source integer is a constant, convert it to the target 13081 // floating point type. Issue a warning if the value changes 13082 // during the whole conversion. 13083 llvm::APFloat TargetFloatValue( 13084 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13085 llvm::APFloat::opStatus ConversionStatus = 13086 TargetFloatValue.convertFromAPInt( 13087 *SourceInt, SourceBT->isSignedInteger(), 13088 llvm::APFloat::rmNearestTiesToEven); 13089 13090 if (ConversionStatus != llvm::APFloat::opOK) { 13091 SmallString<32> PrettySourceValue; 13092 SourceInt->toString(PrettySourceValue, 10); 13093 SmallString<32> PrettyTargetValue; 13094 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 13095 13096 S.DiagRuntimeBehavior( 13097 E->getExprLoc(), E, 13098 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 13099 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13100 << E->getSourceRange() << clang::SourceRange(CC)); 13101 } 13102 } else { 13103 // Otherwise, the implicit conversion may lose precision. 13104 DiagnoseImpCast(S, E, T, CC, 13105 diag::warn_impcast_integer_float_precision); 13106 } 13107 } 13108 } 13109 13110 DiagnoseNullConversion(S, E, T, CC); 13111 13112 S.DiscardMisalignedMemberAddress(Target, E); 13113 13114 if (Target->isBooleanType()) 13115 DiagnoseIntInBoolContext(S, E); 13116 13117 if (!Source->isIntegerType() || !Target->isIntegerType()) 13118 return; 13119 13120 // TODO: remove this early return once the false positives for constant->bool 13121 // in templates, macros, etc, are reduced or removed. 13122 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 13123 return; 13124 13125 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 13126 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 13127 return adornObjCBoolConversionDiagWithTernaryFixit( 13128 S, E, 13129 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 13130 << E->getType()); 13131 } 13132 13133 IntRange SourceTypeRange = 13134 IntRange::forTargetOfCanonicalType(S.Context, Source); 13135 IntRange LikelySourceRange = 13136 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 13137 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 13138 13139 if (LikelySourceRange.Width > TargetRange.Width) { 13140 // If the source is a constant, use a default-on diagnostic. 13141 // TODO: this should happen for bitfield stores, too. 13142 Expr::EvalResult Result; 13143 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 13144 S.isConstantEvaluated())) { 13145 llvm::APSInt Value(32); 13146 Value = Result.Val.getInt(); 13147 13148 if (S.SourceMgr.isInSystemMacro(CC)) 13149 return; 13150 13151 std::string PrettySourceValue = toString(Value, 10); 13152 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13153 13154 S.DiagRuntimeBehavior( 13155 E->getExprLoc(), E, 13156 S.PDiag(diag::warn_impcast_integer_precision_constant) 13157 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13158 << E->getSourceRange() << SourceRange(CC)); 13159 return; 13160 } 13161 13162 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 13163 if (S.SourceMgr.isInSystemMacro(CC)) 13164 return; 13165 13166 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 13167 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 13168 /* pruneControlFlow */ true); 13169 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 13170 } 13171 13172 if (TargetRange.Width > SourceTypeRange.Width) { 13173 if (auto *UO = dyn_cast<UnaryOperator>(E)) 13174 if (UO->getOpcode() == UO_Minus) 13175 if (Source->isUnsignedIntegerType()) { 13176 if (Target->isUnsignedIntegerType()) 13177 return DiagnoseImpCast(S, E, T, CC, 13178 diag::warn_impcast_high_order_zero_bits); 13179 if (Target->isSignedIntegerType()) 13180 return DiagnoseImpCast(S, E, T, CC, 13181 diag::warn_impcast_nonnegative_result); 13182 } 13183 } 13184 13185 if (TargetRange.Width == LikelySourceRange.Width && 13186 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 13187 Source->isSignedIntegerType()) { 13188 // Warn when doing a signed to signed conversion, warn if the positive 13189 // source value is exactly the width of the target type, which will 13190 // cause a negative value to be stored. 13191 13192 Expr::EvalResult Result; 13193 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 13194 !S.SourceMgr.isInSystemMacro(CC)) { 13195 llvm::APSInt Value = Result.Val.getInt(); 13196 if (isSameWidthConstantConversion(S, E, T, CC)) { 13197 std::string PrettySourceValue = toString(Value, 10); 13198 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13199 13200 S.DiagRuntimeBehavior( 13201 E->getExprLoc(), E, 13202 S.PDiag(diag::warn_impcast_integer_precision_constant) 13203 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13204 << E->getSourceRange() << SourceRange(CC)); 13205 return; 13206 } 13207 } 13208 13209 // Fall through for non-constants to give a sign conversion warning. 13210 } 13211 13212 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 13213 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 13214 LikelySourceRange.Width == TargetRange.Width)) { 13215 if (S.SourceMgr.isInSystemMacro(CC)) 13216 return; 13217 13218 unsigned DiagID = diag::warn_impcast_integer_sign; 13219 13220 // Traditionally, gcc has warned about this under -Wsign-compare. 13221 // We also want to warn about it in -Wconversion. 13222 // So if -Wconversion is off, use a completely identical diagnostic 13223 // in the sign-compare group. 13224 // The conditional-checking code will 13225 if (ICContext) { 13226 DiagID = diag::warn_impcast_integer_sign_conditional; 13227 *ICContext = true; 13228 } 13229 13230 return DiagnoseImpCast(S, E, T, CC, DiagID); 13231 } 13232 13233 // Diagnose conversions between different enumeration types. 13234 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 13235 // type, to give us better diagnostics. 13236 QualType SourceType = E->getType(); 13237 if (!S.getLangOpts().CPlusPlus) { 13238 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13239 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 13240 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 13241 SourceType = S.Context.getTypeDeclType(Enum); 13242 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 13243 } 13244 } 13245 13246 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 13247 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 13248 if (SourceEnum->getDecl()->hasNameForLinkage() && 13249 TargetEnum->getDecl()->hasNameForLinkage() && 13250 SourceEnum != TargetEnum) { 13251 if (S.SourceMgr.isInSystemMacro(CC)) 13252 return; 13253 13254 return DiagnoseImpCast(S, E, SourceType, T, CC, 13255 diag::warn_impcast_different_enum_types); 13256 } 13257 } 13258 13259 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13260 SourceLocation CC, QualType T); 13261 13262 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 13263 SourceLocation CC, bool &ICContext) { 13264 E = E->IgnoreParenImpCasts(); 13265 13266 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 13267 return CheckConditionalOperator(S, CO, CC, T); 13268 13269 AnalyzeImplicitConversions(S, E, CC); 13270 if (E->getType() != T) 13271 return CheckImplicitConversion(S, E, T, CC, &ICContext); 13272 } 13273 13274 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13275 SourceLocation CC, QualType T) { 13276 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 13277 13278 Expr *TrueExpr = E->getTrueExpr(); 13279 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 13280 TrueExpr = BCO->getCommon(); 13281 13282 bool Suspicious = false; 13283 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 13284 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 13285 13286 if (T->isBooleanType()) 13287 DiagnoseIntInBoolContext(S, E); 13288 13289 // If -Wconversion would have warned about either of the candidates 13290 // for a signedness conversion to the context type... 13291 if (!Suspicious) return; 13292 13293 // ...but it's currently ignored... 13294 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 13295 return; 13296 13297 // ...then check whether it would have warned about either of the 13298 // candidates for a signedness conversion to the condition type. 13299 if (E->getType() == T) return; 13300 13301 Suspicious = false; 13302 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 13303 E->getType(), CC, &Suspicious); 13304 if (!Suspicious) 13305 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 13306 E->getType(), CC, &Suspicious); 13307 } 13308 13309 /// Check conversion of given expression to boolean. 13310 /// Input argument E is a logical expression. 13311 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 13312 if (S.getLangOpts().Bool) 13313 return; 13314 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 13315 return; 13316 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 13317 } 13318 13319 namespace { 13320 struct AnalyzeImplicitConversionsWorkItem { 13321 Expr *E; 13322 SourceLocation CC; 13323 bool IsListInit; 13324 }; 13325 } 13326 13327 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 13328 /// that should be visited are added to WorkList. 13329 static void AnalyzeImplicitConversions( 13330 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 13331 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 13332 Expr *OrigE = Item.E; 13333 SourceLocation CC = Item.CC; 13334 13335 QualType T = OrigE->getType(); 13336 Expr *E = OrigE->IgnoreParenImpCasts(); 13337 13338 // Propagate whether we are in a C++ list initialization expression. 13339 // If so, we do not issue warnings for implicit int-float conversion 13340 // precision loss, because C++11 narrowing already handles it. 13341 bool IsListInit = Item.IsListInit || 13342 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 13343 13344 if (E->isTypeDependent() || E->isValueDependent()) 13345 return; 13346 13347 Expr *SourceExpr = E; 13348 // Examine, but don't traverse into the source expression of an 13349 // OpaqueValueExpr, since it may have multiple parents and we don't want to 13350 // emit duplicate diagnostics. Its fine to examine the form or attempt to 13351 // evaluate it in the context of checking the specific conversion to T though. 13352 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 13353 if (auto *Src = OVE->getSourceExpr()) 13354 SourceExpr = Src; 13355 13356 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 13357 if (UO->getOpcode() == UO_Not && 13358 UO->getSubExpr()->isKnownToHaveBooleanValue()) 13359 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 13360 << OrigE->getSourceRange() << T->isBooleanType() 13361 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 13362 13363 if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) 13364 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) && 13365 BO->getLHS()->isKnownToHaveBooleanValue() && 13366 BO->getRHS()->isKnownToHaveBooleanValue() && 13367 BO->getLHS()->HasSideEffects(S.Context) && 13368 BO->getRHS()->HasSideEffects(S.Context)) { 13369 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical) 13370 << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange() 13371 << FixItHint::CreateReplacement( 13372 BO->getOperatorLoc(), 13373 (BO->getOpcode() == BO_And ? "&&" : "||")); 13374 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int); 13375 } 13376 13377 // For conditional operators, we analyze the arguments as if they 13378 // were being fed directly into the output. 13379 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 13380 CheckConditionalOperator(S, CO, CC, T); 13381 return; 13382 } 13383 13384 // Check implicit argument conversions for function calls. 13385 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 13386 CheckImplicitArgumentConversions(S, Call, CC); 13387 13388 // Go ahead and check any implicit conversions we might have skipped. 13389 // The non-canonical typecheck is just an optimization; 13390 // CheckImplicitConversion will filter out dead implicit conversions. 13391 if (SourceExpr->getType() != T) 13392 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 13393 13394 // Now continue drilling into this expression. 13395 13396 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 13397 // The bound subexpressions in a PseudoObjectExpr are not reachable 13398 // as transitive children. 13399 // FIXME: Use a more uniform representation for this. 13400 for (auto *SE : POE->semantics()) 13401 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 13402 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 13403 } 13404 13405 // Skip past explicit casts. 13406 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 13407 E = CE->getSubExpr()->IgnoreParenImpCasts(); 13408 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 13409 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 13410 WorkList.push_back({E, CC, IsListInit}); 13411 return; 13412 } 13413 13414 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13415 // Do a somewhat different check with comparison operators. 13416 if (BO->isComparisonOp()) 13417 return AnalyzeComparison(S, BO); 13418 13419 // And with simple assignments. 13420 if (BO->getOpcode() == BO_Assign) 13421 return AnalyzeAssignment(S, BO); 13422 // And with compound assignments. 13423 if (BO->isAssignmentOp()) 13424 return AnalyzeCompoundAssignment(S, BO); 13425 } 13426 13427 // These break the otherwise-useful invariant below. Fortunately, 13428 // we don't really need to recurse into them, because any internal 13429 // expressions should have been analyzed already when they were 13430 // built into statements. 13431 if (isa<StmtExpr>(E)) return; 13432 13433 // Don't descend into unevaluated contexts. 13434 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 13435 13436 // Now just recurse over the expression's children. 13437 CC = E->getExprLoc(); 13438 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 13439 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 13440 for (Stmt *SubStmt : E->children()) { 13441 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 13442 if (!ChildExpr) 13443 continue; 13444 13445 if (IsLogicalAndOperator && 13446 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 13447 // Ignore checking string literals that are in logical and operators. 13448 // This is a common pattern for asserts. 13449 continue; 13450 WorkList.push_back({ChildExpr, CC, IsListInit}); 13451 } 13452 13453 if (BO && BO->isLogicalOp()) { 13454 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 13455 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13456 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13457 13458 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 13459 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13460 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13461 } 13462 13463 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 13464 if (U->getOpcode() == UO_LNot) { 13465 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 13466 } else if (U->getOpcode() != UO_AddrOf) { 13467 if (U->getSubExpr()->getType()->isAtomicType()) 13468 S.Diag(U->getSubExpr()->getBeginLoc(), 13469 diag::warn_atomic_implicit_seq_cst); 13470 } 13471 } 13472 } 13473 13474 /// AnalyzeImplicitConversions - Find and report any interesting 13475 /// implicit conversions in the given expression. There are a couple 13476 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 13477 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 13478 bool IsListInit/*= false*/) { 13479 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 13480 WorkList.push_back({OrigE, CC, IsListInit}); 13481 while (!WorkList.empty()) 13482 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 13483 } 13484 13485 /// Diagnose integer type and any valid implicit conversion to it. 13486 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 13487 // Taking into account implicit conversions, 13488 // allow any integer. 13489 if (!E->getType()->isIntegerType()) { 13490 S.Diag(E->getBeginLoc(), 13491 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 13492 return true; 13493 } 13494 // Potentially emit standard warnings for implicit conversions if enabled 13495 // using -Wconversion. 13496 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 13497 return false; 13498 } 13499 13500 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 13501 // Returns true when emitting a warning about taking the address of a reference. 13502 static bool CheckForReference(Sema &SemaRef, const Expr *E, 13503 const PartialDiagnostic &PD) { 13504 E = E->IgnoreParenImpCasts(); 13505 13506 const FunctionDecl *FD = nullptr; 13507 13508 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13509 if (!DRE->getDecl()->getType()->isReferenceType()) 13510 return false; 13511 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13512 if (!M->getMemberDecl()->getType()->isReferenceType()) 13513 return false; 13514 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 13515 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 13516 return false; 13517 FD = Call->getDirectCallee(); 13518 } else { 13519 return false; 13520 } 13521 13522 SemaRef.Diag(E->getExprLoc(), PD); 13523 13524 // If possible, point to location of function. 13525 if (FD) { 13526 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 13527 } 13528 13529 return true; 13530 } 13531 13532 // Returns true if the SourceLocation is expanded from any macro body. 13533 // Returns false if the SourceLocation is invalid, is from not in a macro 13534 // expansion, or is from expanded from a top-level macro argument. 13535 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 13536 if (Loc.isInvalid()) 13537 return false; 13538 13539 while (Loc.isMacroID()) { 13540 if (SM.isMacroBodyExpansion(Loc)) 13541 return true; 13542 Loc = SM.getImmediateMacroCallerLoc(Loc); 13543 } 13544 13545 return false; 13546 } 13547 13548 /// Diagnose pointers that are always non-null. 13549 /// \param E the expression containing the pointer 13550 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 13551 /// compared to a null pointer 13552 /// \param IsEqual True when the comparison is equal to a null pointer 13553 /// \param Range Extra SourceRange to highlight in the diagnostic 13554 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 13555 Expr::NullPointerConstantKind NullKind, 13556 bool IsEqual, SourceRange Range) { 13557 if (!E) 13558 return; 13559 13560 // Don't warn inside macros. 13561 if (E->getExprLoc().isMacroID()) { 13562 const SourceManager &SM = getSourceManager(); 13563 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 13564 IsInAnyMacroBody(SM, Range.getBegin())) 13565 return; 13566 } 13567 E = E->IgnoreImpCasts(); 13568 13569 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 13570 13571 if (isa<CXXThisExpr>(E)) { 13572 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13573 : diag::warn_this_bool_conversion; 13574 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13575 return; 13576 } 13577 13578 bool IsAddressOf = false; 13579 13580 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13581 if (UO->getOpcode() != UO_AddrOf) 13582 return; 13583 IsAddressOf = true; 13584 E = UO->getSubExpr(); 13585 } 13586 13587 if (IsAddressOf) { 13588 unsigned DiagID = IsCompare 13589 ? diag::warn_address_of_reference_null_compare 13590 : diag::warn_address_of_reference_bool_conversion; 13591 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13592 << IsEqual; 13593 if (CheckForReference(*this, E, PD)) { 13594 return; 13595 } 13596 } 13597 13598 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13599 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13600 std::string Str; 13601 llvm::raw_string_ostream S(Str); 13602 E->printPretty(S, nullptr, getPrintingPolicy()); 13603 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13604 : diag::warn_cast_nonnull_to_bool; 13605 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13606 << E->getSourceRange() << Range << IsEqual; 13607 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13608 }; 13609 13610 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13611 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13612 if (auto *Callee = Call->getDirectCallee()) { 13613 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13614 ComplainAboutNonnullParamOrCall(A); 13615 return; 13616 } 13617 } 13618 } 13619 13620 // Expect to find a single Decl. Skip anything more complicated. 13621 ValueDecl *D = nullptr; 13622 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13623 D = R->getDecl(); 13624 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13625 D = M->getMemberDecl(); 13626 } 13627 13628 // Weak Decls can be null. 13629 if (!D || D->isWeak()) 13630 return; 13631 13632 // Check for parameter decl with nonnull attribute 13633 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13634 if (getCurFunction() && 13635 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13636 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13637 ComplainAboutNonnullParamOrCall(A); 13638 return; 13639 } 13640 13641 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13642 // Skip function template not specialized yet. 13643 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13644 return; 13645 auto ParamIter = llvm::find(FD->parameters(), PV); 13646 assert(ParamIter != FD->param_end()); 13647 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13648 13649 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13650 if (!NonNull->args_size()) { 13651 ComplainAboutNonnullParamOrCall(NonNull); 13652 return; 13653 } 13654 13655 for (const ParamIdx &ArgNo : NonNull->args()) { 13656 if (ArgNo.getASTIndex() == ParamNo) { 13657 ComplainAboutNonnullParamOrCall(NonNull); 13658 return; 13659 } 13660 } 13661 } 13662 } 13663 } 13664 } 13665 13666 QualType T = D->getType(); 13667 const bool IsArray = T->isArrayType(); 13668 const bool IsFunction = T->isFunctionType(); 13669 13670 // Address of function is used to silence the function warning. 13671 if (IsAddressOf && IsFunction) { 13672 return; 13673 } 13674 13675 // Found nothing. 13676 if (!IsAddressOf && !IsFunction && !IsArray) 13677 return; 13678 13679 // Pretty print the expression for the diagnostic. 13680 std::string Str; 13681 llvm::raw_string_ostream S(Str); 13682 E->printPretty(S, nullptr, getPrintingPolicy()); 13683 13684 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13685 : diag::warn_impcast_pointer_to_bool; 13686 enum { 13687 AddressOf, 13688 FunctionPointer, 13689 ArrayPointer 13690 } DiagType; 13691 if (IsAddressOf) 13692 DiagType = AddressOf; 13693 else if (IsFunction) 13694 DiagType = FunctionPointer; 13695 else if (IsArray) 13696 DiagType = ArrayPointer; 13697 else 13698 llvm_unreachable("Could not determine diagnostic."); 13699 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13700 << Range << IsEqual; 13701 13702 if (!IsFunction) 13703 return; 13704 13705 // Suggest '&' to silence the function warning. 13706 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13707 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13708 13709 // Check to see if '()' fixit should be emitted. 13710 QualType ReturnType; 13711 UnresolvedSet<4> NonTemplateOverloads; 13712 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13713 if (ReturnType.isNull()) 13714 return; 13715 13716 if (IsCompare) { 13717 // There are two cases here. If there is null constant, the only suggest 13718 // for a pointer return type. If the null is 0, then suggest if the return 13719 // type is a pointer or an integer type. 13720 if (!ReturnType->isPointerType()) { 13721 if (NullKind == Expr::NPCK_ZeroExpression || 13722 NullKind == Expr::NPCK_ZeroLiteral) { 13723 if (!ReturnType->isIntegerType()) 13724 return; 13725 } else { 13726 return; 13727 } 13728 } 13729 } else { // !IsCompare 13730 // For function to bool, only suggest if the function pointer has bool 13731 // return type. 13732 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13733 return; 13734 } 13735 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13736 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13737 } 13738 13739 /// Diagnoses "dangerous" implicit conversions within the given 13740 /// expression (which is a full expression). Implements -Wconversion 13741 /// and -Wsign-compare. 13742 /// 13743 /// \param CC the "context" location of the implicit conversion, i.e. 13744 /// the most location of the syntactic entity requiring the implicit 13745 /// conversion 13746 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13747 // Don't diagnose in unevaluated contexts. 13748 if (isUnevaluatedContext()) 13749 return; 13750 13751 // Don't diagnose for value- or type-dependent expressions. 13752 if (E->isTypeDependent() || E->isValueDependent()) 13753 return; 13754 13755 // Check for array bounds violations in cases where the check isn't triggered 13756 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13757 // ArraySubscriptExpr is on the RHS of a variable initialization. 13758 CheckArrayAccess(E); 13759 13760 // This is not the right CC for (e.g.) a variable initialization. 13761 AnalyzeImplicitConversions(*this, E, CC); 13762 } 13763 13764 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13765 /// Input argument E is a logical expression. 13766 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13767 ::CheckBoolLikeConversion(*this, E, CC); 13768 } 13769 13770 /// Diagnose when expression is an integer constant expression and its evaluation 13771 /// results in integer overflow 13772 void Sema::CheckForIntOverflow (Expr *E) { 13773 // Use a work list to deal with nested struct initializers. 13774 SmallVector<Expr *, 2> Exprs(1, E); 13775 13776 do { 13777 Expr *OriginalE = Exprs.pop_back_val(); 13778 Expr *E = OriginalE->IgnoreParenCasts(); 13779 13780 if (isa<BinaryOperator>(E)) { 13781 E->EvaluateForOverflow(Context); 13782 continue; 13783 } 13784 13785 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13786 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13787 else if (isa<ObjCBoxedExpr>(OriginalE)) 13788 E->EvaluateForOverflow(Context); 13789 else if (auto Call = dyn_cast<CallExpr>(E)) 13790 Exprs.append(Call->arg_begin(), Call->arg_end()); 13791 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13792 Exprs.append(Message->arg_begin(), Message->arg_end()); 13793 } while (!Exprs.empty()); 13794 } 13795 13796 namespace { 13797 13798 /// Visitor for expressions which looks for unsequenced operations on the 13799 /// same object. 13800 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13801 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13802 13803 /// A tree of sequenced regions within an expression. Two regions are 13804 /// unsequenced if one is an ancestor or a descendent of the other. When we 13805 /// finish processing an expression with sequencing, such as a comma 13806 /// expression, we fold its tree nodes into its parent, since they are 13807 /// unsequenced with respect to nodes we will visit later. 13808 class SequenceTree { 13809 struct Value { 13810 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13811 unsigned Parent : 31; 13812 unsigned Merged : 1; 13813 }; 13814 SmallVector<Value, 8> Values; 13815 13816 public: 13817 /// A region within an expression which may be sequenced with respect 13818 /// to some other region. 13819 class Seq { 13820 friend class SequenceTree; 13821 13822 unsigned Index; 13823 13824 explicit Seq(unsigned N) : Index(N) {} 13825 13826 public: 13827 Seq() : Index(0) {} 13828 }; 13829 13830 SequenceTree() { Values.push_back(Value(0)); } 13831 Seq root() const { return Seq(0); } 13832 13833 /// Create a new sequence of operations, which is an unsequenced 13834 /// subset of \p Parent. This sequence of operations is sequenced with 13835 /// respect to other children of \p Parent. 13836 Seq allocate(Seq Parent) { 13837 Values.push_back(Value(Parent.Index)); 13838 return Seq(Values.size() - 1); 13839 } 13840 13841 /// Merge a sequence of operations into its parent. 13842 void merge(Seq S) { 13843 Values[S.Index].Merged = true; 13844 } 13845 13846 /// Determine whether two operations are unsequenced. This operation 13847 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13848 /// should have been merged into its parent as appropriate. 13849 bool isUnsequenced(Seq Cur, Seq Old) { 13850 unsigned C = representative(Cur.Index); 13851 unsigned Target = representative(Old.Index); 13852 while (C >= Target) { 13853 if (C == Target) 13854 return true; 13855 C = Values[C].Parent; 13856 } 13857 return false; 13858 } 13859 13860 private: 13861 /// Pick a representative for a sequence. 13862 unsigned representative(unsigned K) { 13863 if (Values[K].Merged) 13864 // Perform path compression as we go. 13865 return Values[K].Parent = representative(Values[K].Parent); 13866 return K; 13867 } 13868 }; 13869 13870 /// An object for which we can track unsequenced uses. 13871 using Object = const NamedDecl *; 13872 13873 /// Different flavors of object usage which we track. We only track the 13874 /// least-sequenced usage of each kind. 13875 enum UsageKind { 13876 /// A read of an object. Multiple unsequenced reads are OK. 13877 UK_Use, 13878 13879 /// A modification of an object which is sequenced before the value 13880 /// computation of the expression, such as ++n in C++. 13881 UK_ModAsValue, 13882 13883 /// A modification of an object which is not sequenced before the value 13884 /// computation of the expression, such as n++. 13885 UK_ModAsSideEffect, 13886 13887 UK_Count = UK_ModAsSideEffect + 1 13888 }; 13889 13890 /// Bundle together a sequencing region and the expression corresponding 13891 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13892 struct Usage { 13893 const Expr *UsageExpr; 13894 SequenceTree::Seq Seq; 13895 13896 Usage() : UsageExpr(nullptr), Seq() {} 13897 }; 13898 13899 struct UsageInfo { 13900 Usage Uses[UK_Count]; 13901 13902 /// Have we issued a diagnostic for this object already? 13903 bool Diagnosed; 13904 13905 UsageInfo() : Uses(), Diagnosed(false) {} 13906 }; 13907 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13908 13909 Sema &SemaRef; 13910 13911 /// Sequenced regions within the expression. 13912 SequenceTree Tree; 13913 13914 /// Declaration modifications and references which we have seen. 13915 UsageInfoMap UsageMap; 13916 13917 /// The region we are currently within. 13918 SequenceTree::Seq Region; 13919 13920 /// Filled in with declarations which were modified as a side-effect 13921 /// (that is, post-increment operations). 13922 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13923 13924 /// Expressions to check later. We defer checking these to reduce 13925 /// stack usage. 13926 SmallVectorImpl<const Expr *> &WorkList; 13927 13928 /// RAII object wrapping the visitation of a sequenced subexpression of an 13929 /// expression. At the end of this process, the side-effects of the evaluation 13930 /// become sequenced with respect to the value computation of the result, so 13931 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13932 /// UK_ModAsValue. 13933 struct SequencedSubexpression { 13934 SequencedSubexpression(SequenceChecker &Self) 13935 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13936 Self.ModAsSideEffect = &ModAsSideEffect; 13937 } 13938 13939 ~SequencedSubexpression() { 13940 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13941 // Add a new usage with usage kind UK_ModAsValue, and then restore 13942 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13943 // the previous one was empty). 13944 UsageInfo &UI = Self.UsageMap[M.first]; 13945 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13946 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13947 SideEffectUsage = M.second; 13948 } 13949 Self.ModAsSideEffect = OldModAsSideEffect; 13950 } 13951 13952 SequenceChecker &Self; 13953 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13954 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13955 }; 13956 13957 /// RAII object wrapping the visitation of a subexpression which we might 13958 /// choose to evaluate as a constant. If any subexpression is evaluated and 13959 /// found to be non-constant, this allows us to suppress the evaluation of 13960 /// the outer expression. 13961 class EvaluationTracker { 13962 public: 13963 EvaluationTracker(SequenceChecker &Self) 13964 : Self(Self), Prev(Self.EvalTracker) { 13965 Self.EvalTracker = this; 13966 } 13967 13968 ~EvaluationTracker() { 13969 Self.EvalTracker = Prev; 13970 if (Prev) 13971 Prev->EvalOK &= EvalOK; 13972 } 13973 13974 bool evaluate(const Expr *E, bool &Result) { 13975 if (!EvalOK || E->isValueDependent()) 13976 return false; 13977 EvalOK = E->EvaluateAsBooleanCondition( 13978 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13979 return EvalOK; 13980 } 13981 13982 private: 13983 SequenceChecker &Self; 13984 EvaluationTracker *Prev; 13985 bool EvalOK = true; 13986 } *EvalTracker = nullptr; 13987 13988 /// Find the object which is produced by the specified expression, 13989 /// if any. 13990 Object getObject(const Expr *E, bool Mod) const { 13991 E = E->IgnoreParenCasts(); 13992 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13993 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13994 return getObject(UO->getSubExpr(), Mod); 13995 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13996 if (BO->getOpcode() == BO_Comma) 13997 return getObject(BO->getRHS(), Mod); 13998 if (Mod && BO->isAssignmentOp()) 13999 return getObject(BO->getLHS(), Mod); 14000 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14001 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 14002 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 14003 return ME->getMemberDecl(); 14004 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 14005 // FIXME: If this is a reference, map through to its value. 14006 return DRE->getDecl(); 14007 return nullptr; 14008 } 14009 14010 /// Note that an object \p O was modified or used by an expression 14011 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 14012 /// the object \p O as obtained via the \p UsageMap. 14013 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 14014 // Get the old usage for the given object and usage kind. 14015 Usage &U = UI.Uses[UK]; 14016 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 14017 // If we have a modification as side effect and are in a sequenced 14018 // subexpression, save the old Usage so that we can restore it later 14019 // in SequencedSubexpression::~SequencedSubexpression. 14020 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 14021 ModAsSideEffect->push_back(std::make_pair(O, U)); 14022 // Then record the new usage with the current sequencing region. 14023 U.UsageExpr = UsageExpr; 14024 U.Seq = Region; 14025 } 14026 } 14027 14028 /// Check whether a modification or use of an object \p O in an expression 14029 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 14030 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 14031 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 14032 /// usage and false we are checking for a mod-use unsequenced usage. 14033 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 14034 UsageKind OtherKind, bool IsModMod) { 14035 if (UI.Diagnosed) 14036 return; 14037 14038 const Usage &U = UI.Uses[OtherKind]; 14039 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 14040 return; 14041 14042 const Expr *Mod = U.UsageExpr; 14043 const Expr *ModOrUse = UsageExpr; 14044 if (OtherKind == UK_Use) 14045 std::swap(Mod, ModOrUse); 14046 14047 SemaRef.DiagRuntimeBehavior( 14048 Mod->getExprLoc(), {Mod, ModOrUse}, 14049 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 14050 : diag::warn_unsequenced_mod_use) 14051 << O << SourceRange(ModOrUse->getExprLoc())); 14052 UI.Diagnosed = true; 14053 } 14054 14055 // A note on note{Pre, Post}{Use, Mod}: 14056 // 14057 // (It helps to follow the algorithm with an expression such as 14058 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 14059 // operations before C++17 and both are well-defined in C++17). 14060 // 14061 // When visiting a node which uses/modify an object we first call notePreUse 14062 // or notePreMod before visiting its sub-expression(s). At this point the 14063 // children of the current node have not yet been visited and so the eventual 14064 // uses/modifications resulting from the children of the current node have not 14065 // been recorded yet. 14066 // 14067 // We then visit the children of the current node. After that notePostUse or 14068 // notePostMod is called. These will 1) detect an unsequenced modification 14069 // as side effect (as in "k++ + k") and 2) add a new usage with the 14070 // appropriate usage kind. 14071 // 14072 // We also have to be careful that some operation sequences modification as 14073 // side effect as well (for example: || or ,). To account for this we wrap 14074 // the visitation of such a sub-expression (for example: the LHS of || or ,) 14075 // with SequencedSubexpression. SequencedSubexpression is an RAII object 14076 // which record usages which are modifications as side effect, and then 14077 // downgrade them (or more accurately restore the previous usage which was a 14078 // modification as side effect) when exiting the scope of the sequenced 14079 // subexpression. 14080 14081 void notePreUse(Object O, const Expr *UseExpr) { 14082 UsageInfo &UI = UsageMap[O]; 14083 // Uses conflict with other modifications. 14084 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 14085 } 14086 14087 void notePostUse(Object O, const Expr *UseExpr) { 14088 UsageInfo &UI = UsageMap[O]; 14089 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 14090 /*IsModMod=*/false); 14091 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 14092 } 14093 14094 void notePreMod(Object O, const Expr *ModExpr) { 14095 UsageInfo &UI = UsageMap[O]; 14096 // Modifications conflict with other modifications and with uses. 14097 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 14098 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 14099 } 14100 14101 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 14102 UsageInfo &UI = UsageMap[O]; 14103 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 14104 /*IsModMod=*/true); 14105 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 14106 } 14107 14108 public: 14109 SequenceChecker(Sema &S, const Expr *E, 14110 SmallVectorImpl<const Expr *> &WorkList) 14111 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 14112 Visit(E); 14113 // Silence a -Wunused-private-field since WorkList is now unused. 14114 // TODO: Evaluate if it can be used, and if not remove it. 14115 (void)this->WorkList; 14116 } 14117 14118 void VisitStmt(const Stmt *S) { 14119 // Skip all statements which aren't expressions for now. 14120 } 14121 14122 void VisitExpr(const Expr *E) { 14123 // By default, just recurse to evaluated subexpressions. 14124 Base::VisitStmt(E); 14125 } 14126 14127 void VisitCastExpr(const CastExpr *E) { 14128 Object O = Object(); 14129 if (E->getCastKind() == CK_LValueToRValue) 14130 O = getObject(E->getSubExpr(), false); 14131 14132 if (O) 14133 notePreUse(O, E); 14134 VisitExpr(E); 14135 if (O) 14136 notePostUse(O, E); 14137 } 14138 14139 void VisitSequencedExpressions(const Expr *SequencedBefore, 14140 const Expr *SequencedAfter) { 14141 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 14142 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 14143 SequenceTree::Seq OldRegion = Region; 14144 14145 { 14146 SequencedSubexpression SeqBefore(*this); 14147 Region = BeforeRegion; 14148 Visit(SequencedBefore); 14149 } 14150 14151 Region = AfterRegion; 14152 Visit(SequencedAfter); 14153 14154 Region = OldRegion; 14155 14156 Tree.merge(BeforeRegion); 14157 Tree.merge(AfterRegion); 14158 } 14159 14160 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 14161 // C++17 [expr.sub]p1: 14162 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 14163 // expression E1 is sequenced before the expression E2. 14164 if (SemaRef.getLangOpts().CPlusPlus17) 14165 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 14166 else { 14167 Visit(ASE->getLHS()); 14168 Visit(ASE->getRHS()); 14169 } 14170 } 14171 14172 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14173 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14174 void VisitBinPtrMem(const BinaryOperator *BO) { 14175 // C++17 [expr.mptr.oper]p4: 14176 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 14177 // the expression E1 is sequenced before the expression E2. 14178 if (SemaRef.getLangOpts().CPlusPlus17) 14179 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14180 else { 14181 Visit(BO->getLHS()); 14182 Visit(BO->getRHS()); 14183 } 14184 } 14185 14186 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14187 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14188 void VisitBinShlShr(const BinaryOperator *BO) { 14189 // C++17 [expr.shift]p4: 14190 // The expression E1 is sequenced before the expression E2. 14191 if (SemaRef.getLangOpts().CPlusPlus17) 14192 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14193 else { 14194 Visit(BO->getLHS()); 14195 Visit(BO->getRHS()); 14196 } 14197 } 14198 14199 void VisitBinComma(const BinaryOperator *BO) { 14200 // C++11 [expr.comma]p1: 14201 // Every value computation and side effect associated with the left 14202 // expression is sequenced before every value computation and side 14203 // effect associated with the right expression. 14204 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14205 } 14206 14207 void VisitBinAssign(const BinaryOperator *BO) { 14208 SequenceTree::Seq RHSRegion; 14209 SequenceTree::Seq LHSRegion; 14210 if (SemaRef.getLangOpts().CPlusPlus17) { 14211 RHSRegion = Tree.allocate(Region); 14212 LHSRegion = Tree.allocate(Region); 14213 } else { 14214 RHSRegion = Region; 14215 LHSRegion = Region; 14216 } 14217 SequenceTree::Seq OldRegion = Region; 14218 14219 // C++11 [expr.ass]p1: 14220 // [...] the assignment is sequenced after the value computation 14221 // of the right and left operands, [...] 14222 // 14223 // so check it before inspecting the operands and update the 14224 // map afterwards. 14225 Object O = getObject(BO->getLHS(), /*Mod=*/true); 14226 if (O) 14227 notePreMod(O, BO); 14228 14229 if (SemaRef.getLangOpts().CPlusPlus17) { 14230 // C++17 [expr.ass]p1: 14231 // [...] The right operand is sequenced before the left operand. [...] 14232 { 14233 SequencedSubexpression SeqBefore(*this); 14234 Region = RHSRegion; 14235 Visit(BO->getRHS()); 14236 } 14237 14238 Region = LHSRegion; 14239 Visit(BO->getLHS()); 14240 14241 if (O && isa<CompoundAssignOperator>(BO)) 14242 notePostUse(O, BO); 14243 14244 } else { 14245 // C++11 does not specify any sequencing between the LHS and RHS. 14246 Region = LHSRegion; 14247 Visit(BO->getLHS()); 14248 14249 if (O && isa<CompoundAssignOperator>(BO)) 14250 notePostUse(O, BO); 14251 14252 Region = RHSRegion; 14253 Visit(BO->getRHS()); 14254 } 14255 14256 // C++11 [expr.ass]p1: 14257 // the assignment is sequenced [...] before the value computation of the 14258 // assignment expression. 14259 // C11 6.5.16/3 has no such rule. 14260 Region = OldRegion; 14261 if (O) 14262 notePostMod(O, BO, 14263 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14264 : UK_ModAsSideEffect); 14265 if (SemaRef.getLangOpts().CPlusPlus17) { 14266 Tree.merge(RHSRegion); 14267 Tree.merge(LHSRegion); 14268 } 14269 } 14270 14271 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 14272 VisitBinAssign(CAO); 14273 } 14274 14275 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14276 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14277 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 14278 Object O = getObject(UO->getSubExpr(), true); 14279 if (!O) 14280 return VisitExpr(UO); 14281 14282 notePreMod(O, UO); 14283 Visit(UO->getSubExpr()); 14284 // C++11 [expr.pre.incr]p1: 14285 // the expression ++x is equivalent to x+=1 14286 notePostMod(O, UO, 14287 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14288 : UK_ModAsSideEffect); 14289 } 14290 14291 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14292 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14293 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 14294 Object O = getObject(UO->getSubExpr(), true); 14295 if (!O) 14296 return VisitExpr(UO); 14297 14298 notePreMod(O, UO); 14299 Visit(UO->getSubExpr()); 14300 notePostMod(O, UO, UK_ModAsSideEffect); 14301 } 14302 14303 void VisitBinLOr(const BinaryOperator *BO) { 14304 // C++11 [expr.log.or]p2: 14305 // If the second expression is evaluated, every value computation and 14306 // side effect associated with the first expression is sequenced before 14307 // every value computation and side effect associated with the 14308 // second expression. 14309 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14310 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14311 SequenceTree::Seq OldRegion = Region; 14312 14313 EvaluationTracker Eval(*this); 14314 { 14315 SequencedSubexpression Sequenced(*this); 14316 Region = LHSRegion; 14317 Visit(BO->getLHS()); 14318 } 14319 14320 // C++11 [expr.log.or]p1: 14321 // [...] the second operand is not evaluated if the first operand 14322 // evaluates to true. 14323 bool EvalResult = false; 14324 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14325 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 14326 if (ShouldVisitRHS) { 14327 Region = RHSRegion; 14328 Visit(BO->getRHS()); 14329 } 14330 14331 Region = OldRegion; 14332 Tree.merge(LHSRegion); 14333 Tree.merge(RHSRegion); 14334 } 14335 14336 void VisitBinLAnd(const BinaryOperator *BO) { 14337 // C++11 [expr.log.and]p2: 14338 // If the second expression is evaluated, every value computation and 14339 // side effect associated with the first expression is sequenced before 14340 // every value computation and side effect associated with the 14341 // second expression. 14342 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14343 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14344 SequenceTree::Seq OldRegion = Region; 14345 14346 EvaluationTracker Eval(*this); 14347 { 14348 SequencedSubexpression Sequenced(*this); 14349 Region = LHSRegion; 14350 Visit(BO->getLHS()); 14351 } 14352 14353 // C++11 [expr.log.and]p1: 14354 // [...] the second operand is not evaluated if the first operand is false. 14355 bool EvalResult = false; 14356 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14357 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 14358 if (ShouldVisitRHS) { 14359 Region = RHSRegion; 14360 Visit(BO->getRHS()); 14361 } 14362 14363 Region = OldRegion; 14364 Tree.merge(LHSRegion); 14365 Tree.merge(RHSRegion); 14366 } 14367 14368 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 14369 // C++11 [expr.cond]p1: 14370 // [...] Every value computation and side effect associated with the first 14371 // expression is sequenced before every value computation and side effect 14372 // associated with the second or third expression. 14373 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 14374 14375 // No sequencing is specified between the true and false expression. 14376 // However since exactly one of both is going to be evaluated we can 14377 // consider them to be sequenced. This is needed to avoid warning on 14378 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 14379 // both the true and false expressions because we can't evaluate x. 14380 // This will still allow us to detect an expression like (pre C++17) 14381 // "(x ? y += 1 : y += 2) = y". 14382 // 14383 // We don't wrap the visitation of the true and false expression with 14384 // SequencedSubexpression because we don't want to downgrade modifications 14385 // as side effect in the true and false expressions after the visition 14386 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 14387 // not warn between the two "y++", but we should warn between the "y++" 14388 // and the "y". 14389 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 14390 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 14391 SequenceTree::Seq OldRegion = Region; 14392 14393 EvaluationTracker Eval(*this); 14394 { 14395 SequencedSubexpression Sequenced(*this); 14396 Region = ConditionRegion; 14397 Visit(CO->getCond()); 14398 } 14399 14400 // C++11 [expr.cond]p1: 14401 // [...] The first expression is contextually converted to bool (Clause 4). 14402 // It is evaluated and if it is true, the result of the conditional 14403 // expression is the value of the second expression, otherwise that of the 14404 // third expression. Only one of the second and third expressions is 14405 // evaluated. [...] 14406 bool EvalResult = false; 14407 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 14408 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 14409 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 14410 if (ShouldVisitTrueExpr) { 14411 Region = TrueRegion; 14412 Visit(CO->getTrueExpr()); 14413 } 14414 if (ShouldVisitFalseExpr) { 14415 Region = FalseRegion; 14416 Visit(CO->getFalseExpr()); 14417 } 14418 14419 Region = OldRegion; 14420 Tree.merge(ConditionRegion); 14421 Tree.merge(TrueRegion); 14422 Tree.merge(FalseRegion); 14423 } 14424 14425 void VisitCallExpr(const CallExpr *CE) { 14426 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 14427 14428 if (CE->isUnevaluatedBuiltinCall(Context)) 14429 return; 14430 14431 // C++11 [intro.execution]p15: 14432 // When calling a function [...], every value computation and side effect 14433 // associated with any argument expression, or with the postfix expression 14434 // designating the called function, is sequenced before execution of every 14435 // expression or statement in the body of the function [and thus before 14436 // the value computation of its result]. 14437 SequencedSubexpression Sequenced(*this); 14438 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 14439 // C++17 [expr.call]p5 14440 // The postfix-expression is sequenced before each expression in the 14441 // expression-list and any default argument. [...] 14442 SequenceTree::Seq CalleeRegion; 14443 SequenceTree::Seq OtherRegion; 14444 if (SemaRef.getLangOpts().CPlusPlus17) { 14445 CalleeRegion = Tree.allocate(Region); 14446 OtherRegion = Tree.allocate(Region); 14447 } else { 14448 CalleeRegion = Region; 14449 OtherRegion = Region; 14450 } 14451 SequenceTree::Seq OldRegion = Region; 14452 14453 // Visit the callee expression first. 14454 Region = CalleeRegion; 14455 if (SemaRef.getLangOpts().CPlusPlus17) { 14456 SequencedSubexpression Sequenced(*this); 14457 Visit(CE->getCallee()); 14458 } else { 14459 Visit(CE->getCallee()); 14460 } 14461 14462 // Then visit the argument expressions. 14463 Region = OtherRegion; 14464 for (const Expr *Argument : CE->arguments()) 14465 Visit(Argument); 14466 14467 Region = OldRegion; 14468 if (SemaRef.getLangOpts().CPlusPlus17) { 14469 Tree.merge(CalleeRegion); 14470 Tree.merge(OtherRegion); 14471 } 14472 }); 14473 } 14474 14475 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 14476 // C++17 [over.match.oper]p2: 14477 // [...] the operator notation is first transformed to the equivalent 14478 // function-call notation as summarized in Table 12 (where @ denotes one 14479 // of the operators covered in the specified subclause). However, the 14480 // operands are sequenced in the order prescribed for the built-in 14481 // operator (Clause 8). 14482 // 14483 // From the above only overloaded binary operators and overloaded call 14484 // operators have sequencing rules in C++17 that we need to handle 14485 // separately. 14486 if (!SemaRef.getLangOpts().CPlusPlus17 || 14487 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 14488 return VisitCallExpr(CXXOCE); 14489 14490 enum { 14491 NoSequencing, 14492 LHSBeforeRHS, 14493 RHSBeforeLHS, 14494 LHSBeforeRest 14495 } SequencingKind; 14496 switch (CXXOCE->getOperator()) { 14497 case OO_Equal: 14498 case OO_PlusEqual: 14499 case OO_MinusEqual: 14500 case OO_StarEqual: 14501 case OO_SlashEqual: 14502 case OO_PercentEqual: 14503 case OO_CaretEqual: 14504 case OO_AmpEqual: 14505 case OO_PipeEqual: 14506 case OO_LessLessEqual: 14507 case OO_GreaterGreaterEqual: 14508 SequencingKind = RHSBeforeLHS; 14509 break; 14510 14511 case OO_LessLess: 14512 case OO_GreaterGreater: 14513 case OO_AmpAmp: 14514 case OO_PipePipe: 14515 case OO_Comma: 14516 case OO_ArrowStar: 14517 case OO_Subscript: 14518 SequencingKind = LHSBeforeRHS; 14519 break; 14520 14521 case OO_Call: 14522 SequencingKind = LHSBeforeRest; 14523 break; 14524 14525 default: 14526 SequencingKind = NoSequencing; 14527 break; 14528 } 14529 14530 if (SequencingKind == NoSequencing) 14531 return VisitCallExpr(CXXOCE); 14532 14533 // This is a call, so all subexpressions are sequenced before the result. 14534 SequencedSubexpression Sequenced(*this); 14535 14536 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 14537 assert(SemaRef.getLangOpts().CPlusPlus17 && 14538 "Should only get there with C++17 and above!"); 14539 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 14540 "Should only get there with an overloaded binary operator" 14541 " or an overloaded call operator!"); 14542 14543 if (SequencingKind == LHSBeforeRest) { 14544 assert(CXXOCE->getOperator() == OO_Call && 14545 "We should only have an overloaded call operator here!"); 14546 14547 // This is very similar to VisitCallExpr, except that we only have the 14548 // C++17 case. The postfix-expression is the first argument of the 14549 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 14550 // are in the following arguments. 14551 // 14552 // Note that we intentionally do not visit the callee expression since 14553 // it is just a decayed reference to a function. 14554 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 14555 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 14556 SequenceTree::Seq OldRegion = Region; 14557 14558 assert(CXXOCE->getNumArgs() >= 1 && 14559 "An overloaded call operator must have at least one argument" 14560 " for the postfix-expression!"); 14561 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 14562 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 14563 CXXOCE->getNumArgs() - 1); 14564 14565 // Visit the postfix-expression first. 14566 { 14567 Region = PostfixExprRegion; 14568 SequencedSubexpression Sequenced(*this); 14569 Visit(PostfixExpr); 14570 } 14571 14572 // Then visit the argument expressions. 14573 Region = ArgsRegion; 14574 for (const Expr *Arg : Args) 14575 Visit(Arg); 14576 14577 Region = OldRegion; 14578 Tree.merge(PostfixExprRegion); 14579 Tree.merge(ArgsRegion); 14580 } else { 14581 assert(CXXOCE->getNumArgs() == 2 && 14582 "Should only have two arguments here!"); 14583 assert((SequencingKind == LHSBeforeRHS || 14584 SequencingKind == RHSBeforeLHS) && 14585 "Unexpected sequencing kind!"); 14586 14587 // We do not visit the callee expression since it is just a decayed 14588 // reference to a function. 14589 const Expr *E1 = CXXOCE->getArg(0); 14590 const Expr *E2 = CXXOCE->getArg(1); 14591 if (SequencingKind == RHSBeforeLHS) 14592 std::swap(E1, E2); 14593 14594 return VisitSequencedExpressions(E1, E2); 14595 } 14596 }); 14597 } 14598 14599 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14600 // This is a call, so all subexpressions are sequenced before the result. 14601 SequencedSubexpression Sequenced(*this); 14602 14603 if (!CCE->isListInitialization()) 14604 return VisitExpr(CCE); 14605 14606 // In C++11, list initializations are sequenced. 14607 SmallVector<SequenceTree::Seq, 32> Elts; 14608 SequenceTree::Seq Parent = Region; 14609 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14610 E = CCE->arg_end(); 14611 I != E; ++I) { 14612 Region = Tree.allocate(Parent); 14613 Elts.push_back(Region); 14614 Visit(*I); 14615 } 14616 14617 // Forget that the initializers are sequenced. 14618 Region = Parent; 14619 for (unsigned I = 0; I < Elts.size(); ++I) 14620 Tree.merge(Elts[I]); 14621 } 14622 14623 void VisitInitListExpr(const InitListExpr *ILE) { 14624 if (!SemaRef.getLangOpts().CPlusPlus11) 14625 return VisitExpr(ILE); 14626 14627 // In C++11, list initializations are sequenced. 14628 SmallVector<SequenceTree::Seq, 32> Elts; 14629 SequenceTree::Seq Parent = Region; 14630 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14631 const Expr *E = ILE->getInit(I); 14632 if (!E) 14633 continue; 14634 Region = Tree.allocate(Parent); 14635 Elts.push_back(Region); 14636 Visit(E); 14637 } 14638 14639 // Forget that the initializers are sequenced. 14640 Region = Parent; 14641 for (unsigned I = 0; I < Elts.size(); ++I) 14642 Tree.merge(Elts[I]); 14643 } 14644 }; 14645 14646 } // namespace 14647 14648 void Sema::CheckUnsequencedOperations(const Expr *E) { 14649 SmallVector<const Expr *, 8> WorkList; 14650 WorkList.push_back(E); 14651 while (!WorkList.empty()) { 14652 const Expr *Item = WorkList.pop_back_val(); 14653 SequenceChecker(*this, Item, WorkList); 14654 } 14655 } 14656 14657 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14658 bool IsConstexpr) { 14659 llvm::SaveAndRestore<bool> ConstantContext( 14660 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14661 CheckImplicitConversions(E, CheckLoc); 14662 if (!E->isInstantiationDependent()) 14663 CheckUnsequencedOperations(E); 14664 if (!IsConstexpr && !E->isValueDependent()) 14665 CheckForIntOverflow(E); 14666 DiagnoseMisalignedMembers(); 14667 } 14668 14669 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14670 FieldDecl *BitField, 14671 Expr *Init) { 14672 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14673 } 14674 14675 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14676 SourceLocation Loc) { 14677 if (!PType->isVariablyModifiedType()) 14678 return; 14679 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14680 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14681 return; 14682 } 14683 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14684 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14685 return; 14686 } 14687 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14688 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14689 return; 14690 } 14691 14692 const ArrayType *AT = S.Context.getAsArrayType(PType); 14693 if (!AT) 14694 return; 14695 14696 if (AT->getSizeModifier() != ArrayType::Star) { 14697 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14698 return; 14699 } 14700 14701 S.Diag(Loc, diag::err_array_star_in_function_definition); 14702 } 14703 14704 /// CheckParmsForFunctionDef - Check that the parameters of the given 14705 /// function are appropriate for the definition of a function. This 14706 /// takes care of any checks that cannot be performed on the 14707 /// declaration itself, e.g., that the types of each of the function 14708 /// parameters are complete. 14709 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14710 bool CheckParameterNames) { 14711 bool HasInvalidParm = false; 14712 for (ParmVarDecl *Param : Parameters) { 14713 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14714 // function declarator that is part of a function definition of 14715 // that function shall not have incomplete type. 14716 // 14717 // This is also C++ [dcl.fct]p6. 14718 if (!Param->isInvalidDecl() && 14719 RequireCompleteType(Param->getLocation(), Param->getType(), 14720 diag::err_typecheck_decl_incomplete_type)) { 14721 Param->setInvalidDecl(); 14722 HasInvalidParm = true; 14723 } 14724 14725 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14726 // declaration of each parameter shall include an identifier. 14727 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14728 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14729 // Diagnose this as an extension in C17 and earlier. 14730 if (!getLangOpts().C2x) 14731 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14732 } 14733 14734 // C99 6.7.5.3p12: 14735 // If the function declarator is not part of a definition of that 14736 // function, parameters may have incomplete type and may use the [*] 14737 // notation in their sequences of declarator specifiers to specify 14738 // variable length array types. 14739 QualType PType = Param->getOriginalType(); 14740 // FIXME: This diagnostic should point the '[*]' if source-location 14741 // information is added for it. 14742 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14743 14744 // If the parameter is a c++ class type and it has to be destructed in the 14745 // callee function, declare the destructor so that it can be called by the 14746 // callee function. Do not perform any direct access check on the dtor here. 14747 if (!Param->isInvalidDecl()) { 14748 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14749 if (!ClassDecl->isInvalidDecl() && 14750 !ClassDecl->hasIrrelevantDestructor() && 14751 !ClassDecl->isDependentContext() && 14752 ClassDecl->isParamDestroyedInCallee()) { 14753 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14754 MarkFunctionReferenced(Param->getLocation(), Destructor); 14755 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14756 } 14757 } 14758 } 14759 14760 // Parameters with the pass_object_size attribute only need to be marked 14761 // constant at function definitions. Because we lack information about 14762 // whether we're on a declaration or definition when we're instantiating the 14763 // attribute, we need to check for constness here. 14764 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14765 if (!Param->getType().isConstQualified()) 14766 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14767 << Attr->getSpelling() << 1; 14768 14769 // Check for parameter names shadowing fields from the class. 14770 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14771 // The owning context for the parameter should be the function, but we 14772 // want to see if this function's declaration context is a record. 14773 DeclContext *DC = Param->getDeclContext(); 14774 if (DC && DC->isFunctionOrMethod()) { 14775 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14776 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14777 RD, /*DeclIsField*/ false); 14778 } 14779 } 14780 } 14781 14782 return HasInvalidParm; 14783 } 14784 14785 Optional<std::pair<CharUnits, CharUnits>> 14786 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14787 14788 /// Compute the alignment and offset of the base class object given the 14789 /// derived-to-base cast expression and the alignment and offset of the derived 14790 /// class object. 14791 static std::pair<CharUnits, CharUnits> 14792 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14793 CharUnits BaseAlignment, CharUnits Offset, 14794 ASTContext &Ctx) { 14795 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14796 ++PathI) { 14797 const CXXBaseSpecifier *Base = *PathI; 14798 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14799 if (Base->isVirtual()) { 14800 // The complete object may have a lower alignment than the non-virtual 14801 // alignment of the base, in which case the base may be misaligned. Choose 14802 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14803 // conservative lower bound of the complete object alignment. 14804 CharUnits NonVirtualAlignment = 14805 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14806 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14807 Offset = CharUnits::Zero(); 14808 } else { 14809 const ASTRecordLayout &RL = 14810 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14811 Offset += RL.getBaseClassOffset(BaseDecl); 14812 } 14813 DerivedType = Base->getType(); 14814 } 14815 14816 return std::make_pair(BaseAlignment, Offset); 14817 } 14818 14819 /// Compute the alignment and offset of a binary additive operator. 14820 static Optional<std::pair<CharUnits, CharUnits>> 14821 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14822 bool IsSub, ASTContext &Ctx) { 14823 QualType PointeeType = PtrE->getType()->getPointeeType(); 14824 14825 if (!PointeeType->isConstantSizeType()) 14826 return llvm::None; 14827 14828 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14829 14830 if (!P) 14831 return llvm::None; 14832 14833 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14834 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14835 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14836 if (IsSub) 14837 Offset = -Offset; 14838 return std::make_pair(P->first, P->second + Offset); 14839 } 14840 14841 // If the integer expression isn't a constant expression, compute the lower 14842 // bound of the alignment using the alignment and offset of the pointer 14843 // expression and the element size. 14844 return std::make_pair( 14845 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14846 CharUnits::Zero()); 14847 } 14848 14849 /// This helper function takes an lvalue expression and returns the alignment of 14850 /// a VarDecl and a constant offset from the VarDecl. 14851 Optional<std::pair<CharUnits, CharUnits>> 14852 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14853 E = E->IgnoreParens(); 14854 switch (E->getStmtClass()) { 14855 default: 14856 break; 14857 case Stmt::CStyleCastExprClass: 14858 case Stmt::CXXStaticCastExprClass: 14859 case Stmt::ImplicitCastExprClass: { 14860 auto *CE = cast<CastExpr>(E); 14861 const Expr *From = CE->getSubExpr(); 14862 switch (CE->getCastKind()) { 14863 default: 14864 break; 14865 case CK_NoOp: 14866 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14867 case CK_UncheckedDerivedToBase: 14868 case CK_DerivedToBase: { 14869 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14870 if (!P) 14871 break; 14872 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14873 P->second, Ctx); 14874 } 14875 } 14876 break; 14877 } 14878 case Stmt::ArraySubscriptExprClass: { 14879 auto *ASE = cast<ArraySubscriptExpr>(E); 14880 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14881 false, Ctx); 14882 } 14883 case Stmt::DeclRefExprClass: { 14884 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14885 // FIXME: If VD is captured by copy or is an escaping __block variable, 14886 // use the alignment of VD's type. 14887 if (!VD->getType()->isReferenceType()) 14888 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14889 if (VD->hasInit()) 14890 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14891 } 14892 break; 14893 } 14894 case Stmt::MemberExprClass: { 14895 auto *ME = cast<MemberExpr>(E); 14896 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14897 if (!FD || FD->getType()->isReferenceType() || 14898 FD->getParent()->isInvalidDecl()) 14899 break; 14900 Optional<std::pair<CharUnits, CharUnits>> P; 14901 if (ME->isArrow()) 14902 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14903 else 14904 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14905 if (!P) 14906 break; 14907 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14908 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14909 return std::make_pair(P->first, 14910 P->second + CharUnits::fromQuantity(Offset)); 14911 } 14912 case Stmt::UnaryOperatorClass: { 14913 auto *UO = cast<UnaryOperator>(E); 14914 switch (UO->getOpcode()) { 14915 default: 14916 break; 14917 case UO_Deref: 14918 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14919 } 14920 break; 14921 } 14922 case Stmt::BinaryOperatorClass: { 14923 auto *BO = cast<BinaryOperator>(E); 14924 auto Opcode = BO->getOpcode(); 14925 switch (Opcode) { 14926 default: 14927 break; 14928 case BO_Comma: 14929 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14930 } 14931 break; 14932 } 14933 } 14934 return llvm::None; 14935 } 14936 14937 /// This helper function takes a pointer expression and returns the alignment of 14938 /// a VarDecl and a constant offset from the VarDecl. 14939 Optional<std::pair<CharUnits, CharUnits>> 14940 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14941 E = E->IgnoreParens(); 14942 switch (E->getStmtClass()) { 14943 default: 14944 break; 14945 case Stmt::CStyleCastExprClass: 14946 case Stmt::CXXStaticCastExprClass: 14947 case Stmt::ImplicitCastExprClass: { 14948 auto *CE = cast<CastExpr>(E); 14949 const Expr *From = CE->getSubExpr(); 14950 switch (CE->getCastKind()) { 14951 default: 14952 break; 14953 case CK_NoOp: 14954 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14955 case CK_ArrayToPointerDecay: 14956 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14957 case CK_UncheckedDerivedToBase: 14958 case CK_DerivedToBase: { 14959 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14960 if (!P) 14961 break; 14962 return getDerivedToBaseAlignmentAndOffset( 14963 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14964 } 14965 } 14966 break; 14967 } 14968 case Stmt::CXXThisExprClass: { 14969 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14970 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14971 return std::make_pair(Alignment, CharUnits::Zero()); 14972 } 14973 case Stmt::UnaryOperatorClass: { 14974 auto *UO = cast<UnaryOperator>(E); 14975 if (UO->getOpcode() == UO_AddrOf) 14976 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14977 break; 14978 } 14979 case Stmt::BinaryOperatorClass: { 14980 auto *BO = cast<BinaryOperator>(E); 14981 auto Opcode = BO->getOpcode(); 14982 switch (Opcode) { 14983 default: 14984 break; 14985 case BO_Add: 14986 case BO_Sub: { 14987 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14988 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14989 std::swap(LHS, RHS); 14990 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14991 Ctx); 14992 } 14993 case BO_Comma: 14994 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14995 } 14996 break; 14997 } 14998 } 14999 return llvm::None; 15000 } 15001 15002 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 15003 // See if we can compute the alignment of a VarDecl and an offset from it. 15004 Optional<std::pair<CharUnits, CharUnits>> P = 15005 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 15006 15007 if (P) 15008 return P->first.alignmentAtOffset(P->second); 15009 15010 // If that failed, return the type's alignment. 15011 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 15012 } 15013 15014 /// CheckCastAlign - Implements -Wcast-align, which warns when a 15015 /// pointer cast increases the alignment requirements. 15016 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 15017 // This is actually a lot of work to potentially be doing on every 15018 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 15019 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 15020 return; 15021 15022 // Ignore dependent types. 15023 if (T->isDependentType() || Op->getType()->isDependentType()) 15024 return; 15025 15026 // Require that the destination be a pointer type. 15027 const PointerType *DestPtr = T->getAs<PointerType>(); 15028 if (!DestPtr) return; 15029 15030 // If the destination has alignment 1, we're done. 15031 QualType DestPointee = DestPtr->getPointeeType(); 15032 if (DestPointee->isIncompleteType()) return; 15033 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 15034 if (DestAlign.isOne()) return; 15035 15036 // Require that the source be a pointer type. 15037 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 15038 if (!SrcPtr) return; 15039 QualType SrcPointee = SrcPtr->getPointeeType(); 15040 15041 // Explicitly allow casts from cv void*. We already implicitly 15042 // allowed casts to cv void*, since they have alignment 1. 15043 // Also allow casts involving incomplete types, which implicitly 15044 // includes 'void'. 15045 if (SrcPointee->isIncompleteType()) return; 15046 15047 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 15048 15049 if (SrcAlign >= DestAlign) return; 15050 15051 Diag(TRange.getBegin(), diag::warn_cast_align) 15052 << Op->getType() << T 15053 << static_cast<unsigned>(SrcAlign.getQuantity()) 15054 << static_cast<unsigned>(DestAlign.getQuantity()) 15055 << TRange << Op->getSourceRange(); 15056 } 15057 15058 /// Check whether this array fits the idiom of a size-one tail padded 15059 /// array member of a struct. 15060 /// 15061 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 15062 /// commonly used to emulate flexible arrays in C89 code. 15063 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 15064 const NamedDecl *ND) { 15065 if (Size != 1 || !ND) return false; 15066 15067 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 15068 if (!FD) return false; 15069 15070 // Don't consider sizes resulting from macro expansions or template argument 15071 // substitution to form C89 tail-padded arrays. 15072 15073 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 15074 while (TInfo) { 15075 TypeLoc TL = TInfo->getTypeLoc(); 15076 // Look through typedefs. 15077 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 15078 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 15079 TInfo = TDL->getTypeSourceInfo(); 15080 continue; 15081 } 15082 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 15083 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 15084 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 15085 return false; 15086 } 15087 break; 15088 } 15089 15090 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 15091 if (!RD) return false; 15092 if (RD->isUnion()) return false; 15093 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15094 if (!CRD->isStandardLayout()) return false; 15095 } 15096 15097 // See if this is the last field decl in the record. 15098 const Decl *D = FD; 15099 while ((D = D->getNextDeclInContext())) 15100 if (isa<FieldDecl>(D)) 15101 return false; 15102 return true; 15103 } 15104 15105 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 15106 const ArraySubscriptExpr *ASE, 15107 bool AllowOnePastEnd, bool IndexNegated) { 15108 // Already diagnosed by the constant evaluator. 15109 if (isConstantEvaluated()) 15110 return; 15111 15112 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 15113 if (IndexExpr->isValueDependent()) 15114 return; 15115 15116 const Type *EffectiveType = 15117 BaseExpr->getType()->getPointeeOrArrayElementType(); 15118 BaseExpr = BaseExpr->IgnoreParenCasts(); 15119 const ConstantArrayType *ArrayTy = 15120 Context.getAsConstantArrayType(BaseExpr->getType()); 15121 15122 const Type *BaseType = 15123 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 15124 bool IsUnboundedArray = (BaseType == nullptr); 15125 if (EffectiveType->isDependentType() || 15126 (!IsUnboundedArray && BaseType->isDependentType())) 15127 return; 15128 15129 Expr::EvalResult Result; 15130 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 15131 return; 15132 15133 llvm::APSInt index = Result.Val.getInt(); 15134 if (IndexNegated) { 15135 index.setIsUnsigned(false); 15136 index = -index; 15137 } 15138 15139 const NamedDecl *ND = nullptr; 15140 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15141 ND = DRE->getDecl(); 15142 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 15143 ND = ME->getMemberDecl(); 15144 15145 if (IsUnboundedArray) { 15146 if (index.isUnsigned() || !index.isNegative()) { 15147 const auto &ASTC = getASTContext(); 15148 unsigned AddrBits = 15149 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 15150 EffectiveType->getCanonicalTypeInternal())); 15151 if (index.getBitWidth() < AddrBits) 15152 index = index.zext(AddrBits); 15153 Optional<CharUnits> ElemCharUnits = 15154 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 15155 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 15156 // pointer) bounds-checking isn't meaningful. 15157 if (!ElemCharUnits) 15158 return; 15159 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 15160 // If index has more active bits than address space, we already know 15161 // we have a bounds violation to warn about. Otherwise, compute 15162 // address of (index + 1)th element, and warn about bounds violation 15163 // only if that address exceeds address space. 15164 if (index.getActiveBits() <= AddrBits) { 15165 bool Overflow; 15166 llvm::APInt Product(index); 15167 Product += 1; 15168 Product = Product.umul_ov(ElemBytes, Overflow); 15169 if (!Overflow && Product.getActiveBits() <= AddrBits) 15170 return; 15171 } 15172 15173 // Need to compute max possible elements in address space, since that 15174 // is included in diag message. 15175 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 15176 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 15177 MaxElems += 1; 15178 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 15179 MaxElems = MaxElems.udiv(ElemBytes); 15180 15181 unsigned DiagID = 15182 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 15183 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 15184 15185 // Diag message shows element size in bits and in "bytes" (platform- 15186 // dependent CharUnits) 15187 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15188 PDiag(DiagID) 15189 << toString(index, 10, true) << AddrBits 15190 << (unsigned)ASTC.toBits(*ElemCharUnits) 15191 << toString(ElemBytes, 10, false) 15192 << toString(MaxElems, 10, false) 15193 << (unsigned)MaxElems.getLimitedValue(~0U) 15194 << IndexExpr->getSourceRange()); 15195 15196 if (!ND) { 15197 // Try harder to find a NamedDecl to point at in the note. 15198 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15199 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15200 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15201 ND = DRE->getDecl(); 15202 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15203 ND = ME->getMemberDecl(); 15204 } 15205 15206 if (ND) 15207 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15208 PDiag(diag::note_array_declared_here) << ND); 15209 } 15210 return; 15211 } 15212 15213 if (index.isUnsigned() || !index.isNegative()) { 15214 // It is possible that the type of the base expression after 15215 // IgnoreParenCasts is incomplete, even though the type of the base 15216 // expression before IgnoreParenCasts is complete (see PR39746 for an 15217 // example). In this case we have no information about whether the array 15218 // access exceeds the array bounds. However we can still diagnose an array 15219 // access which precedes the array bounds. 15220 if (BaseType->isIncompleteType()) 15221 return; 15222 15223 llvm::APInt size = ArrayTy->getSize(); 15224 if (!size.isStrictlyPositive()) 15225 return; 15226 15227 if (BaseType != EffectiveType) { 15228 // Make sure we're comparing apples to apples when comparing index to size 15229 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 15230 uint64_t array_typesize = Context.getTypeSize(BaseType); 15231 // Handle ptrarith_typesize being zero, such as when casting to void* 15232 if (!ptrarith_typesize) ptrarith_typesize = 1; 15233 if (ptrarith_typesize != array_typesize) { 15234 // There's a cast to a different size type involved 15235 uint64_t ratio = array_typesize / ptrarith_typesize; 15236 // TODO: Be smarter about handling cases where array_typesize is not a 15237 // multiple of ptrarith_typesize 15238 if (ptrarith_typesize * ratio == array_typesize) 15239 size *= llvm::APInt(size.getBitWidth(), ratio); 15240 } 15241 } 15242 15243 if (size.getBitWidth() > index.getBitWidth()) 15244 index = index.zext(size.getBitWidth()); 15245 else if (size.getBitWidth() < index.getBitWidth()) 15246 size = size.zext(index.getBitWidth()); 15247 15248 // For array subscripting the index must be less than size, but for pointer 15249 // arithmetic also allow the index (offset) to be equal to size since 15250 // computing the next address after the end of the array is legal and 15251 // commonly done e.g. in C++ iterators and range-based for loops. 15252 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 15253 return; 15254 15255 // Also don't warn for arrays of size 1 which are members of some 15256 // structure. These are often used to approximate flexible arrays in C89 15257 // code. 15258 if (IsTailPaddedMemberArray(*this, size, ND)) 15259 return; 15260 15261 // Suppress the warning if the subscript expression (as identified by the 15262 // ']' location) and the index expression are both from macro expansions 15263 // within a system header. 15264 if (ASE) { 15265 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 15266 ASE->getRBracketLoc()); 15267 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 15268 SourceLocation IndexLoc = 15269 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 15270 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 15271 return; 15272 } 15273 } 15274 15275 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 15276 : diag::warn_ptr_arith_exceeds_bounds; 15277 15278 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15279 PDiag(DiagID) << toString(index, 10, true) 15280 << toString(size, 10, true) 15281 << (unsigned)size.getLimitedValue(~0U) 15282 << IndexExpr->getSourceRange()); 15283 } else { 15284 unsigned DiagID = diag::warn_array_index_precedes_bounds; 15285 if (!ASE) { 15286 DiagID = diag::warn_ptr_arith_precedes_bounds; 15287 if (index.isNegative()) index = -index; 15288 } 15289 15290 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15291 PDiag(DiagID) << toString(index, 10, true) 15292 << IndexExpr->getSourceRange()); 15293 } 15294 15295 if (!ND) { 15296 // Try harder to find a NamedDecl to point at in the note. 15297 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15298 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15299 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15300 ND = DRE->getDecl(); 15301 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15302 ND = ME->getMemberDecl(); 15303 } 15304 15305 if (ND) 15306 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15307 PDiag(diag::note_array_declared_here) << ND); 15308 } 15309 15310 void Sema::CheckArrayAccess(const Expr *expr) { 15311 int AllowOnePastEnd = 0; 15312 while (expr) { 15313 expr = expr->IgnoreParenImpCasts(); 15314 switch (expr->getStmtClass()) { 15315 case Stmt::ArraySubscriptExprClass: { 15316 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 15317 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 15318 AllowOnePastEnd > 0); 15319 expr = ASE->getBase(); 15320 break; 15321 } 15322 case Stmt::MemberExprClass: { 15323 expr = cast<MemberExpr>(expr)->getBase(); 15324 break; 15325 } 15326 case Stmt::OMPArraySectionExprClass: { 15327 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 15328 if (ASE->getLowerBound()) 15329 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 15330 /*ASE=*/nullptr, AllowOnePastEnd > 0); 15331 return; 15332 } 15333 case Stmt::UnaryOperatorClass: { 15334 // Only unwrap the * and & unary operators 15335 const UnaryOperator *UO = cast<UnaryOperator>(expr); 15336 expr = UO->getSubExpr(); 15337 switch (UO->getOpcode()) { 15338 case UO_AddrOf: 15339 AllowOnePastEnd++; 15340 break; 15341 case UO_Deref: 15342 AllowOnePastEnd--; 15343 break; 15344 default: 15345 return; 15346 } 15347 break; 15348 } 15349 case Stmt::ConditionalOperatorClass: { 15350 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 15351 if (const Expr *lhs = cond->getLHS()) 15352 CheckArrayAccess(lhs); 15353 if (const Expr *rhs = cond->getRHS()) 15354 CheckArrayAccess(rhs); 15355 return; 15356 } 15357 case Stmt::CXXOperatorCallExprClass: { 15358 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 15359 for (const auto *Arg : OCE->arguments()) 15360 CheckArrayAccess(Arg); 15361 return; 15362 } 15363 default: 15364 return; 15365 } 15366 } 15367 } 15368 15369 //===--- CHECK: Objective-C retain cycles ----------------------------------// 15370 15371 namespace { 15372 15373 struct RetainCycleOwner { 15374 VarDecl *Variable = nullptr; 15375 SourceRange Range; 15376 SourceLocation Loc; 15377 bool Indirect = false; 15378 15379 RetainCycleOwner() = default; 15380 15381 void setLocsFrom(Expr *e) { 15382 Loc = e->getExprLoc(); 15383 Range = e->getSourceRange(); 15384 } 15385 }; 15386 15387 } // namespace 15388 15389 /// Consider whether capturing the given variable can possibly lead to 15390 /// a retain cycle. 15391 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 15392 // In ARC, it's captured strongly iff the variable has __strong 15393 // lifetime. In MRR, it's captured strongly if the variable is 15394 // __block and has an appropriate type. 15395 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15396 return false; 15397 15398 owner.Variable = var; 15399 if (ref) 15400 owner.setLocsFrom(ref); 15401 return true; 15402 } 15403 15404 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 15405 while (true) { 15406 e = e->IgnoreParens(); 15407 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 15408 switch (cast->getCastKind()) { 15409 case CK_BitCast: 15410 case CK_LValueBitCast: 15411 case CK_LValueToRValue: 15412 case CK_ARCReclaimReturnedObject: 15413 e = cast->getSubExpr(); 15414 continue; 15415 15416 default: 15417 return false; 15418 } 15419 } 15420 15421 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 15422 ObjCIvarDecl *ivar = ref->getDecl(); 15423 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15424 return false; 15425 15426 // Try to find a retain cycle in the base. 15427 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 15428 return false; 15429 15430 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 15431 owner.Indirect = true; 15432 return true; 15433 } 15434 15435 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 15436 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 15437 if (!var) return false; 15438 return considerVariable(var, ref, owner); 15439 } 15440 15441 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 15442 if (member->isArrow()) return false; 15443 15444 // Don't count this as an indirect ownership. 15445 e = member->getBase(); 15446 continue; 15447 } 15448 15449 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 15450 // Only pay attention to pseudo-objects on property references. 15451 ObjCPropertyRefExpr *pre 15452 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 15453 ->IgnoreParens()); 15454 if (!pre) return false; 15455 if (pre->isImplicitProperty()) return false; 15456 ObjCPropertyDecl *property = pre->getExplicitProperty(); 15457 if (!property->isRetaining() && 15458 !(property->getPropertyIvarDecl() && 15459 property->getPropertyIvarDecl()->getType() 15460 .getObjCLifetime() == Qualifiers::OCL_Strong)) 15461 return false; 15462 15463 owner.Indirect = true; 15464 if (pre->isSuperReceiver()) { 15465 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 15466 if (!owner.Variable) 15467 return false; 15468 owner.Loc = pre->getLocation(); 15469 owner.Range = pre->getSourceRange(); 15470 return true; 15471 } 15472 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 15473 ->getSourceExpr()); 15474 continue; 15475 } 15476 15477 // Array ivars? 15478 15479 return false; 15480 } 15481 } 15482 15483 namespace { 15484 15485 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 15486 ASTContext &Context; 15487 VarDecl *Variable; 15488 Expr *Capturer = nullptr; 15489 bool VarWillBeReased = false; 15490 15491 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 15492 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 15493 Context(Context), Variable(variable) {} 15494 15495 void VisitDeclRefExpr(DeclRefExpr *ref) { 15496 if (ref->getDecl() == Variable && !Capturer) 15497 Capturer = ref; 15498 } 15499 15500 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 15501 if (Capturer) return; 15502 Visit(ref->getBase()); 15503 if (Capturer && ref->isFreeIvar()) 15504 Capturer = ref; 15505 } 15506 15507 void VisitBlockExpr(BlockExpr *block) { 15508 // Look inside nested blocks 15509 if (block->getBlockDecl()->capturesVariable(Variable)) 15510 Visit(block->getBlockDecl()->getBody()); 15511 } 15512 15513 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 15514 if (Capturer) return; 15515 if (OVE->getSourceExpr()) 15516 Visit(OVE->getSourceExpr()); 15517 } 15518 15519 void VisitBinaryOperator(BinaryOperator *BinOp) { 15520 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 15521 return; 15522 Expr *LHS = BinOp->getLHS(); 15523 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 15524 if (DRE->getDecl() != Variable) 15525 return; 15526 if (Expr *RHS = BinOp->getRHS()) { 15527 RHS = RHS->IgnoreParenCasts(); 15528 Optional<llvm::APSInt> Value; 15529 VarWillBeReased = 15530 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 15531 *Value == 0); 15532 } 15533 } 15534 } 15535 }; 15536 15537 } // namespace 15538 15539 /// Check whether the given argument is a block which captures a 15540 /// variable. 15541 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 15542 assert(owner.Variable && owner.Loc.isValid()); 15543 15544 e = e->IgnoreParenCasts(); 15545 15546 // Look through [^{...} copy] and Block_copy(^{...}). 15547 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 15548 Selector Cmd = ME->getSelector(); 15549 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 15550 e = ME->getInstanceReceiver(); 15551 if (!e) 15552 return nullptr; 15553 e = e->IgnoreParenCasts(); 15554 } 15555 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 15556 if (CE->getNumArgs() == 1) { 15557 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 15558 if (Fn) { 15559 const IdentifierInfo *FnI = Fn->getIdentifier(); 15560 if (FnI && FnI->isStr("_Block_copy")) { 15561 e = CE->getArg(0)->IgnoreParenCasts(); 15562 } 15563 } 15564 } 15565 } 15566 15567 BlockExpr *block = dyn_cast<BlockExpr>(e); 15568 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 15569 return nullptr; 15570 15571 FindCaptureVisitor visitor(S.Context, owner.Variable); 15572 visitor.Visit(block->getBlockDecl()->getBody()); 15573 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15574 } 15575 15576 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15577 RetainCycleOwner &owner) { 15578 assert(capturer); 15579 assert(owner.Variable && owner.Loc.isValid()); 15580 15581 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15582 << owner.Variable << capturer->getSourceRange(); 15583 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15584 << owner.Indirect << owner.Range; 15585 } 15586 15587 /// Check for a keyword selector that starts with the word 'add' or 15588 /// 'set'. 15589 static bool isSetterLikeSelector(Selector sel) { 15590 if (sel.isUnarySelector()) return false; 15591 15592 StringRef str = sel.getNameForSlot(0); 15593 while (!str.empty() && str.front() == '_') str = str.substr(1); 15594 if (str.startswith("set")) 15595 str = str.substr(3); 15596 else if (str.startswith("add")) { 15597 // Specially allow 'addOperationWithBlock:'. 15598 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15599 return false; 15600 str = str.substr(3); 15601 } 15602 else 15603 return false; 15604 15605 if (str.empty()) return true; 15606 return !isLowercase(str.front()); 15607 } 15608 15609 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15610 ObjCMessageExpr *Message) { 15611 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15612 Message->getReceiverInterface(), 15613 NSAPI::ClassId_NSMutableArray); 15614 if (!IsMutableArray) { 15615 return None; 15616 } 15617 15618 Selector Sel = Message->getSelector(); 15619 15620 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15621 S.NSAPIObj->getNSArrayMethodKind(Sel); 15622 if (!MKOpt) { 15623 return None; 15624 } 15625 15626 NSAPI::NSArrayMethodKind MK = *MKOpt; 15627 15628 switch (MK) { 15629 case NSAPI::NSMutableArr_addObject: 15630 case NSAPI::NSMutableArr_insertObjectAtIndex: 15631 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15632 return 0; 15633 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15634 return 1; 15635 15636 default: 15637 return None; 15638 } 15639 15640 return None; 15641 } 15642 15643 static 15644 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15645 ObjCMessageExpr *Message) { 15646 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15647 Message->getReceiverInterface(), 15648 NSAPI::ClassId_NSMutableDictionary); 15649 if (!IsMutableDictionary) { 15650 return None; 15651 } 15652 15653 Selector Sel = Message->getSelector(); 15654 15655 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 15656 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 15657 if (!MKOpt) { 15658 return None; 15659 } 15660 15661 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 15662 15663 switch (MK) { 15664 case NSAPI::NSMutableDict_setObjectForKey: 15665 case NSAPI::NSMutableDict_setValueForKey: 15666 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 15667 return 0; 15668 15669 default: 15670 return None; 15671 } 15672 15673 return None; 15674 } 15675 15676 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 15677 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 15678 Message->getReceiverInterface(), 15679 NSAPI::ClassId_NSMutableSet); 15680 15681 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 15682 Message->getReceiverInterface(), 15683 NSAPI::ClassId_NSMutableOrderedSet); 15684 if (!IsMutableSet && !IsMutableOrderedSet) { 15685 return None; 15686 } 15687 15688 Selector Sel = Message->getSelector(); 15689 15690 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15691 if (!MKOpt) { 15692 return None; 15693 } 15694 15695 NSAPI::NSSetMethodKind MK = *MKOpt; 15696 15697 switch (MK) { 15698 case NSAPI::NSMutableSet_addObject: 15699 case NSAPI::NSOrderedSet_setObjectAtIndex: 15700 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15701 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15702 return 0; 15703 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 15704 return 1; 15705 } 15706 15707 return None; 15708 } 15709 15710 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 15711 if (!Message->isInstanceMessage()) { 15712 return; 15713 } 15714 15715 Optional<int> ArgOpt; 15716 15717 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 15718 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 15719 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 15720 return; 15721 } 15722 15723 int ArgIndex = *ArgOpt; 15724 15725 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 15726 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 15727 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 15728 } 15729 15730 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 15731 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15732 if (ArgRE->isObjCSelfExpr()) { 15733 Diag(Message->getSourceRange().getBegin(), 15734 diag::warn_objc_circular_container) 15735 << ArgRE->getDecl() << StringRef("'super'"); 15736 } 15737 } 15738 } else { 15739 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 15740 15741 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 15742 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 15743 } 15744 15745 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 15746 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15747 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 15748 ValueDecl *Decl = ReceiverRE->getDecl(); 15749 Diag(Message->getSourceRange().getBegin(), 15750 diag::warn_objc_circular_container) 15751 << Decl << Decl; 15752 if (!ArgRE->isObjCSelfExpr()) { 15753 Diag(Decl->getLocation(), 15754 diag::note_objc_circular_container_declared_here) 15755 << Decl; 15756 } 15757 } 15758 } 15759 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15760 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15761 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15762 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15763 Diag(Message->getSourceRange().getBegin(), 15764 diag::warn_objc_circular_container) 15765 << Decl << Decl; 15766 Diag(Decl->getLocation(), 15767 diag::note_objc_circular_container_declared_here) 15768 << Decl; 15769 } 15770 } 15771 } 15772 } 15773 } 15774 15775 /// Check a message send to see if it's likely to cause a retain cycle. 15776 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15777 // Only check instance methods whose selector looks like a setter. 15778 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15779 return; 15780 15781 // Try to find a variable that the receiver is strongly owned by. 15782 RetainCycleOwner owner; 15783 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15784 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15785 return; 15786 } else { 15787 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15788 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15789 owner.Loc = msg->getSuperLoc(); 15790 owner.Range = msg->getSuperLoc(); 15791 } 15792 15793 // Check whether the receiver is captured by any of the arguments. 15794 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15795 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15796 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15797 // noescape blocks should not be retained by the method. 15798 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15799 continue; 15800 return diagnoseRetainCycle(*this, capturer, owner); 15801 } 15802 } 15803 } 15804 15805 /// Check a property assign to see if it's likely to cause a retain cycle. 15806 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15807 RetainCycleOwner owner; 15808 if (!findRetainCycleOwner(*this, receiver, owner)) 15809 return; 15810 15811 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15812 diagnoseRetainCycle(*this, capturer, owner); 15813 } 15814 15815 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15816 RetainCycleOwner Owner; 15817 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15818 return; 15819 15820 // Because we don't have an expression for the variable, we have to set the 15821 // location explicitly here. 15822 Owner.Loc = Var->getLocation(); 15823 Owner.Range = Var->getSourceRange(); 15824 15825 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15826 diagnoseRetainCycle(*this, Capturer, Owner); 15827 } 15828 15829 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15830 Expr *RHS, bool isProperty) { 15831 // Check if RHS is an Objective-C object literal, which also can get 15832 // immediately zapped in a weak reference. Note that we explicitly 15833 // allow ObjCStringLiterals, since those are designed to never really die. 15834 RHS = RHS->IgnoreParenImpCasts(); 15835 15836 // This enum needs to match with the 'select' in 15837 // warn_objc_arc_literal_assign (off-by-1). 15838 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15839 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15840 return false; 15841 15842 S.Diag(Loc, diag::warn_arc_literal_assign) 15843 << (unsigned) Kind 15844 << (isProperty ? 0 : 1) 15845 << RHS->getSourceRange(); 15846 15847 return true; 15848 } 15849 15850 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15851 Qualifiers::ObjCLifetime LT, 15852 Expr *RHS, bool isProperty) { 15853 // Strip off any implicit cast added to get to the one ARC-specific. 15854 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15855 if (cast->getCastKind() == CK_ARCConsumeObject) { 15856 S.Diag(Loc, diag::warn_arc_retained_assign) 15857 << (LT == Qualifiers::OCL_ExplicitNone) 15858 << (isProperty ? 0 : 1) 15859 << RHS->getSourceRange(); 15860 return true; 15861 } 15862 RHS = cast->getSubExpr(); 15863 } 15864 15865 if (LT == Qualifiers::OCL_Weak && 15866 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15867 return true; 15868 15869 return false; 15870 } 15871 15872 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15873 QualType LHS, Expr *RHS) { 15874 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15875 15876 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15877 return false; 15878 15879 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15880 return true; 15881 15882 return false; 15883 } 15884 15885 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15886 Expr *LHS, Expr *RHS) { 15887 QualType LHSType; 15888 // PropertyRef on LHS type need be directly obtained from 15889 // its declaration as it has a PseudoType. 15890 ObjCPropertyRefExpr *PRE 15891 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15892 if (PRE && !PRE->isImplicitProperty()) { 15893 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15894 if (PD) 15895 LHSType = PD->getType(); 15896 } 15897 15898 if (LHSType.isNull()) 15899 LHSType = LHS->getType(); 15900 15901 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15902 15903 if (LT == Qualifiers::OCL_Weak) { 15904 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15905 getCurFunction()->markSafeWeakUse(LHS); 15906 } 15907 15908 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15909 return; 15910 15911 // FIXME. Check for other life times. 15912 if (LT != Qualifiers::OCL_None) 15913 return; 15914 15915 if (PRE) { 15916 if (PRE->isImplicitProperty()) 15917 return; 15918 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15919 if (!PD) 15920 return; 15921 15922 unsigned Attributes = PD->getPropertyAttributes(); 15923 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15924 // when 'assign' attribute was not explicitly specified 15925 // by user, ignore it and rely on property type itself 15926 // for lifetime info. 15927 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15928 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15929 LHSType->isObjCRetainableType()) 15930 return; 15931 15932 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15933 if (cast->getCastKind() == CK_ARCConsumeObject) { 15934 Diag(Loc, diag::warn_arc_retained_property_assign) 15935 << RHS->getSourceRange(); 15936 return; 15937 } 15938 RHS = cast->getSubExpr(); 15939 } 15940 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15941 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15942 return; 15943 } 15944 } 15945 } 15946 15947 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15948 15949 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15950 SourceLocation StmtLoc, 15951 const NullStmt *Body) { 15952 // Do not warn if the body is a macro that expands to nothing, e.g: 15953 // 15954 // #define CALL(x) 15955 // if (condition) 15956 // CALL(0); 15957 if (Body->hasLeadingEmptyMacro()) 15958 return false; 15959 15960 // Get line numbers of statement and body. 15961 bool StmtLineInvalid; 15962 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15963 &StmtLineInvalid); 15964 if (StmtLineInvalid) 15965 return false; 15966 15967 bool BodyLineInvalid; 15968 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15969 &BodyLineInvalid); 15970 if (BodyLineInvalid) 15971 return false; 15972 15973 // Warn if null statement and body are on the same line. 15974 if (StmtLine != BodyLine) 15975 return false; 15976 15977 return true; 15978 } 15979 15980 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15981 const Stmt *Body, 15982 unsigned DiagID) { 15983 // Since this is a syntactic check, don't emit diagnostic for template 15984 // instantiations, this just adds noise. 15985 if (CurrentInstantiationScope) 15986 return; 15987 15988 // The body should be a null statement. 15989 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15990 if (!NBody) 15991 return; 15992 15993 // Do the usual checks. 15994 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15995 return; 15996 15997 Diag(NBody->getSemiLoc(), DiagID); 15998 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15999 } 16000 16001 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 16002 const Stmt *PossibleBody) { 16003 assert(!CurrentInstantiationScope); // Ensured by caller 16004 16005 SourceLocation StmtLoc; 16006 const Stmt *Body; 16007 unsigned DiagID; 16008 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 16009 StmtLoc = FS->getRParenLoc(); 16010 Body = FS->getBody(); 16011 DiagID = diag::warn_empty_for_body; 16012 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 16013 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 16014 Body = WS->getBody(); 16015 DiagID = diag::warn_empty_while_body; 16016 } else 16017 return; // Neither `for' nor `while'. 16018 16019 // The body should be a null statement. 16020 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 16021 if (!NBody) 16022 return; 16023 16024 // Skip expensive checks if diagnostic is disabled. 16025 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 16026 return; 16027 16028 // Do the usual checks. 16029 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 16030 return; 16031 16032 // `for(...);' and `while(...);' are popular idioms, so in order to keep 16033 // noise level low, emit diagnostics only if for/while is followed by a 16034 // CompoundStmt, e.g.: 16035 // for (int i = 0; i < n; i++); 16036 // { 16037 // a(i); 16038 // } 16039 // or if for/while is followed by a statement with more indentation 16040 // than for/while itself: 16041 // for (int i = 0; i < n; i++); 16042 // a(i); 16043 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 16044 if (!ProbableTypo) { 16045 bool BodyColInvalid; 16046 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 16047 PossibleBody->getBeginLoc(), &BodyColInvalid); 16048 if (BodyColInvalid) 16049 return; 16050 16051 bool StmtColInvalid; 16052 unsigned StmtCol = 16053 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 16054 if (StmtColInvalid) 16055 return; 16056 16057 if (BodyCol > StmtCol) 16058 ProbableTypo = true; 16059 } 16060 16061 if (ProbableTypo) { 16062 Diag(NBody->getSemiLoc(), DiagID); 16063 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 16064 } 16065 } 16066 16067 //===--- CHECK: Warn on self move with std::move. -------------------------===// 16068 16069 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 16070 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 16071 SourceLocation OpLoc) { 16072 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 16073 return; 16074 16075 if (inTemplateInstantiation()) 16076 return; 16077 16078 // Strip parens and casts away. 16079 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 16080 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 16081 16082 // Check for a call expression 16083 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 16084 if (!CE || CE->getNumArgs() != 1) 16085 return; 16086 16087 // Check for a call to std::move 16088 if (!CE->isCallToStdMove()) 16089 return; 16090 16091 // Get argument from std::move 16092 RHSExpr = CE->getArg(0); 16093 16094 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 16095 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 16096 16097 // Two DeclRefExpr's, check that the decls are the same. 16098 if (LHSDeclRef && RHSDeclRef) { 16099 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16100 return; 16101 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16102 RHSDeclRef->getDecl()->getCanonicalDecl()) 16103 return; 16104 16105 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16106 << LHSExpr->getSourceRange() 16107 << RHSExpr->getSourceRange(); 16108 return; 16109 } 16110 16111 // Member variables require a different approach to check for self moves. 16112 // MemberExpr's are the same if every nested MemberExpr refers to the same 16113 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 16114 // the base Expr's are CXXThisExpr's. 16115 const Expr *LHSBase = LHSExpr; 16116 const Expr *RHSBase = RHSExpr; 16117 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 16118 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 16119 if (!LHSME || !RHSME) 16120 return; 16121 16122 while (LHSME && RHSME) { 16123 if (LHSME->getMemberDecl()->getCanonicalDecl() != 16124 RHSME->getMemberDecl()->getCanonicalDecl()) 16125 return; 16126 16127 LHSBase = LHSME->getBase(); 16128 RHSBase = RHSME->getBase(); 16129 LHSME = dyn_cast<MemberExpr>(LHSBase); 16130 RHSME = dyn_cast<MemberExpr>(RHSBase); 16131 } 16132 16133 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 16134 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 16135 if (LHSDeclRef && RHSDeclRef) { 16136 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16137 return; 16138 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16139 RHSDeclRef->getDecl()->getCanonicalDecl()) 16140 return; 16141 16142 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16143 << LHSExpr->getSourceRange() 16144 << RHSExpr->getSourceRange(); 16145 return; 16146 } 16147 16148 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 16149 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16150 << LHSExpr->getSourceRange() 16151 << RHSExpr->getSourceRange(); 16152 } 16153 16154 //===--- Layout compatibility ----------------------------------------------// 16155 16156 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 16157 16158 /// Check if two enumeration types are layout-compatible. 16159 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 16160 // C++11 [dcl.enum] p8: 16161 // Two enumeration types are layout-compatible if they have the same 16162 // underlying type. 16163 return ED1->isComplete() && ED2->isComplete() && 16164 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 16165 } 16166 16167 /// Check if two fields are layout-compatible. 16168 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 16169 FieldDecl *Field2) { 16170 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 16171 return false; 16172 16173 if (Field1->isBitField() != Field2->isBitField()) 16174 return false; 16175 16176 if (Field1->isBitField()) { 16177 // Make sure that the bit-fields are the same length. 16178 unsigned Bits1 = Field1->getBitWidthValue(C); 16179 unsigned Bits2 = Field2->getBitWidthValue(C); 16180 16181 if (Bits1 != Bits2) 16182 return false; 16183 } 16184 16185 return true; 16186 } 16187 16188 /// Check if two standard-layout structs are layout-compatible. 16189 /// (C++11 [class.mem] p17) 16190 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 16191 RecordDecl *RD2) { 16192 // If both records are C++ classes, check that base classes match. 16193 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 16194 // If one of records is a CXXRecordDecl we are in C++ mode, 16195 // thus the other one is a CXXRecordDecl, too. 16196 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 16197 // Check number of base classes. 16198 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 16199 return false; 16200 16201 // Check the base classes. 16202 for (CXXRecordDecl::base_class_const_iterator 16203 Base1 = D1CXX->bases_begin(), 16204 BaseEnd1 = D1CXX->bases_end(), 16205 Base2 = D2CXX->bases_begin(); 16206 Base1 != BaseEnd1; 16207 ++Base1, ++Base2) { 16208 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 16209 return false; 16210 } 16211 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 16212 // If only RD2 is a C++ class, it should have zero base classes. 16213 if (D2CXX->getNumBases() > 0) 16214 return false; 16215 } 16216 16217 // Check the fields. 16218 RecordDecl::field_iterator Field2 = RD2->field_begin(), 16219 Field2End = RD2->field_end(), 16220 Field1 = RD1->field_begin(), 16221 Field1End = RD1->field_end(); 16222 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 16223 if (!isLayoutCompatible(C, *Field1, *Field2)) 16224 return false; 16225 } 16226 if (Field1 != Field1End || Field2 != Field2End) 16227 return false; 16228 16229 return true; 16230 } 16231 16232 /// Check if two standard-layout unions are layout-compatible. 16233 /// (C++11 [class.mem] p18) 16234 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 16235 RecordDecl *RD2) { 16236 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 16237 for (auto *Field2 : RD2->fields()) 16238 UnmatchedFields.insert(Field2); 16239 16240 for (auto *Field1 : RD1->fields()) { 16241 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 16242 I = UnmatchedFields.begin(), 16243 E = UnmatchedFields.end(); 16244 16245 for ( ; I != E; ++I) { 16246 if (isLayoutCompatible(C, Field1, *I)) { 16247 bool Result = UnmatchedFields.erase(*I); 16248 (void) Result; 16249 assert(Result); 16250 break; 16251 } 16252 } 16253 if (I == E) 16254 return false; 16255 } 16256 16257 return UnmatchedFields.empty(); 16258 } 16259 16260 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 16261 RecordDecl *RD2) { 16262 if (RD1->isUnion() != RD2->isUnion()) 16263 return false; 16264 16265 if (RD1->isUnion()) 16266 return isLayoutCompatibleUnion(C, RD1, RD2); 16267 else 16268 return isLayoutCompatibleStruct(C, RD1, RD2); 16269 } 16270 16271 /// Check if two types are layout-compatible in C++11 sense. 16272 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 16273 if (T1.isNull() || T2.isNull()) 16274 return false; 16275 16276 // C++11 [basic.types] p11: 16277 // If two types T1 and T2 are the same type, then T1 and T2 are 16278 // layout-compatible types. 16279 if (C.hasSameType(T1, T2)) 16280 return true; 16281 16282 T1 = T1.getCanonicalType().getUnqualifiedType(); 16283 T2 = T2.getCanonicalType().getUnqualifiedType(); 16284 16285 const Type::TypeClass TC1 = T1->getTypeClass(); 16286 const Type::TypeClass TC2 = T2->getTypeClass(); 16287 16288 if (TC1 != TC2) 16289 return false; 16290 16291 if (TC1 == Type::Enum) { 16292 return isLayoutCompatible(C, 16293 cast<EnumType>(T1)->getDecl(), 16294 cast<EnumType>(T2)->getDecl()); 16295 } else if (TC1 == Type::Record) { 16296 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 16297 return false; 16298 16299 return isLayoutCompatible(C, 16300 cast<RecordType>(T1)->getDecl(), 16301 cast<RecordType>(T2)->getDecl()); 16302 } 16303 16304 return false; 16305 } 16306 16307 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 16308 16309 /// Given a type tag expression find the type tag itself. 16310 /// 16311 /// \param TypeExpr Type tag expression, as it appears in user's code. 16312 /// 16313 /// \param VD Declaration of an identifier that appears in a type tag. 16314 /// 16315 /// \param MagicValue Type tag magic value. 16316 /// 16317 /// \param isConstantEvaluated whether the evalaution should be performed in 16318 16319 /// constant context. 16320 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 16321 const ValueDecl **VD, uint64_t *MagicValue, 16322 bool isConstantEvaluated) { 16323 while(true) { 16324 if (!TypeExpr) 16325 return false; 16326 16327 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 16328 16329 switch (TypeExpr->getStmtClass()) { 16330 case Stmt::UnaryOperatorClass: { 16331 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 16332 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 16333 TypeExpr = UO->getSubExpr(); 16334 continue; 16335 } 16336 return false; 16337 } 16338 16339 case Stmt::DeclRefExprClass: { 16340 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 16341 *VD = DRE->getDecl(); 16342 return true; 16343 } 16344 16345 case Stmt::IntegerLiteralClass: { 16346 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 16347 llvm::APInt MagicValueAPInt = IL->getValue(); 16348 if (MagicValueAPInt.getActiveBits() <= 64) { 16349 *MagicValue = MagicValueAPInt.getZExtValue(); 16350 return true; 16351 } else 16352 return false; 16353 } 16354 16355 case Stmt::BinaryConditionalOperatorClass: 16356 case Stmt::ConditionalOperatorClass: { 16357 const AbstractConditionalOperator *ACO = 16358 cast<AbstractConditionalOperator>(TypeExpr); 16359 bool Result; 16360 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 16361 isConstantEvaluated)) { 16362 if (Result) 16363 TypeExpr = ACO->getTrueExpr(); 16364 else 16365 TypeExpr = ACO->getFalseExpr(); 16366 continue; 16367 } 16368 return false; 16369 } 16370 16371 case Stmt::BinaryOperatorClass: { 16372 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 16373 if (BO->getOpcode() == BO_Comma) { 16374 TypeExpr = BO->getRHS(); 16375 continue; 16376 } 16377 return false; 16378 } 16379 16380 default: 16381 return false; 16382 } 16383 } 16384 } 16385 16386 /// Retrieve the C type corresponding to type tag TypeExpr. 16387 /// 16388 /// \param TypeExpr Expression that specifies a type tag. 16389 /// 16390 /// \param MagicValues Registered magic values. 16391 /// 16392 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 16393 /// kind. 16394 /// 16395 /// \param TypeInfo Information about the corresponding C type. 16396 /// 16397 /// \param isConstantEvaluated whether the evalaution should be performed in 16398 /// constant context. 16399 /// 16400 /// \returns true if the corresponding C type was found. 16401 static bool GetMatchingCType( 16402 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 16403 const ASTContext &Ctx, 16404 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 16405 *MagicValues, 16406 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 16407 bool isConstantEvaluated) { 16408 FoundWrongKind = false; 16409 16410 // Variable declaration that has type_tag_for_datatype attribute. 16411 const ValueDecl *VD = nullptr; 16412 16413 uint64_t MagicValue; 16414 16415 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 16416 return false; 16417 16418 if (VD) { 16419 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 16420 if (I->getArgumentKind() != ArgumentKind) { 16421 FoundWrongKind = true; 16422 return false; 16423 } 16424 TypeInfo.Type = I->getMatchingCType(); 16425 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 16426 TypeInfo.MustBeNull = I->getMustBeNull(); 16427 return true; 16428 } 16429 return false; 16430 } 16431 16432 if (!MagicValues) 16433 return false; 16434 16435 llvm::DenseMap<Sema::TypeTagMagicValue, 16436 Sema::TypeTagData>::const_iterator I = 16437 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 16438 if (I == MagicValues->end()) 16439 return false; 16440 16441 TypeInfo = I->second; 16442 return true; 16443 } 16444 16445 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 16446 uint64_t MagicValue, QualType Type, 16447 bool LayoutCompatible, 16448 bool MustBeNull) { 16449 if (!TypeTagForDatatypeMagicValues) 16450 TypeTagForDatatypeMagicValues.reset( 16451 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 16452 16453 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 16454 (*TypeTagForDatatypeMagicValues)[Magic] = 16455 TypeTagData(Type, LayoutCompatible, MustBeNull); 16456 } 16457 16458 static bool IsSameCharType(QualType T1, QualType T2) { 16459 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 16460 if (!BT1) 16461 return false; 16462 16463 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 16464 if (!BT2) 16465 return false; 16466 16467 BuiltinType::Kind T1Kind = BT1->getKind(); 16468 BuiltinType::Kind T2Kind = BT2->getKind(); 16469 16470 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 16471 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 16472 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 16473 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 16474 } 16475 16476 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 16477 const ArrayRef<const Expr *> ExprArgs, 16478 SourceLocation CallSiteLoc) { 16479 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 16480 bool IsPointerAttr = Attr->getIsPointer(); 16481 16482 // Retrieve the argument representing the 'type_tag'. 16483 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 16484 if (TypeTagIdxAST >= ExprArgs.size()) { 16485 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16486 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 16487 return; 16488 } 16489 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 16490 bool FoundWrongKind; 16491 TypeTagData TypeInfo; 16492 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 16493 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 16494 TypeInfo, isConstantEvaluated())) { 16495 if (FoundWrongKind) 16496 Diag(TypeTagExpr->getExprLoc(), 16497 diag::warn_type_tag_for_datatype_wrong_kind) 16498 << TypeTagExpr->getSourceRange(); 16499 return; 16500 } 16501 16502 // Retrieve the argument representing the 'arg_idx'. 16503 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 16504 if (ArgumentIdxAST >= ExprArgs.size()) { 16505 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16506 << 1 << Attr->getArgumentIdx().getSourceIndex(); 16507 return; 16508 } 16509 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 16510 if (IsPointerAttr) { 16511 // Skip implicit cast of pointer to `void *' (as a function argument). 16512 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 16513 if (ICE->getType()->isVoidPointerType() && 16514 ICE->getCastKind() == CK_BitCast) 16515 ArgumentExpr = ICE->getSubExpr(); 16516 } 16517 QualType ArgumentType = ArgumentExpr->getType(); 16518 16519 // Passing a `void*' pointer shouldn't trigger a warning. 16520 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 16521 return; 16522 16523 if (TypeInfo.MustBeNull) { 16524 // Type tag with matching void type requires a null pointer. 16525 if (!ArgumentExpr->isNullPointerConstant(Context, 16526 Expr::NPC_ValueDependentIsNotNull)) { 16527 Diag(ArgumentExpr->getExprLoc(), 16528 diag::warn_type_safety_null_pointer_required) 16529 << ArgumentKind->getName() 16530 << ArgumentExpr->getSourceRange() 16531 << TypeTagExpr->getSourceRange(); 16532 } 16533 return; 16534 } 16535 16536 QualType RequiredType = TypeInfo.Type; 16537 if (IsPointerAttr) 16538 RequiredType = Context.getPointerType(RequiredType); 16539 16540 bool mismatch = false; 16541 if (!TypeInfo.LayoutCompatible) { 16542 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 16543 16544 // C++11 [basic.fundamental] p1: 16545 // Plain char, signed char, and unsigned char are three distinct types. 16546 // 16547 // But we treat plain `char' as equivalent to `signed char' or `unsigned 16548 // char' depending on the current char signedness mode. 16549 if (mismatch) 16550 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 16551 RequiredType->getPointeeType())) || 16552 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 16553 mismatch = false; 16554 } else 16555 if (IsPointerAttr) 16556 mismatch = !isLayoutCompatible(Context, 16557 ArgumentType->getPointeeType(), 16558 RequiredType->getPointeeType()); 16559 else 16560 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 16561 16562 if (mismatch) 16563 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 16564 << ArgumentType << ArgumentKind 16565 << TypeInfo.LayoutCompatible << RequiredType 16566 << ArgumentExpr->getSourceRange() 16567 << TypeTagExpr->getSourceRange(); 16568 } 16569 16570 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 16571 CharUnits Alignment) { 16572 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16573 } 16574 16575 void Sema::DiagnoseMisalignedMembers() { 16576 for (MisalignedMember &m : MisalignedMembers) { 16577 const NamedDecl *ND = m.RD; 16578 if (ND->getName().empty()) { 16579 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16580 ND = TD; 16581 } 16582 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16583 << m.MD << ND << m.E->getSourceRange(); 16584 } 16585 MisalignedMembers.clear(); 16586 } 16587 16588 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16589 E = E->IgnoreParens(); 16590 if (!T->isPointerType() && !T->isIntegerType()) 16591 return; 16592 if (isa<UnaryOperator>(E) && 16593 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16594 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16595 if (isa<MemberExpr>(Op)) { 16596 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16597 if (MA != MisalignedMembers.end() && 16598 (T->isIntegerType() || 16599 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16600 Context.getTypeAlignInChars( 16601 T->getPointeeType()) <= MA->Alignment)))) 16602 MisalignedMembers.erase(MA); 16603 } 16604 } 16605 } 16606 16607 void Sema::RefersToMemberWithReducedAlignment( 16608 Expr *E, 16609 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16610 Action) { 16611 const auto *ME = dyn_cast<MemberExpr>(E); 16612 if (!ME) 16613 return; 16614 16615 // No need to check expressions with an __unaligned-qualified type. 16616 if (E->getType().getQualifiers().hasUnaligned()) 16617 return; 16618 16619 // For a chain of MemberExpr like "a.b.c.d" this list 16620 // will keep FieldDecl's like [d, c, b]. 16621 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16622 const MemberExpr *TopME = nullptr; 16623 bool AnyIsPacked = false; 16624 do { 16625 QualType BaseType = ME->getBase()->getType(); 16626 if (BaseType->isDependentType()) 16627 return; 16628 if (ME->isArrow()) 16629 BaseType = BaseType->getPointeeType(); 16630 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16631 if (RD->isInvalidDecl()) 16632 return; 16633 16634 ValueDecl *MD = ME->getMemberDecl(); 16635 auto *FD = dyn_cast<FieldDecl>(MD); 16636 // We do not care about non-data members. 16637 if (!FD || FD->isInvalidDecl()) 16638 return; 16639 16640 AnyIsPacked = 16641 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16642 ReverseMemberChain.push_back(FD); 16643 16644 TopME = ME; 16645 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16646 } while (ME); 16647 assert(TopME && "We did not compute a topmost MemberExpr!"); 16648 16649 // Not the scope of this diagnostic. 16650 if (!AnyIsPacked) 16651 return; 16652 16653 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 16654 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 16655 // TODO: The innermost base of the member expression may be too complicated. 16656 // For now, just disregard these cases. This is left for future 16657 // improvement. 16658 if (!DRE && !isa<CXXThisExpr>(TopBase)) 16659 return; 16660 16661 // Alignment expected by the whole expression. 16662 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 16663 16664 // No need to do anything else with this case. 16665 if (ExpectedAlignment.isOne()) 16666 return; 16667 16668 // Synthesize offset of the whole access. 16669 CharUnits Offset; 16670 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain)) 16671 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD)); 16672 16673 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 16674 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 16675 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 16676 16677 // The base expression of the innermost MemberExpr may give 16678 // stronger guarantees than the class containing the member. 16679 if (DRE && !TopME->isArrow()) { 16680 const ValueDecl *VD = DRE->getDecl(); 16681 if (!VD->getType()->isReferenceType()) 16682 CompleteObjectAlignment = 16683 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 16684 } 16685 16686 // Check if the synthesized offset fulfills the alignment. 16687 if (Offset % ExpectedAlignment != 0 || 16688 // It may fulfill the offset it but the effective alignment may still be 16689 // lower than the expected expression alignment. 16690 CompleteObjectAlignment < ExpectedAlignment) { 16691 // If this happens, we want to determine a sensible culprit of this. 16692 // Intuitively, watching the chain of member expressions from right to 16693 // left, we start with the required alignment (as required by the field 16694 // type) but some packed attribute in that chain has reduced the alignment. 16695 // It may happen that another packed structure increases it again. But if 16696 // we are here such increase has not been enough. So pointing the first 16697 // FieldDecl that either is packed or else its RecordDecl is, 16698 // seems reasonable. 16699 FieldDecl *FD = nullptr; 16700 CharUnits Alignment; 16701 for (FieldDecl *FDI : ReverseMemberChain) { 16702 if (FDI->hasAttr<PackedAttr>() || 16703 FDI->getParent()->hasAttr<PackedAttr>()) { 16704 FD = FDI; 16705 Alignment = std::min( 16706 Context.getTypeAlignInChars(FD->getType()), 16707 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 16708 break; 16709 } 16710 } 16711 assert(FD && "We did not find a packed FieldDecl!"); 16712 Action(E, FD->getParent(), FD, Alignment); 16713 } 16714 } 16715 16716 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 16717 using namespace std::placeholders; 16718 16719 RefersToMemberWithReducedAlignment( 16720 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 16721 _2, _3, _4)); 16722 } 16723 16724 // Check if \p Ty is a valid type for the elementwise math builtins. If it is 16725 // not a valid type, emit an error message and return true. Otherwise return 16726 // false. 16727 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, 16728 QualType Ty) { 16729 if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) { 16730 S.Diag(Loc, diag::err_builtin_invalid_arg_type) 16731 << 1 << /* vector, integer or float ty*/ 0 << Ty; 16732 return true; 16733 } 16734 return false; 16735 } 16736 16737 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) { 16738 if (checkArgCount(*this, TheCall, 1)) 16739 return true; 16740 16741 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 16742 if (A.isInvalid()) 16743 return true; 16744 16745 TheCall->setArg(0, A.get()); 16746 QualType TyA = A.get()->getType(); 16747 16748 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA)) 16749 return true; 16750 16751 TheCall->setType(TyA); 16752 return false; 16753 } 16754 16755 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) { 16756 if (checkArgCount(*this, TheCall, 2)) 16757 return true; 16758 16759 ExprResult A = TheCall->getArg(0); 16760 ExprResult B = TheCall->getArg(1); 16761 // Do standard promotions between the two arguments, returning their common 16762 // type. 16763 QualType Res = 16764 UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison); 16765 if (A.isInvalid() || B.isInvalid()) 16766 return true; 16767 16768 QualType TyA = A.get()->getType(); 16769 QualType TyB = B.get()->getType(); 16770 16771 if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType()) 16772 return Diag(A.get()->getBeginLoc(), 16773 diag::err_typecheck_call_different_arg_types) 16774 << TyA << TyB; 16775 16776 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA)) 16777 return true; 16778 16779 TheCall->setArg(0, A.get()); 16780 TheCall->setArg(1, B.get()); 16781 TheCall->setType(Res); 16782 return false; 16783 } 16784 16785 bool Sema::SemaBuiltinReduceMath(CallExpr *TheCall) { 16786 if (checkArgCount(*this, TheCall, 1)) 16787 return true; 16788 16789 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 16790 if (A.isInvalid()) 16791 return true; 16792 16793 TheCall->setArg(0, A.get()); 16794 const VectorType *TyA = A.get()->getType()->getAs<VectorType>(); 16795 if (!TyA) { 16796 SourceLocation ArgLoc = TheCall->getArg(0)->getBeginLoc(); 16797 return Diag(ArgLoc, diag::err_builtin_invalid_arg_type) 16798 << 1 << /* vector ty*/ 4 << A.get()->getType(); 16799 } 16800 16801 TheCall->setType(TyA->getElementType()); 16802 return false; 16803 } 16804 16805 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 16806 ExprResult CallResult) { 16807 if (checkArgCount(*this, TheCall, 1)) 16808 return ExprError(); 16809 16810 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 16811 if (MatrixArg.isInvalid()) 16812 return MatrixArg; 16813 Expr *Matrix = MatrixArg.get(); 16814 16815 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 16816 if (!MType) { 16817 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16818 << 1 << /* matrix ty*/ 1 << Matrix->getType(); 16819 return ExprError(); 16820 } 16821 16822 // Create returned matrix type by swapping rows and columns of the argument 16823 // matrix type. 16824 QualType ResultType = Context.getConstantMatrixType( 16825 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 16826 16827 // Change the return type to the type of the returned matrix. 16828 TheCall->setType(ResultType); 16829 16830 // Update call argument to use the possibly converted matrix argument. 16831 TheCall->setArg(0, Matrix); 16832 return CallResult; 16833 } 16834 16835 // Get and verify the matrix dimensions. 16836 static llvm::Optional<unsigned> 16837 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16838 SourceLocation ErrorPos; 16839 Optional<llvm::APSInt> Value = 16840 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16841 if (!Value) { 16842 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16843 << Name; 16844 return {}; 16845 } 16846 uint64_t Dim = Value->getZExtValue(); 16847 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16848 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16849 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16850 return {}; 16851 } 16852 return Dim; 16853 } 16854 16855 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16856 ExprResult CallResult) { 16857 if (!getLangOpts().MatrixTypes) { 16858 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16859 return ExprError(); 16860 } 16861 16862 if (checkArgCount(*this, TheCall, 4)) 16863 return ExprError(); 16864 16865 unsigned PtrArgIdx = 0; 16866 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16867 Expr *RowsExpr = TheCall->getArg(1); 16868 Expr *ColumnsExpr = TheCall->getArg(2); 16869 Expr *StrideExpr = TheCall->getArg(3); 16870 16871 bool ArgError = false; 16872 16873 // Check pointer argument. 16874 { 16875 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16876 if (PtrConv.isInvalid()) 16877 return PtrConv; 16878 PtrExpr = PtrConv.get(); 16879 TheCall->setArg(0, PtrExpr); 16880 if (PtrExpr->isTypeDependent()) { 16881 TheCall->setType(Context.DependentTy); 16882 return TheCall; 16883 } 16884 } 16885 16886 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16887 QualType ElementTy; 16888 if (!PtrTy) { 16889 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16890 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 16891 ArgError = true; 16892 } else { 16893 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16894 16895 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16896 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16897 << PtrArgIdx + 1 << /* pointer to element ty*/ 2 16898 << PtrExpr->getType(); 16899 ArgError = true; 16900 } 16901 } 16902 16903 // Apply default Lvalue conversions and convert the expression to size_t. 16904 auto ApplyArgumentConversions = [this](Expr *E) { 16905 ExprResult Conv = DefaultLvalueConversion(E); 16906 if (Conv.isInvalid()) 16907 return Conv; 16908 16909 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16910 }; 16911 16912 // Apply conversion to row and column expressions. 16913 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16914 if (!RowsConv.isInvalid()) { 16915 RowsExpr = RowsConv.get(); 16916 TheCall->setArg(1, RowsExpr); 16917 } else 16918 RowsExpr = nullptr; 16919 16920 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16921 if (!ColumnsConv.isInvalid()) { 16922 ColumnsExpr = ColumnsConv.get(); 16923 TheCall->setArg(2, ColumnsExpr); 16924 } else 16925 ColumnsExpr = nullptr; 16926 16927 // If any any part of the result matrix type is still pending, just use 16928 // Context.DependentTy, until all parts are resolved. 16929 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16930 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16931 TheCall->setType(Context.DependentTy); 16932 return CallResult; 16933 } 16934 16935 // Check row and column dimensions. 16936 llvm::Optional<unsigned> MaybeRows; 16937 if (RowsExpr) 16938 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16939 16940 llvm::Optional<unsigned> MaybeColumns; 16941 if (ColumnsExpr) 16942 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16943 16944 // Check stride argument. 16945 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16946 if (StrideConv.isInvalid()) 16947 return ExprError(); 16948 StrideExpr = StrideConv.get(); 16949 TheCall->setArg(3, StrideExpr); 16950 16951 if (MaybeRows) { 16952 if (Optional<llvm::APSInt> Value = 16953 StrideExpr->getIntegerConstantExpr(Context)) { 16954 uint64_t Stride = Value->getZExtValue(); 16955 if (Stride < *MaybeRows) { 16956 Diag(StrideExpr->getBeginLoc(), 16957 diag::err_builtin_matrix_stride_too_small); 16958 ArgError = true; 16959 } 16960 } 16961 } 16962 16963 if (ArgError || !MaybeRows || !MaybeColumns) 16964 return ExprError(); 16965 16966 TheCall->setType( 16967 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16968 return CallResult; 16969 } 16970 16971 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16972 ExprResult CallResult) { 16973 if (checkArgCount(*this, TheCall, 3)) 16974 return ExprError(); 16975 16976 unsigned PtrArgIdx = 1; 16977 Expr *MatrixExpr = TheCall->getArg(0); 16978 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16979 Expr *StrideExpr = TheCall->getArg(2); 16980 16981 bool ArgError = false; 16982 16983 { 16984 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16985 if (MatrixConv.isInvalid()) 16986 return MatrixConv; 16987 MatrixExpr = MatrixConv.get(); 16988 TheCall->setArg(0, MatrixExpr); 16989 } 16990 if (MatrixExpr->isTypeDependent()) { 16991 TheCall->setType(Context.DependentTy); 16992 return TheCall; 16993 } 16994 16995 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16996 if (!MatrixTy) { 16997 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16998 << 1 << /*matrix ty */ 1 << MatrixExpr->getType(); 16999 ArgError = true; 17000 } 17001 17002 { 17003 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 17004 if (PtrConv.isInvalid()) 17005 return PtrConv; 17006 PtrExpr = PtrConv.get(); 17007 TheCall->setArg(1, PtrExpr); 17008 if (PtrExpr->isTypeDependent()) { 17009 TheCall->setType(Context.DependentTy); 17010 return TheCall; 17011 } 17012 } 17013 17014 // Check pointer argument. 17015 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 17016 if (!PtrTy) { 17017 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17018 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 17019 ArgError = true; 17020 } else { 17021 QualType ElementTy = PtrTy->getPointeeType(); 17022 if (ElementTy.isConstQualified()) { 17023 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 17024 ArgError = true; 17025 } 17026 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 17027 if (MatrixTy && 17028 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 17029 Diag(PtrExpr->getBeginLoc(), 17030 diag::err_builtin_matrix_pointer_arg_mismatch) 17031 << ElementTy << MatrixTy->getElementType(); 17032 ArgError = true; 17033 } 17034 } 17035 17036 // Apply default Lvalue conversions and convert the stride expression to 17037 // size_t. 17038 { 17039 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 17040 if (StrideConv.isInvalid()) 17041 return StrideConv; 17042 17043 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 17044 if (StrideConv.isInvalid()) 17045 return StrideConv; 17046 StrideExpr = StrideConv.get(); 17047 TheCall->setArg(2, StrideExpr); 17048 } 17049 17050 // Check stride argument. 17051 if (MatrixTy) { 17052 if (Optional<llvm::APSInt> Value = 17053 StrideExpr->getIntegerConstantExpr(Context)) { 17054 uint64_t Stride = Value->getZExtValue(); 17055 if (Stride < MatrixTy->getNumRows()) { 17056 Diag(StrideExpr->getBeginLoc(), 17057 diag::err_builtin_matrix_stride_too_small); 17058 ArgError = true; 17059 } 17060 } 17061 } 17062 17063 if (ArgError) 17064 return ExprError(); 17065 17066 return CallResult; 17067 } 17068 17069 /// \brief Enforce the bounds of a TCB 17070 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 17071 /// directly calls other functions in the same TCB as marked by the enforce_tcb 17072 /// and enforce_tcb_leaf attributes. 17073 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 17074 const FunctionDecl *Callee) { 17075 const FunctionDecl *Caller = getCurFunctionDecl(); 17076 17077 // Calls to builtins are not enforced. 17078 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 17079 Callee->getBuiltinID() != 0) 17080 return; 17081 17082 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 17083 // all TCBs the callee is a part of. 17084 llvm::StringSet<> CalleeTCBs; 17085 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 17086 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 17087 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 17088 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 17089 17090 // Go through the TCBs the caller is a part of and emit warnings if Caller 17091 // is in a TCB that the Callee is not. 17092 for_each( 17093 Caller->specific_attrs<EnforceTCBAttr>(), 17094 [&](const auto *A) { 17095 StringRef CallerTCB = A->getTCBName(); 17096 if (CalleeTCBs.count(CallerTCB) == 0) { 17097 this->Diag(TheCall->getExprLoc(), 17098 diag::warn_tcb_enforcement_violation) << Callee 17099 << CallerTCB; 17100 } 17101 }); 17102 } 17103