1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSet.h" 79 #include "llvm/ADT/StringSwitch.h" 80 #include "llvm/ADT/Triple.h" 81 #include "llvm/Support/AtomicOrdering.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/ConvertUTF.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/Locale.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/SaveAndRestore.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 #include <bitset> 93 #include <cassert> 94 #include <cctype> 95 #include <cstddef> 96 #include <cstdint> 97 #include <functional> 98 #include <limits> 99 #include <string> 100 #include <tuple> 101 #include <utility> 102 103 using namespace clang; 104 using namespace sema; 105 106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 107 unsigned ByteNo) const { 108 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 109 Context.getTargetInfo()); 110 } 111 112 /// Checks that a call expression's argument count is the desired number. 113 /// This is useful when doing custom type-checking. Returns true on error. 114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 115 unsigned argCount = call->getNumArgs(); 116 if (argCount == desiredArgCount) return false; 117 118 if (argCount < desiredArgCount) 119 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 120 << 0 /*function call*/ << desiredArgCount << argCount 121 << call->getSourceRange(); 122 123 // Highlight all the excess arguments. 124 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 125 call->getArg(argCount - 1)->getEndLoc()); 126 127 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 128 << 0 /*function call*/ << desiredArgCount << argCount 129 << call->getArg(1)->getSourceRange(); 130 } 131 132 /// Check that the first argument to __builtin_annotation is an integer 133 /// and the second argument is a non-wide string literal. 134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 135 if (checkArgCount(S, TheCall, 2)) 136 return true; 137 138 // First argument should be an integer. 139 Expr *ValArg = TheCall->getArg(0); 140 QualType Ty = ValArg->getType(); 141 if (!Ty->isIntegerType()) { 142 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 143 << ValArg->getSourceRange(); 144 return true; 145 } 146 147 // Second argument should be a constant string. 148 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 149 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 150 if (!Literal || !Literal->isAscii()) { 151 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 152 << StrArg->getSourceRange(); 153 return true; 154 } 155 156 TheCall->setType(Ty); 157 return false; 158 } 159 160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 161 // We need at least one argument. 162 if (TheCall->getNumArgs() < 1) { 163 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 164 << 0 << 1 << TheCall->getNumArgs() 165 << TheCall->getCallee()->getSourceRange(); 166 return true; 167 } 168 169 // All arguments should be wide string literals. 170 for (Expr *Arg : TheCall->arguments()) { 171 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 172 if (!Literal || !Literal->isWide()) { 173 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 174 << Arg->getSourceRange(); 175 return true; 176 } 177 } 178 179 return false; 180 } 181 182 /// Check that the argument to __builtin_addressof is a glvalue, and set the 183 /// result type to the corresponding pointer type. 184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 185 if (checkArgCount(S, TheCall, 1)) 186 return true; 187 188 ExprResult Arg(TheCall->getArg(0)); 189 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 190 if (ResultType.isNull()) 191 return true; 192 193 TheCall->setArg(0, Arg.get()); 194 TheCall->setType(ResultType); 195 return false; 196 } 197 198 /// Check that the argument to __builtin_function_start is a function. 199 static bool SemaBuiltinFunctionStart(Sema &S, CallExpr *TheCall) { 200 if (checkArgCount(S, TheCall, 1)) 201 return true; 202 203 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 204 if (Arg.isInvalid()) 205 return true; 206 207 TheCall->setArg(0, Arg.get()); 208 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>( 209 Arg.get()->getAsBuiltinConstantDeclRef(S.getASTContext())); 210 211 if (!FD) { 212 S.Diag(TheCall->getBeginLoc(), diag::err_function_start_invalid_type) 213 << TheCall->getSourceRange(); 214 return true; 215 } 216 217 return !S.checkAddressOfFunctionIsAvailable(FD, /*Complain=*/true, 218 TheCall->getBeginLoc()); 219 } 220 221 /// Check the number of arguments and set the result type to 222 /// the argument type. 223 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 224 if (checkArgCount(S, TheCall, 1)) 225 return true; 226 227 TheCall->setType(TheCall->getArg(0)->getType()); 228 return false; 229 } 230 231 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 232 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 233 /// type (but not a function pointer) and that the alignment is a power-of-two. 234 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 235 if (checkArgCount(S, TheCall, 2)) 236 return true; 237 238 clang::Expr *Source = TheCall->getArg(0); 239 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 240 241 auto IsValidIntegerType = [](QualType Ty) { 242 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 243 }; 244 QualType SrcTy = Source->getType(); 245 // We should also be able to use it with arrays (but not functions!). 246 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 247 SrcTy = S.Context.getDecayedType(SrcTy); 248 } 249 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 250 SrcTy->isFunctionPointerType()) { 251 // FIXME: this is not quite the right error message since we don't allow 252 // floating point types, or member pointers. 253 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 254 << SrcTy; 255 return true; 256 } 257 258 clang::Expr *AlignOp = TheCall->getArg(1); 259 if (!IsValidIntegerType(AlignOp->getType())) { 260 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 261 << AlignOp->getType(); 262 return true; 263 } 264 Expr::EvalResult AlignResult; 265 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 266 // We can't check validity of alignment if it is value dependent. 267 if (!AlignOp->isValueDependent() && 268 AlignOp->EvaluateAsInt(AlignResult, S.Context, 269 Expr::SE_AllowSideEffects)) { 270 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 271 llvm::APSInt MaxValue( 272 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 273 if (AlignValue < 1) { 274 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 275 return true; 276 } 277 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 278 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 279 << toString(MaxValue, 10); 280 return true; 281 } 282 if (!AlignValue.isPowerOf2()) { 283 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 284 return true; 285 } 286 if (AlignValue == 1) { 287 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 288 << IsBooleanAlignBuiltin; 289 } 290 } 291 292 ExprResult SrcArg = S.PerformCopyInitialization( 293 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 294 SourceLocation(), Source); 295 if (SrcArg.isInvalid()) 296 return true; 297 TheCall->setArg(0, SrcArg.get()); 298 ExprResult AlignArg = 299 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 300 S.Context, AlignOp->getType(), false), 301 SourceLocation(), AlignOp); 302 if (AlignArg.isInvalid()) 303 return true; 304 TheCall->setArg(1, AlignArg.get()); 305 // For align_up/align_down, the return type is the same as the (potentially 306 // decayed) argument type including qualifiers. For is_aligned(), the result 307 // is always bool. 308 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 309 return false; 310 } 311 312 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 313 unsigned BuiltinID) { 314 if (checkArgCount(S, TheCall, 3)) 315 return true; 316 317 // First two arguments should be integers. 318 for (unsigned I = 0; I < 2; ++I) { 319 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 320 if (Arg.isInvalid()) return true; 321 TheCall->setArg(I, Arg.get()); 322 323 QualType Ty = Arg.get()->getType(); 324 if (!Ty->isIntegerType()) { 325 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 326 << Ty << Arg.get()->getSourceRange(); 327 return true; 328 } 329 } 330 331 // Third argument should be a pointer to a non-const integer. 332 // IRGen correctly handles volatile, restrict, and address spaces, and 333 // the other qualifiers aren't possible. 334 { 335 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 336 if (Arg.isInvalid()) return true; 337 TheCall->setArg(2, Arg.get()); 338 339 QualType Ty = Arg.get()->getType(); 340 const auto *PtrTy = Ty->getAs<PointerType>(); 341 if (!PtrTy || 342 !PtrTy->getPointeeType()->isIntegerType() || 343 PtrTy->getPointeeType().isConstQualified()) { 344 S.Diag(Arg.get()->getBeginLoc(), 345 diag::err_overflow_builtin_must_be_ptr_int) 346 << Ty << Arg.get()->getSourceRange(); 347 return true; 348 } 349 } 350 351 // Disallow signed bit-precise integer args larger than 128 bits to mul 352 // function until we improve backend support. 353 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 354 for (unsigned I = 0; I < 3; ++I) { 355 const auto Arg = TheCall->getArg(I); 356 // Third argument will be a pointer. 357 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 358 if (Ty->isBitIntType() && Ty->isSignedIntegerType() && 359 S.getASTContext().getIntWidth(Ty) > 128) 360 return S.Diag(Arg->getBeginLoc(), 361 diag::err_overflow_builtin_bit_int_max_size) 362 << 128; 363 } 364 } 365 366 return false; 367 } 368 369 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 370 if (checkArgCount(S, BuiltinCall, 2)) 371 return true; 372 373 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 374 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 375 Expr *Call = BuiltinCall->getArg(0); 376 Expr *Chain = BuiltinCall->getArg(1); 377 378 if (Call->getStmtClass() != Stmt::CallExprClass) { 379 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 380 << Call->getSourceRange(); 381 return true; 382 } 383 384 auto CE = cast<CallExpr>(Call); 385 if (CE->getCallee()->getType()->isBlockPointerType()) { 386 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 387 << Call->getSourceRange(); 388 return true; 389 } 390 391 const Decl *TargetDecl = CE->getCalleeDecl(); 392 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 393 if (FD->getBuiltinID()) { 394 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 395 << Call->getSourceRange(); 396 return true; 397 } 398 399 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 400 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 401 << Call->getSourceRange(); 402 return true; 403 } 404 405 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 406 if (ChainResult.isInvalid()) 407 return true; 408 if (!ChainResult.get()->getType()->isPointerType()) { 409 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 410 << Chain->getSourceRange(); 411 return true; 412 } 413 414 QualType ReturnTy = CE->getCallReturnType(S.Context); 415 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 416 QualType BuiltinTy = S.Context.getFunctionType( 417 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 418 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 419 420 Builtin = 421 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 422 423 BuiltinCall->setType(CE->getType()); 424 BuiltinCall->setValueKind(CE->getValueKind()); 425 BuiltinCall->setObjectKind(CE->getObjectKind()); 426 BuiltinCall->setCallee(Builtin); 427 BuiltinCall->setArg(1, ChainResult.get()); 428 429 return false; 430 } 431 432 namespace { 433 434 class ScanfDiagnosticFormatHandler 435 : public analyze_format_string::FormatStringHandler { 436 // Accepts the argument index (relative to the first destination index) of the 437 // argument whose size we want. 438 using ComputeSizeFunction = 439 llvm::function_ref<Optional<llvm::APSInt>(unsigned)>; 440 441 // Accepts the argument index (relative to the first destination index), the 442 // destination size, and the source size). 443 using DiagnoseFunction = 444 llvm::function_ref<void(unsigned, unsigned, unsigned)>; 445 446 ComputeSizeFunction ComputeSizeArgument; 447 DiagnoseFunction Diagnose; 448 449 public: 450 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument, 451 DiagnoseFunction Diagnose) 452 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {} 453 454 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 455 const char *StartSpecifier, 456 unsigned specifierLen) override { 457 if (!FS.consumesDataArgument()) 458 return true; 459 460 unsigned NulByte = 0; 461 switch ((FS.getConversionSpecifier().getKind())) { 462 default: 463 return true; 464 case analyze_format_string::ConversionSpecifier::sArg: 465 case analyze_format_string::ConversionSpecifier::ScanListArg: 466 NulByte = 1; 467 break; 468 case analyze_format_string::ConversionSpecifier::cArg: 469 break; 470 } 471 472 analyze_format_string::OptionalAmount FW = FS.getFieldWidth(); 473 if (FW.getHowSpecified() != 474 analyze_format_string::OptionalAmount::HowSpecified::Constant) 475 return true; 476 477 unsigned SourceSize = FW.getConstantAmount() + NulByte; 478 479 Optional<llvm::APSInt> DestSizeAPS = ComputeSizeArgument(FS.getArgIndex()); 480 if (!DestSizeAPS) 481 return true; 482 483 unsigned DestSize = DestSizeAPS->getZExtValue(); 484 485 if (DestSize < SourceSize) 486 Diagnose(FS.getArgIndex(), DestSize, SourceSize); 487 488 return true; 489 } 490 }; 491 492 class EstimateSizeFormatHandler 493 : public analyze_format_string::FormatStringHandler { 494 size_t Size; 495 496 public: 497 EstimateSizeFormatHandler(StringRef Format) 498 : Size(std::min(Format.find(0), Format.size()) + 499 1 /* null byte always written by sprintf */) {} 500 501 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 502 const char *, unsigned SpecifierLen) override { 503 504 const size_t FieldWidth = computeFieldWidth(FS); 505 const size_t Precision = computePrecision(FS); 506 507 // The actual format. 508 switch (FS.getConversionSpecifier().getKind()) { 509 // Just a char. 510 case analyze_format_string::ConversionSpecifier::cArg: 511 case analyze_format_string::ConversionSpecifier::CArg: 512 Size += std::max(FieldWidth, (size_t)1); 513 break; 514 // Just an integer. 515 case analyze_format_string::ConversionSpecifier::dArg: 516 case analyze_format_string::ConversionSpecifier::DArg: 517 case analyze_format_string::ConversionSpecifier::iArg: 518 case analyze_format_string::ConversionSpecifier::oArg: 519 case analyze_format_string::ConversionSpecifier::OArg: 520 case analyze_format_string::ConversionSpecifier::uArg: 521 case analyze_format_string::ConversionSpecifier::UArg: 522 case analyze_format_string::ConversionSpecifier::xArg: 523 case analyze_format_string::ConversionSpecifier::XArg: 524 Size += std::max(FieldWidth, Precision); 525 break; 526 527 // %g style conversion switches between %f or %e style dynamically. 528 // %f always takes less space, so default to it. 529 case analyze_format_string::ConversionSpecifier::gArg: 530 case analyze_format_string::ConversionSpecifier::GArg: 531 532 // Floating point number in the form '[+]ddd.ddd'. 533 case analyze_format_string::ConversionSpecifier::fArg: 534 case analyze_format_string::ConversionSpecifier::FArg: 535 Size += std::max(FieldWidth, 1 /* integer part */ + 536 (Precision ? 1 + Precision 537 : 0) /* period + decimal */); 538 break; 539 540 // Floating point number in the form '[-]d.ddde[+-]dd'. 541 case analyze_format_string::ConversionSpecifier::eArg: 542 case analyze_format_string::ConversionSpecifier::EArg: 543 Size += 544 std::max(FieldWidth, 545 1 /* integer part */ + 546 (Precision ? 1 + Precision : 0) /* period + decimal */ + 547 1 /* e or E letter */ + 2 /* exponent */); 548 break; 549 550 // Floating point number in the form '[-]0xh.hhhhp±dd'. 551 case analyze_format_string::ConversionSpecifier::aArg: 552 case analyze_format_string::ConversionSpecifier::AArg: 553 Size += 554 std::max(FieldWidth, 555 2 /* 0x */ + 1 /* integer part */ + 556 (Precision ? 1 + Precision : 0) /* period + decimal */ + 557 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 558 break; 559 560 // Just a string. 561 case analyze_format_string::ConversionSpecifier::sArg: 562 case analyze_format_string::ConversionSpecifier::SArg: 563 Size += FieldWidth; 564 break; 565 566 // Just a pointer in the form '0xddd'. 567 case analyze_format_string::ConversionSpecifier::pArg: 568 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 569 break; 570 571 // A plain percent. 572 case analyze_format_string::ConversionSpecifier::PercentArg: 573 Size += 1; 574 break; 575 576 default: 577 break; 578 } 579 580 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 581 582 if (FS.hasAlternativeForm()) { 583 switch (FS.getConversionSpecifier().getKind()) { 584 default: 585 break; 586 // Force a leading '0'. 587 case analyze_format_string::ConversionSpecifier::oArg: 588 Size += 1; 589 break; 590 // Force a leading '0x'. 591 case analyze_format_string::ConversionSpecifier::xArg: 592 case analyze_format_string::ConversionSpecifier::XArg: 593 Size += 2; 594 break; 595 // Force a period '.' before decimal, even if precision is 0. 596 case analyze_format_string::ConversionSpecifier::aArg: 597 case analyze_format_string::ConversionSpecifier::AArg: 598 case analyze_format_string::ConversionSpecifier::eArg: 599 case analyze_format_string::ConversionSpecifier::EArg: 600 case analyze_format_string::ConversionSpecifier::fArg: 601 case analyze_format_string::ConversionSpecifier::FArg: 602 case analyze_format_string::ConversionSpecifier::gArg: 603 case analyze_format_string::ConversionSpecifier::GArg: 604 Size += (Precision ? 0 : 1); 605 break; 606 } 607 } 608 assert(SpecifierLen <= Size && "no underflow"); 609 Size -= SpecifierLen; 610 return true; 611 } 612 613 size_t getSizeLowerBound() const { return Size; } 614 615 private: 616 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 617 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 618 size_t FieldWidth = 0; 619 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 620 FieldWidth = FW.getConstantAmount(); 621 return FieldWidth; 622 } 623 624 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 625 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 626 size_t Precision = 0; 627 628 // See man 3 printf for default precision value based on the specifier. 629 switch (FW.getHowSpecified()) { 630 case analyze_format_string::OptionalAmount::NotSpecified: 631 switch (FS.getConversionSpecifier().getKind()) { 632 default: 633 break; 634 case analyze_format_string::ConversionSpecifier::dArg: // %d 635 case analyze_format_string::ConversionSpecifier::DArg: // %D 636 case analyze_format_string::ConversionSpecifier::iArg: // %i 637 Precision = 1; 638 break; 639 case analyze_format_string::ConversionSpecifier::oArg: // %d 640 case analyze_format_string::ConversionSpecifier::OArg: // %D 641 case analyze_format_string::ConversionSpecifier::uArg: // %d 642 case analyze_format_string::ConversionSpecifier::UArg: // %D 643 case analyze_format_string::ConversionSpecifier::xArg: // %d 644 case analyze_format_string::ConversionSpecifier::XArg: // %D 645 Precision = 1; 646 break; 647 case analyze_format_string::ConversionSpecifier::fArg: // %f 648 case analyze_format_string::ConversionSpecifier::FArg: // %F 649 case analyze_format_string::ConversionSpecifier::eArg: // %e 650 case analyze_format_string::ConversionSpecifier::EArg: // %E 651 case analyze_format_string::ConversionSpecifier::gArg: // %g 652 case analyze_format_string::ConversionSpecifier::GArg: // %G 653 Precision = 6; 654 break; 655 case analyze_format_string::ConversionSpecifier::pArg: // %d 656 Precision = 1; 657 break; 658 } 659 break; 660 case analyze_format_string::OptionalAmount::Constant: 661 Precision = FW.getConstantAmount(); 662 break; 663 default: 664 break; 665 } 666 return Precision; 667 } 668 }; 669 670 } // namespace 671 672 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 673 CallExpr *TheCall) { 674 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 675 isConstantEvaluated()) 676 return; 677 678 bool UseDABAttr = false; 679 const FunctionDecl *UseDecl = FD; 680 681 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>(); 682 if (DABAttr) { 683 UseDecl = DABAttr->getFunction(); 684 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!"); 685 UseDABAttr = true; 686 } 687 688 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true); 689 690 if (!BuiltinID) 691 return; 692 693 const TargetInfo &TI = getASTContext().getTargetInfo(); 694 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 695 696 auto TranslateIndex = [&](unsigned Index) -> Optional<unsigned> { 697 // If we refer to a diagnose_as_builtin attribute, we need to change the 698 // argument index to refer to the arguments of the called function. Unless 699 // the index is out of bounds, which presumably means it's a variadic 700 // function. 701 if (!UseDABAttr) 702 return Index; 703 unsigned DABIndices = DABAttr->argIndices_size(); 704 unsigned NewIndex = Index < DABIndices 705 ? DABAttr->argIndices_begin()[Index] 706 : Index - DABIndices + FD->getNumParams(); 707 if (NewIndex >= TheCall->getNumArgs()) 708 return llvm::None; 709 return NewIndex; 710 }; 711 712 auto ComputeExplicitObjectSizeArgument = 713 [&](unsigned Index) -> Optional<llvm::APSInt> { 714 Optional<unsigned> IndexOptional = TranslateIndex(Index); 715 if (!IndexOptional) 716 return llvm::None; 717 unsigned NewIndex = IndexOptional.getValue(); 718 Expr::EvalResult Result; 719 Expr *SizeArg = TheCall->getArg(NewIndex); 720 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 721 return llvm::None; 722 llvm::APSInt Integer = Result.Val.getInt(); 723 Integer.setIsUnsigned(true); 724 return Integer; 725 }; 726 727 auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 728 // If the parameter has a pass_object_size attribute, then we should use its 729 // (potentially) more strict checking mode. Otherwise, conservatively assume 730 // type 0. 731 int BOSType = 0; 732 // This check can fail for variadic functions. 733 if (Index < FD->getNumParams()) { 734 if (const auto *POS = 735 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>()) 736 BOSType = POS->getType(); 737 } 738 739 Optional<unsigned> IndexOptional = TranslateIndex(Index); 740 if (!IndexOptional) 741 return llvm::None; 742 unsigned NewIndex = IndexOptional.getValue(); 743 744 const Expr *ObjArg = TheCall->getArg(NewIndex); 745 uint64_t Result; 746 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 747 return llvm::None; 748 749 // Get the object size in the target's size_t width. 750 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 751 }; 752 753 auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 754 Optional<unsigned> IndexOptional = TranslateIndex(Index); 755 if (!IndexOptional) 756 return llvm::None; 757 unsigned NewIndex = IndexOptional.getValue(); 758 759 const Expr *ObjArg = TheCall->getArg(NewIndex); 760 uint64_t Result; 761 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext())) 762 return llvm::None; 763 // Add 1 for null byte. 764 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth); 765 }; 766 767 Optional<llvm::APSInt> SourceSize; 768 Optional<llvm::APSInt> DestinationSize; 769 unsigned DiagID = 0; 770 bool IsChkVariant = false; 771 772 auto GetFunctionName = [&]() { 773 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 774 // Skim off the details of whichever builtin was called to produce a better 775 // diagnostic, as it's unlikely that the user wrote the __builtin 776 // explicitly. 777 if (IsChkVariant) { 778 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 779 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 780 } else if (FunctionName.startswith("__builtin_")) { 781 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 782 } 783 return FunctionName; 784 }; 785 786 switch (BuiltinID) { 787 default: 788 return; 789 case Builtin::BI__builtin_strcpy: 790 case Builtin::BIstrcpy: { 791 DiagID = diag::warn_fortify_strlen_overflow; 792 SourceSize = ComputeStrLenArgument(1); 793 DestinationSize = ComputeSizeArgument(0); 794 break; 795 } 796 797 case Builtin::BI__builtin___strcpy_chk: { 798 DiagID = diag::warn_fortify_strlen_overflow; 799 SourceSize = ComputeStrLenArgument(1); 800 DestinationSize = ComputeExplicitObjectSizeArgument(2); 801 IsChkVariant = true; 802 break; 803 } 804 805 case Builtin::BIscanf: 806 case Builtin::BIfscanf: 807 case Builtin::BIsscanf: { 808 unsigned FormatIndex = 1; 809 unsigned DataIndex = 2; 810 if (BuiltinID == Builtin::BIscanf) { 811 FormatIndex = 0; 812 DataIndex = 1; 813 } 814 815 const auto *FormatExpr = 816 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 817 818 const auto *Format = dyn_cast<StringLiteral>(FormatExpr); 819 if (!Format) 820 return; 821 822 if (!Format->isAscii() && !Format->isUTF8()) 823 return; 824 825 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize, 826 unsigned SourceSize) { 827 DiagID = diag::warn_fortify_scanf_overflow; 828 unsigned Index = ArgIndex + DataIndex; 829 StringRef FunctionName = GetFunctionName(); 830 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall, 831 PDiag(DiagID) << FunctionName << (Index + 1) 832 << DestSize << SourceSize); 833 }; 834 835 StringRef FormatStrRef = Format->getString(); 836 auto ShiftedComputeSizeArgument = [&](unsigned Index) { 837 return ComputeSizeArgument(Index + DataIndex); 838 }; 839 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose); 840 const char *FormatBytes = FormatStrRef.data(); 841 const ConstantArrayType *T = 842 Context.getAsConstantArrayType(Format->getType()); 843 assert(T && "String literal not of constant array type!"); 844 size_t TypeSize = T->getSize().getZExtValue(); 845 846 // In case there's a null byte somewhere. 847 size_t StrLen = 848 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 849 850 analyze_format_string::ParseScanfString(H, FormatBytes, 851 FormatBytes + StrLen, getLangOpts(), 852 Context.getTargetInfo()); 853 854 // Unlike the other cases, in this one we have already issued the diagnostic 855 // here, so no need to continue (because unlike the other cases, here the 856 // diagnostic refers to the argument number). 857 return; 858 } 859 860 case Builtin::BIsprintf: 861 case Builtin::BI__builtin___sprintf_chk: { 862 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 863 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 864 865 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 866 867 if (!Format->isAscii() && !Format->isUTF8()) 868 return; 869 870 StringRef FormatStrRef = Format->getString(); 871 EstimateSizeFormatHandler H(FormatStrRef); 872 const char *FormatBytes = FormatStrRef.data(); 873 const ConstantArrayType *T = 874 Context.getAsConstantArrayType(Format->getType()); 875 assert(T && "String literal not of constant array type!"); 876 size_t TypeSize = T->getSize().getZExtValue(); 877 878 // In case there's a null byte somewhere. 879 size_t StrLen = 880 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 881 if (!analyze_format_string::ParsePrintfString( 882 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 883 Context.getTargetInfo(), false)) { 884 DiagID = diag::warn_fortify_source_format_overflow; 885 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 886 .extOrTrunc(SizeTypeWidth); 887 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 888 DestinationSize = ComputeExplicitObjectSizeArgument(2); 889 IsChkVariant = true; 890 } else { 891 DestinationSize = ComputeSizeArgument(0); 892 } 893 break; 894 } 895 } 896 return; 897 } 898 case Builtin::BI__builtin___memcpy_chk: 899 case Builtin::BI__builtin___memmove_chk: 900 case Builtin::BI__builtin___memset_chk: 901 case Builtin::BI__builtin___strlcat_chk: 902 case Builtin::BI__builtin___strlcpy_chk: 903 case Builtin::BI__builtin___strncat_chk: 904 case Builtin::BI__builtin___strncpy_chk: 905 case Builtin::BI__builtin___stpncpy_chk: 906 case Builtin::BI__builtin___memccpy_chk: 907 case Builtin::BI__builtin___mempcpy_chk: { 908 DiagID = diag::warn_builtin_chk_overflow; 909 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2); 910 DestinationSize = 911 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 912 IsChkVariant = true; 913 break; 914 } 915 916 case Builtin::BI__builtin___snprintf_chk: 917 case Builtin::BI__builtin___vsnprintf_chk: { 918 DiagID = diag::warn_builtin_chk_overflow; 919 SourceSize = ComputeExplicitObjectSizeArgument(1); 920 DestinationSize = ComputeExplicitObjectSizeArgument(3); 921 IsChkVariant = true; 922 break; 923 } 924 925 case Builtin::BIstrncat: 926 case Builtin::BI__builtin_strncat: 927 case Builtin::BIstrncpy: 928 case Builtin::BI__builtin_strncpy: 929 case Builtin::BIstpncpy: 930 case Builtin::BI__builtin_stpncpy: { 931 // Whether these functions overflow depends on the runtime strlen of the 932 // string, not just the buffer size, so emitting the "always overflow" 933 // diagnostic isn't quite right. We should still diagnose passing a buffer 934 // size larger than the destination buffer though; this is a runtime abort 935 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 936 DiagID = diag::warn_fortify_source_size_mismatch; 937 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 938 DestinationSize = ComputeSizeArgument(0); 939 break; 940 } 941 942 case Builtin::BImemcpy: 943 case Builtin::BI__builtin_memcpy: 944 case Builtin::BImemmove: 945 case Builtin::BI__builtin_memmove: 946 case Builtin::BImemset: 947 case Builtin::BI__builtin_memset: 948 case Builtin::BImempcpy: 949 case Builtin::BI__builtin_mempcpy: { 950 DiagID = diag::warn_fortify_source_overflow; 951 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 952 DestinationSize = ComputeSizeArgument(0); 953 break; 954 } 955 case Builtin::BIsnprintf: 956 case Builtin::BI__builtin_snprintf: 957 case Builtin::BIvsnprintf: 958 case Builtin::BI__builtin_vsnprintf: { 959 DiagID = diag::warn_fortify_source_size_mismatch; 960 SourceSize = ComputeExplicitObjectSizeArgument(1); 961 DestinationSize = ComputeSizeArgument(0); 962 break; 963 } 964 } 965 966 if (!SourceSize || !DestinationSize || 967 llvm::APSInt::compareValues(SourceSize.getValue(), 968 DestinationSize.getValue()) <= 0) 969 return; 970 971 StringRef FunctionName = GetFunctionName(); 972 973 SmallString<16> DestinationStr; 974 SmallString<16> SourceStr; 975 DestinationSize->toString(DestinationStr, /*Radix=*/10); 976 SourceSize->toString(SourceStr, /*Radix=*/10); 977 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 978 PDiag(DiagID) 979 << FunctionName << DestinationStr << SourceStr); 980 } 981 982 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 983 Scope::ScopeFlags NeededScopeFlags, 984 unsigned DiagID) { 985 // Scopes aren't available during instantiation. Fortunately, builtin 986 // functions cannot be template args so they cannot be formed through template 987 // instantiation. Therefore checking once during the parse is sufficient. 988 if (SemaRef.inTemplateInstantiation()) 989 return false; 990 991 Scope *S = SemaRef.getCurScope(); 992 while (S && !S->isSEHExceptScope()) 993 S = S->getParent(); 994 if (!S || !(S->getFlags() & NeededScopeFlags)) { 995 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 996 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 997 << DRE->getDecl()->getIdentifier(); 998 return true; 999 } 1000 1001 return false; 1002 } 1003 1004 static inline bool isBlockPointer(Expr *Arg) { 1005 return Arg->getType()->isBlockPointerType(); 1006 } 1007 1008 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 1009 /// void*, which is a requirement of device side enqueue. 1010 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 1011 const BlockPointerType *BPT = 1012 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 1013 ArrayRef<QualType> Params = 1014 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 1015 unsigned ArgCounter = 0; 1016 bool IllegalParams = false; 1017 // Iterate through the block parameters until either one is found that is not 1018 // a local void*, or the block is valid. 1019 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 1020 I != E; ++I, ++ArgCounter) { 1021 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 1022 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 1023 LangAS::opencl_local) { 1024 // Get the location of the error. If a block literal has been passed 1025 // (BlockExpr) then we can point straight to the offending argument, 1026 // else we just point to the variable reference. 1027 SourceLocation ErrorLoc; 1028 if (isa<BlockExpr>(BlockArg)) { 1029 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 1030 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 1031 } else if (isa<DeclRefExpr>(BlockArg)) { 1032 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 1033 } 1034 S.Diag(ErrorLoc, 1035 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 1036 IllegalParams = true; 1037 } 1038 } 1039 1040 return IllegalParams; 1041 } 1042 1043 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 1044 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) { 1045 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 1046 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 1047 return true; 1048 } 1049 return false; 1050 } 1051 1052 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 1053 if (checkArgCount(S, TheCall, 2)) 1054 return true; 1055 1056 if (checkOpenCLSubgroupExt(S, TheCall)) 1057 return true; 1058 1059 // First argument is an ndrange_t type. 1060 Expr *NDRangeArg = TheCall->getArg(0); 1061 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 1062 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1063 << TheCall->getDirectCallee() << "'ndrange_t'"; 1064 return true; 1065 } 1066 1067 Expr *BlockArg = TheCall->getArg(1); 1068 if (!isBlockPointer(BlockArg)) { 1069 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1070 << TheCall->getDirectCallee() << "block"; 1071 return true; 1072 } 1073 return checkOpenCLBlockArgs(S, BlockArg); 1074 } 1075 1076 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 1077 /// get_kernel_work_group_size 1078 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 1079 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 1080 if (checkArgCount(S, TheCall, 1)) 1081 return true; 1082 1083 Expr *BlockArg = TheCall->getArg(0); 1084 if (!isBlockPointer(BlockArg)) { 1085 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1086 << TheCall->getDirectCallee() << "block"; 1087 return true; 1088 } 1089 return checkOpenCLBlockArgs(S, BlockArg); 1090 } 1091 1092 /// Diagnose integer type and any valid implicit conversion to it. 1093 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 1094 const QualType &IntType); 1095 1096 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 1097 unsigned Start, unsigned End) { 1098 bool IllegalParams = false; 1099 for (unsigned I = Start; I <= End; ++I) 1100 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 1101 S.Context.getSizeType()); 1102 return IllegalParams; 1103 } 1104 1105 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 1106 /// 'local void*' parameter of passed block. 1107 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 1108 Expr *BlockArg, 1109 unsigned NumNonVarArgs) { 1110 const BlockPointerType *BPT = 1111 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 1112 unsigned NumBlockParams = 1113 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 1114 unsigned TotalNumArgs = TheCall->getNumArgs(); 1115 1116 // For each argument passed to the block, a corresponding uint needs to 1117 // be passed to describe the size of the local memory. 1118 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 1119 S.Diag(TheCall->getBeginLoc(), 1120 diag::err_opencl_enqueue_kernel_local_size_args); 1121 return true; 1122 } 1123 1124 // Check that the sizes of the local memory are specified by integers. 1125 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 1126 TotalNumArgs - 1); 1127 } 1128 1129 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 1130 /// overload formats specified in Table 6.13.17.1. 1131 /// int enqueue_kernel(queue_t queue, 1132 /// kernel_enqueue_flags_t flags, 1133 /// const ndrange_t ndrange, 1134 /// void (^block)(void)) 1135 /// int enqueue_kernel(queue_t queue, 1136 /// kernel_enqueue_flags_t flags, 1137 /// const ndrange_t ndrange, 1138 /// uint num_events_in_wait_list, 1139 /// clk_event_t *event_wait_list, 1140 /// clk_event_t *event_ret, 1141 /// void (^block)(void)) 1142 /// int enqueue_kernel(queue_t queue, 1143 /// kernel_enqueue_flags_t flags, 1144 /// const ndrange_t ndrange, 1145 /// void (^block)(local void*, ...), 1146 /// uint size0, ...) 1147 /// int enqueue_kernel(queue_t queue, 1148 /// kernel_enqueue_flags_t flags, 1149 /// const ndrange_t ndrange, 1150 /// uint num_events_in_wait_list, 1151 /// clk_event_t *event_wait_list, 1152 /// clk_event_t *event_ret, 1153 /// void (^block)(local void*, ...), 1154 /// uint size0, ...) 1155 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 1156 unsigned NumArgs = TheCall->getNumArgs(); 1157 1158 if (NumArgs < 4) { 1159 S.Diag(TheCall->getBeginLoc(), 1160 diag::err_typecheck_call_too_few_args_at_least) 1161 << 0 << 4 << NumArgs; 1162 return true; 1163 } 1164 1165 Expr *Arg0 = TheCall->getArg(0); 1166 Expr *Arg1 = TheCall->getArg(1); 1167 Expr *Arg2 = TheCall->getArg(2); 1168 Expr *Arg3 = TheCall->getArg(3); 1169 1170 // First argument always needs to be a queue_t type. 1171 if (!Arg0->getType()->isQueueT()) { 1172 S.Diag(TheCall->getArg(0)->getBeginLoc(), 1173 diag::err_opencl_builtin_expected_type) 1174 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 1175 return true; 1176 } 1177 1178 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 1179 if (!Arg1->getType()->isIntegerType()) { 1180 S.Diag(TheCall->getArg(1)->getBeginLoc(), 1181 diag::err_opencl_builtin_expected_type) 1182 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 1183 return true; 1184 } 1185 1186 // Third argument is always an ndrange_t type. 1187 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 1188 S.Diag(TheCall->getArg(2)->getBeginLoc(), 1189 diag::err_opencl_builtin_expected_type) 1190 << TheCall->getDirectCallee() << "'ndrange_t'"; 1191 return true; 1192 } 1193 1194 // With four arguments, there is only one form that the function could be 1195 // called in: no events and no variable arguments. 1196 if (NumArgs == 4) { 1197 // check that the last argument is the right block type. 1198 if (!isBlockPointer(Arg3)) { 1199 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1200 << TheCall->getDirectCallee() << "block"; 1201 return true; 1202 } 1203 // we have a block type, check the prototype 1204 const BlockPointerType *BPT = 1205 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1206 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1207 S.Diag(Arg3->getBeginLoc(), 1208 diag::err_opencl_enqueue_kernel_blocks_no_args); 1209 return true; 1210 } 1211 return false; 1212 } 1213 // we can have block + varargs. 1214 if (isBlockPointer(Arg3)) 1215 return (checkOpenCLBlockArgs(S, Arg3) || 1216 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1217 // last two cases with either exactly 7 args or 7 args and varargs. 1218 if (NumArgs >= 7) { 1219 // check common block argument. 1220 Expr *Arg6 = TheCall->getArg(6); 1221 if (!isBlockPointer(Arg6)) { 1222 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1223 << TheCall->getDirectCallee() << "block"; 1224 return true; 1225 } 1226 if (checkOpenCLBlockArgs(S, Arg6)) 1227 return true; 1228 1229 // Forth argument has to be any integer type. 1230 if (!Arg3->getType()->isIntegerType()) { 1231 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1232 diag::err_opencl_builtin_expected_type) 1233 << TheCall->getDirectCallee() << "integer"; 1234 return true; 1235 } 1236 // check remaining common arguments. 1237 Expr *Arg4 = TheCall->getArg(4); 1238 Expr *Arg5 = TheCall->getArg(5); 1239 1240 // Fifth argument is always passed as a pointer to clk_event_t. 1241 if (!Arg4->isNullPointerConstant(S.Context, 1242 Expr::NPC_ValueDependentIsNotNull) && 1243 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1244 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1245 diag::err_opencl_builtin_expected_type) 1246 << TheCall->getDirectCallee() 1247 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1248 return true; 1249 } 1250 1251 // Sixth argument is always passed as a pointer to clk_event_t. 1252 if (!Arg5->isNullPointerConstant(S.Context, 1253 Expr::NPC_ValueDependentIsNotNull) && 1254 !(Arg5->getType()->isPointerType() && 1255 Arg5->getType()->getPointeeType()->isClkEventT())) { 1256 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1257 diag::err_opencl_builtin_expected_type) 1258 << TheCall->getDirectCallee() 1259 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1260 return true; 1261 } 1262 1263 if (NumArgs == 7) 1264 return false; 1265 1266 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1267 } 1268 1269 // None of the specific case has been detected, give generic error 1270 S.Diag(TheCall->getBeginLoc(), 1271 diag::err_opencl_enqueue_kernel_incorrect_args); 1272 return true; 1273 } 1274 1275 /// Returns OpenCL access qual. 1276 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1277 return D->getAttr<OpenCLAccessAttr>(); 1278 } 1279 1280 /// Returns true if pipe element type is different from the pointer. 1281 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1282 const Expr *Arg0 = Call->getArg(0); 1283 // First argument type should always be pipe. 1284 if (!Arg0->getType()->isPipeType()) { 1285 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1286 << Call->getDirectCallee() << Arg0->getSourceRange(); 1287 return true; 1288 } 1289 OpenCLAccessAttr *AccessQual = 1290 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1291 // Validates the access qualifier is compatible with the call. 1292 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1293 // read_only and write_only, and assumed to be read_only if no qualifier is 1294 // specified. 1295 switch (Call->getDirectCallee()->getBuiltinID()) { 1296 case Builtin::BIread_pipe: 1297 case Builtin::BIreserve_read_pipe: 1298 case Builtin::BIcommit_read_pipe: 1299 case Builtin::BIwork_group_reserve_read_pipe: 1300 case Builtin::BIsub_group_reserve_read_pipe: 1301 case Builtin::BIwork_group_commit_read_pipe: 1302 case Builtin::BIsub_group_commit_read_pipe: 1303 if (!(!AccessQual || AccessQual->isReadOnly())) { 1304 S.Diag(Arg0->getBeginLoc(), 1305 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1306 << "read_only" << Arg0->getSourceRange(); 1307 return true; 1308 } 1309 break; 1310 case Builtin::BIwrite_pipe: 1311 case Builtin::BIreserve_write_pipe: 1312 case Builtin::BIcommit_write_pipe: 1313 case Builtin::BIwork_group_reserve_write_pipe: 1314 case Builtin::BIsub_group_reserve_write_pipe: 1315 case Builtin::BIwork_group_commit_write_pipe: 1316 case Builtin::BIsub_group_commit_write_pipe: 1317 if (!(AccessQual && AccessQual->isWriteOnly())) { 1318 S.Diag(Arg0->getBeginLoc(), 1319 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1320 << "write_only" << Arg0->getSourceRange(); 1321 return true; 1322 } 1323 break; 1324 default: 1325 break; 1326 } 1327 return false; 1328 } 1329 1330 /// Returns true if pipe element type is different from the pointer. 1331 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1332 const Expr *Arg0 = Call->getArg(0); 1333 const Expr *ArgIdx = Call->getArg(Idx); 1334 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1335 const QualType EltTy = PipeTy->getElementType(); 1336 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1337 // The Idx argument should be a pointer and the type of the pointer and 1338 // the type of pipe element should also be the same. 1339 if (!ArgTy || 1340 !S.Context.hasSameType( 1341 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1342 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1343 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1344 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1345 return true; 1346 } 1347 return false; 1348 } 1349 1350 // Performs semantic analysis for the read/write_pipe call. 1351 // \param S Reference to the semantic analyzer. 1352 // \param Call A pointer to the builtin call. 1353 // \return True if a semantic error has been found, false otherwise. 1354 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1355 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1356 // functions have two forms. 1357 switch (Call->getNumArgs()) { 1358 case 2: 1359 if (checkOpenCLPipeArg(S, Call)) 1360 return true; 1361 // The call with 2 arguments should be 1362 // read/write_pipe(pipe T, T*). 1363 // Check packet type T. 1364 if (checkOpenCLPipePacketType(S, Call, 1)) 1365 return true; 1366 break; 1367 1368 case 4: { 1369 if (checkOpenCLPipeArg(S, Call)) 1370 return true; 1371 // The call with 4 arguments should be 1372 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1373 // Check reserve_id_t. 1374 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1375 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1376 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1377 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1378 return true; 1379 } 1380 1381 // Check the index. 1382 const Expr *Arg2 = Call->getArg(2); 1383 if (!Arg2->getType()->isIntegerType() && 1384 !Arg2->getType()->isUnsignedIntegerType()) { 1385 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1386 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1387 << Arg2->getType() << Arg2->getSourceRange(); 1388 return true; 1389 } 1390 1391 // Check packet type T. 1392 if (checkOpenCLPipePacketType(S, Call, 3)) 1393 return true; 1394 } break; 1395 default: 1396 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1397 << Call->getDirectCallee() << Call->getSourceRange(); 1398 return true; 1399 } 1400 1401 return false; 1402 } 1403 1404 // Performs a semantic analysis on the {work_group_/sub_group_ 1405 // /_}reserve_{read/write}_pipe 1406 // \param S Reference to the semantic analyzer. 1407 // \param Call The call to the builtin function to be analyzed. 1408 // \return True if a semantic error was found, false otherwise. 1409 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1410 if (checkArgCount(S, Call, 2)) 1411 return true; 1412 1413 if (checkOpenCLPipeArg(S, Call)) 1414 return true; 1415 1416 // Check the reserve size. 1417 if (!Call->getArg(1)->getType()->isIntegerType() && 1418 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1419 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1420 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1421 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1422 return true; 1423 } 1424 1425 // Since return type of reserve_read/write_pipe built-in function is 1426 // reserve_id_t, which is not defined in the builtin def file , we used int 1427 // as return type and need to override the return type of these functions. 1428 Call->setType(S.Context.OCLReserveIDTy); 1429 1430 return false; 1431 } 1432 1433 // Performs a semantic analysis on {work_group_/sub_group_ 1434 // /_}commit_{read/write}_pipe 1435 // \param S Reference to the semantic analyzer. 1436 // \param Call The call to the builtin function to be analyzed. 1437 // \return True if a semantic error was found, false otherwise. 1438 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1439 if (checkArgCount(S, Call, 2)) 1440 return true; 1441 1442 if (checkOpenCLPipeArg(S, Call)) 1443 return true; 1444 1445 // Check reserve_id_t. 1446 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1447 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1448 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1449 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1450 return true; 1451 } 1452 1453 return false; 1454 } 1455 1456 // Performs a semantic analysis on the call to built-in Pipe 1457 // Query Functions. 1458 // \param S Reference to the semantic analyzer. 1459 // \param Call The call to the builtin function to be analyzed. 1460 // \return True if a semantic error was found, false otherwise. 1461 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1462 if (checkArgCount(S, Call, 1)) 1463 return true; 1464 1465 if (!Call->getArg(0)->getType()->isPipeType()) { 1466 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1467 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1468 return true; 1469 } 1470 1471 return false; 1472 } 1473 1474 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1475 // Performs semantic analysis for the to_global/local/private call. 1476 // \param S Reference to the semantic analyzer. 1477 // \param BuiltinID ID of the builtin function. 1478 // \param Call A pointer to the builtin call. 1479 // \return True if a semantic error has been found, false otherwise. 1480 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1481 CallExpr *Call) { 1482 if (checkArgCount(S, Call, 1)) 1483 return true; 1484 1485 auto RT = Call->getArg(0)->getType(); 1486 if (!RT->isPointerType() || RT->getPointeeType() 1487 .getAddressSpace() == LangAS::opencl_constant) { 1488 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1489 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1490 return true; 1491 } 1492 1493 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1494 S.Diag(Call->getArg(0)->getBeginLoc(), 1495 diag::warn_opencl_generic_address_space_arg) 1496 << Call->getDirectCallee()->getNameInfo().getAsString() 1497 << Call->getArg(0)->getSourceRange(); 1498 } 1499 1500 RT = RT->getPointeeType(); 1501 auto Qual = RT.getQualifiers(); 1502 switch (BuiltinID) { 1503 case Builtin::BIto_global: 1504 Qual.setAddressSpace(LangAS::opencl_global); 1505 break; 1506 case Builtin::BIto_local: 1507 Qual.setAddressSpace(LangAS::opencl_local); 1508 break; 1509 case Builtin::BIto_private: 1510 Qual.setAddressSpace(LangAS::opencl_private); 1511 break; 1512 default: 1513 llvm_unreachable("Invalid builtin function"); 1514 } 1515 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1516 RT.getUnqualifiedType(), Qual))); 1517 1518 return false; 1519 } 1520 1521 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1522 if (checkArgCount(S, TheCall, 1)) 1523 return ExprError(); 1524 1525 // Compute __builtin_launder's parameter type from the argument. 1526 // The parameter type is: 1527 // * The type of the argument if it's not an array or function type, 1528 // Otherwise, 1529 // * The decayed argument type. 1530 QualType ParamTy = [&]() { 1531 QualType ArgTy = TheCall->getArg(0)->getType(); 1532 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1533 return S.Context.getPointerType(Ty->getElementType()); 1534 if (ArgTy->isFunctionType()) { 1535 return S.Context.getPointerType(ArgTy); 1536 } 1537 return ArgTy; 1538 }(); 1539 1540 TheCall->setType(ParamTy); 1541 1542 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1543 if (!ParamTy->isPointerType()) 1544 return 0; 1545 if (ParamTy->isFunctionPointerType()) 1546 return 1; 1547 if (ParamTy->isVoidPointerType()) 1548 return 2; 1549 return llvm::Optional<unsigned>{}; 1550 }(); 1551 if (DiagSelect.hasValue()) { 1552 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1553 << DiagSelect.getValue() << TheCall->getSourceRange(); 1554 return ExprError(); 1555 } 1556 1557 // We either have an incomplete class type, or we have a class template 1558 // whose instantiation has not been forced. Example: 1559 // 1560 // template <class T> struct Foo { T value; }; 1561 // Foo<int> *p = nullptr; 1562 // auto *d = __builtin_launder(p); 1563 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1564 diag::err_incomplete_type)) 1565 return ExprError(); 1566 1567 assert(ParamTy->getPointeeType()->isObjectType() && 1568 "Unhandled non-object pointer case"); 1569 1570 InitializedEntity Entity = 1571 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1572 ExprResult Arg = 1573 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1574 if (Arg.isInvalid()) 1575 return ExprError(); 1576 TheCall->setArg(0, Arg.get()); 1577 1578 return TheCall; 1579 } 1580 1581 // Emit an error and return true if the current architecture is not in the list 1582 // of supported architectures. 1583 static bool 1584 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1585 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1586 llvm::Triple::ArchType CurArch = 1587 S.getASTContext().getTargetInfo().getTriple().getArch(); 1588 if (llvm::is_contained(SupportedArchs, CurArch)) 1589 return false; 1590 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1591 << TheCall->getSourceRange(); 1592 return true; 1593 } 1594 1595 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1596 SourceLocation CallSiteLoc); 1597 1598 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1599 CallExpr *TheCall) { 1600 switch (TI.getTriple().getArch()) { 1601 default: 1602 // Some builtins don't require additional checking, so just consider these 1603 // acceptable. 1604 return false; 1605 case llvm::Triple::arm: 1606 case llvm::Triple::armeb: 1607 case llvm::Triple::thumb: 1608 case llvm::Triple::thumbeb: 1609 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1610 case llvm::Triple::aarch64: 1611 case llvm::Triple::aarch64_32: 1612 case llvm::Triple::aarch64_be: 1613 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1614 case llvm::Triple::bpfeb: 1615 case llvm::Triple::bpfel: 1616 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1617 case llvm::Triple::hexagon: 1618 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1619 case llvm::Triple::mips: 1620 case llvm::Triple::mipsel: 1621 case llvm::Triple::mips64: 1622 case llvm::Triple::mips64el: 1623 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1624 case llvm::Triple::systemz: 1625 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1626 case llvm::Triple::x86: 1627 case llvm::Triple::x86_64: 1628 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1629 case llvm::Triple::ppc: 1630 case llvm::Triple::ppcle: 1631 case llvm::Triple::ppc64: 1632 case llvm::Triple::ppc64le: 1633 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1634 case llvm::Triple::amdgcn: 1635 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1636 case llvm::Triple::riscv32: 1637 case llvm::Triple::riscv64: 1638 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1639 } 1640 } 1641 1642 ExprResult 1643 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1644 CallExpr *TheCall) { 1645 ExprResult TheCallResult(TheCall); 1646 1647 // Find out if any arguments are required to be integer constant expressions. 1648 unsigned ICEArguments = 0; 1649 ASTContext::GetBuiltinTypeError Error; 1650 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1651 if (Error != ASTContext::GE_None) 1652 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1653 1654 // If any arguments are required to be ICE's, check and diagnose. 1655 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1656 // Skip arguments not required to be ICE's. 1657 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1658 1659 llvm::APSInt Result; 1660 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1661 return true; 1662 ICEArguments &= ~(1 << ArgNo); 1663 } 1664 1665 switch (BuiltinID) { 1666 case Builtin::BI__builtin___CFStringMakeConstantString: 1667 assert(TheCall->getNumArgs() == 1 && 1668 "Wrong # arguments to builtin CFStringMakeConstantString"); 1669 if (CheckObjCString(TheCall->getArg(0))) 1670 return ExprError(); 1671 break; 1672 case Builtin::BI__builtin_ms_va_start: 1673 case Builtin::BI__builtin_stdarg_start: 1674 case Builtin::BI__builtin_va_start: 1675 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1676 return ExprError(); 1677 break; 1678 case Builtin::BI__va_start: { 1679 switch (Context.getTargetInfo().getTriple().getArch()) { 1680 case llvm::Triple::aarch64: 1681 case llvm::Triple::arm: 1682 case llvm::Triple::thumb: 1683 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1684 return ExprError(); 1685 break; 1686 default: 1687 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1688 return ExprError(); 1689 break; 1690 } 1691 break; 1692 } 1693 1694 // The acquire, release, and no fence variants are ARM and AArch64 only. 1695 case Builtin::BI_interlockedbittestandset_acq: 1696 case Builtin::BI_interlockedbittestandset_rel: 1697 case Builtin::BI_interlockedbittestandset_nf: 1698 case Builtin::BI_interlockedbittestandreset_acq: 1699 case Builtin::BI_interlockedbittestandreset_rel: 1700 case Builtin::BI_interlockedbittestandreset_nf: 1701 if (CheckBuiltinTargetSupport( 1702 *this, BuiltinID, TheCall, 1703 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1704 return ExprError(); 1705 break; 1706 1707 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1708 case Builtin::BI_bittest64: 1709 case Builtin::BI_bittestandcomplement64: 1710 case Builtin::BI_bittestandreset64: 1711 case Builtin::BI_bittestandset64: 1712 case Builtin::BI_interlockedbittestandreset64: 1713 case Builtin::BI_interlockedbittestandset64: 1714 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1715 {llvm::Triple::x86_64, llvm::Triple::arm, 1716 llvm::Triple::thumb, llvm::Triple::aarch64})) 1717 return ExprError(); 1718 break; 1719 1720 case Builtin::BI__builtin_isgreater: 1721 case Builtin::BI__builtin_isgreaterequal: 1722 case Builtin::BI__builtin_isless: 1723 case Builtin::BI__builtin_islessequal: 1724 case Builtin::BI__builtin_islessgreater: 1725 case Builtin::BI__builtin_isunordered: 1726 if (SemaBuiltinUnorderedCompare(TheCall)) 1727 return ExprError(); 1728 break; 1729 case Builtin::BI__builtin_fpclassify: 1730 if (SemaBuiltinFPClassification(TheCall, 6)) 1731 return ExprError(); 1732 break; 1733 case Builtin::BI__builtin_isfinite: 1734 case Builtin::BI__builtin_isinf: 1735 case Builtin::BI__builtin_isinf_sign: 1736 case Builtin::BI__builtin_isnan: 1737 case Builtin::BI__builtin_isnormal: 1738 case Builtin::BI__builtin_signbit: 1739 case Builtin::BI__builtin_signbitf: 1740 case Builtin::BI__builtin_signbitl: 1741 if (SemaBuiltinFPClassification(TheCall, 1)) 1742 return ExprError(); 1743 break; 1744 case Builtin::BI__builtin_shufflevector: 1745 return SemaBuiltinShuffleVector(TheCall); 1746 // TheCall will be freed by the smart pointer here, but that's fine, since 1747 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1748 case Builtin::BI__builtin_prefetch: 1749 if (SemaBuiltinPrefetch(TheCall)) 1750 return ExprError(); 1751 break; 1752 case Builtin::BI__builtin_alloca_with_align: 1753 case Builtin::BI__builtin_alloca_with_align_uninitialized: 1754 if (SemaBuiltinAllocaWithAlign(TheCall)) 1755 return ExprError(); 1756 LLVM_FALLTHROUGH; 1757 case Builtin::BI__builtin_alloca: 1758 case Builtin::BI__builtin_alloca_uninitialized: 1759 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1760 << TheCall->getDirectCallee(); 1761 break; 1762 case Builtin::BI__arithmetic_fence: 1763 if (SemaBuiltinArithmeticFence(TheCall)) 1764 return ExprError(); 1765 break; 1766 case Builtin::BI__assume: 1767 case Builtin::BI__builtin_assume: 1768 if (SemaBuiltinAssume(TheCall)) 1769 return ExprError(); 1770 break; 1771 case Builtin::BI__builtin_assume_aligned: 1772 if (SemaBuiltinAssumeAligned(TheCall)) 1773 return ExprError(); 1774 break; 1775 case Builtin::BI__builtin_dynamic_object_size: 1776 case Builtin::BI__builtin_object_size: 1777 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1778 return ExprError(); 1779 break; 1780 case Builtin::BI__builtin_longjmp: 1781 if (SemaBuiltinLongjmp(TheCall)) 1782 return ExprError(); 1783 break; 1784 case Builtin::BI__builtin_setjmp: 1785 if (SemaBuiltinSetjmp(TheCall)) 1786 return ExprError(); 1787 break; 1788 case Builtin::BI__builtin_classify_type: 1789 if (checkArgCount(*this, TheCall, 1)) return true; 1790 TheCall->setType(Context.IntTy); 1791 break; 1792 case Builtin::BI__builtin_complex: 1793 if (SemaBuiltinComplex(TheCall)) 1794 return ExprError(); 1795 break; 1796 case Builtin::BI__builtin_constant_p: { 1797 if (checkArgCount(*this, TheCall, 1)) return true; 1798 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1799 if (Arg.isInvalid()) return true; 1800 TheCall->setArg(0, Arg.get()); 1801 TheCall->setType(Context.IntTy); 1802 break; 1803 } 1804 case Builtin::BI__builtin_launder: 1805 return SemaBuiltinLaunder(*this, TheCall); 1806 case Builtin::BI__sync_fetch_and_add: 1807 case Builtin::BI__sync_fetch_and_add_1: 1808 case Builtin::BI__sync_fetch_and_add_2: 1809 case Builtin::BI__sync_fetch_and_add_4: 1810 case Builtin::BI__sync_fetch_and_add_8: 1811 case Builtin::BI__sync_fetch_and_add_16: 1812 case Builtin::BI__sync_fetch_and_sub: 1813 case Builtin::BI__sync_fetch_and_sub_1: 1814 case Builtin::BI__sync_fetch_and_sub_2: 1815 case Builtin::BI__sync_fetch_and_sub_4: 1816 case Builtin::BI__sync_fetch_and_sub_8: 1817 case Builtin::BI__sync_fetch_and_sub_16: 1818 case Builtin::BI__sync_fetch_and_or: 1819 case Builtin::BI__sync_fetch_and_or_1: 1820 case Builtin::BI__sync_fetch_and_or_2: 1821 case Builtin::BI__sync_fetch_and_or_4: 1822 case Builtin::BI__sync_fetch_and_or_8: 1823 case Builtin::BI__sync_fetch_and_or_16: 1824 case Builtin::BI__sync_fetch_and_and: 1825 case Builtin::BI__sync_fetch_and_and_1: 1826 case Builtin::BI__sync_fetch_and_and_2: 1827 case Builtin::BI__sync_fetch_and_and_4: 1828 case Builtin::BI__sync_fetch_and_and_8: 1829 case Builtin::BI__sync_fetch_and_and_16: 1830 case Builtin::BI__sync_fetch_and_xor: 1831 case Builtin::BI__sync_fetch_and_xor_1: 1832 case Builtin::BI__sync_fetch_and_xor_2: 1833 case Builtin::BI__sync_fetch_and_xor_4: 1834 case Builtin::BI__sync_fetch_and_xor_8: 1835 case Builtin::BI__sync_fetch_and_xor_16: 1836 case Builtin::BI__sync_fetch_and_nand: 1837 case Builtin::BI__sync_fetch_and_nand_1: 1838 case Builtin::BI__sync_fetch_and_nand_2: 1839 case Builtin::BI__sync_fetch_and_nand_4: 1840 case Builtin::BI__sync_fetch_and_nand_8: 1841 case Builtin::BI__sync_fetch_and_nand_16: 1842 case Builtin::BI__sync_add_and_fetch: 1843 case Builtin::BI__sync_add_and_fetch_1: 1844 case Builtin::BI__sync_add_and_fetch_2: 1845 case Builtin::BI__sync_add_and_fetch_4: 1846 case Builtin::BI__sync_add_and_fetch_8: 1847 case Builtin::BI__sync_add_and_fetch_16: 1848 case Builtin::BI__sync_sub_and_fetch: 1849 case Builtin::BI__sync_sub_and_fetch_1: 1850 case Builtin::BI__sync_sub_and_fetch_2: 1851 case Builtin::BI__sync_sub_and_fetch_4: 1852 case Builtin::BI__sync_sub_and_fetch_8: 1853 case Builtin::BI__sync_sub_and_fetch_16: 1854 case Builtin::BI__sync_and_and_fetch: 1855 case Builtin::BI__sync_and_and_fetch_1: 1856 case Builtin::BI__sync_and_and_fetch_2: 1857 case Builtin::BI__sync_and_and_fetch_4: 1858 case Builtin::BI__sync_and_and_fetch_8: 1859 case Builtin::BI__sync_and_and_fetch_16: 1860 case Builtin::BI__sync_or_and_fetch: 1861 case Builtin::BI__sync_or_and_fetch_1: 1862 case Builtin::BI__sync_or_and_fetch_2: 1863 case Builtin::BI__sync_or_and_fetch_4: 1864 case Builtin::BI__sync_or_and_fetch_8: 1865 case Builtin::BI__sync_or_and_fetch_16: 1866 case Builtin::BI__sync_xor_and_fetch: 1867 case Builtin::BI__sync_xor_and_fetch_1: 1868 case Builtin::BI__sync_xor_and_fetch_2: 1869 case Builtin::BI__sync_xor_and_fetch_4: 1870 case Builtin::BI__sync_xor_and_fetch_8: 1871 case Builtin::BI__sync_xor_and_fetch_16: 1872 case Builtin::BI__sync_nand_and_fetch: 1873 case Builtin::BI__sync_nand_and_fetch_1: 1874 case Builtin::BI__sync_nand_and_fetch_2: 1875 case Builtin::BI__sync_nand_and_fetch_4: 1876 case Builtin::BI__sync_nand_and_fetch_8: 1877 case Builtin::BI__sync_nand_and_fetch_16: 1878 case Builtin::BI__sync_val_compare_and_swap: 1879 case Builtin::BI__sync_val_compare_and_swap_1: 1880 case Builtin::BI__sync_val_compare_and_swap_2: 1881 case Builtin::BI__sync_val_compare_and_swap_4: 1882 case Builtin::BI__sync_val_compare_and_swap_8: 1883 case Builtin::BI__sync_val_compare_and_swap_16: 1884 case Builtin::BI__sync_bool_compare_and_swap: 1885 case Builtin::BI__sync_bool_compare_and_swap_1: 1886 case Builtin::BI__sync_bool_compare_and_swap_2: 1887 case Builtin::BI__sync_bool_compare_and_swap_4: 1888 case Builtin::BI__sync_bool_compare_and_swap_8: 1889 case Builtin::BI__sync_bool_compare_and_swap_16: 1890 case Builtin::BI__sync_lock_test_and_set: 1891 case Builtin::BI__sync_lock_test_and_set_1: 1892 case Builtin::BI__sync_lock_test_and_set_2: 1893 case Builtin::BI__sync_lock_test_and_set_4: 1894 case Builtin::BI__sync_lock_test_and_set_8: 1895 case Builtin::BI__sync_lock_test_and_set_16: 1896 case Builtin::BI__sync_lock_release: 1897 case Builtin::BI__sync_lock_release_1: 1898 case Builtin::BI__sync_lock_release_2: 1899 case Builtin::BI__sync_lock_release_4: 1900 case Builtin::BI__sync_lock_release_8: 1901 case Builtin::BI__sync_lock_release_16: 1902 case Builtin::BI__sync_swap: 1903 case Builtin::BI__sync_swap_1: 1904 case Builtin::BI__sync_swap_2: 1905 case Builtin::BI__sync_swap_4: 1906 case Builtin::BI__sync_swap_8: 1907 case Builtin::BI__sync_swap_16: 1908 return SemaBuiltinAtomicOverloaded(TheCallResult); 1909 case Builtin::BI__sync_synchronize: 1910 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1911 << TheCall->getCallee()->getSourceRange(); 1912 break; 1913 case Builtin::BI__builtin_nontemporal_load: 1914 case Builtin::BI__builtin_nontemporal_store: 1915 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1916 case Builtin::BI__builtin_memcpy_inline: { 1917 clang::Expr *SizeOp = TheCall->getArg(2); 1918 // We warn about copying to or from `nullptr` pointers when `size` is 1919 // greater than 0. When `size` is value dependent we cannot evaluate its 1920 // value so we bail out. 1921 if (SizeOp->isValueDependent()) 1922 break; 1923 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) { 1924 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1925 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1926 } 1927 break; 1928 } 1929 #define BUILTIN(ID, TYPE, ATTRS) 1930 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1931 case Builtin::BI##ID: \ 1932 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1933 #include "clang/Basic/Builtins.def" 1934 case Builtin::BI__annotation: 1935 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1936 return ExprError(); 1937 break; 1938 case Builtin::BI__builtin_annotation: 1939 if (SemaBuiltinAnnotation(*this, TheCall)) 1940 return ExprError(); 1941 break; 1942 case Builtin::BI__builtin_addressof: 1943 if (SemaBuiltinAddressof(*this, TheCall)) 1944 return ExprError(); 1945 break; 1946 case Builtin::BI__builtin_function_start: 1947 if (SemaBuiltinFunctionStart(*this, TheCall)) 1948 return ExprError(); 1949 break; 1950 case Builtin::BI__builtin_is_aligned: 1951 case Builtin::BI__builtin_align_up: 1952 case Builtin::BI__builtin_align_down: 1953 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1954 return ExprError(); 1955 break; 1956 case Builtin::BI__builtin_add_overflow: 1957 case Builtin::BI__builtin_sub_overflow: 1958 case Builtin::BI__builtin_mul_overflow: 1959 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1960 return ExprError(); 1961 break; 1962 case Builtin::BI__builtin_operator_new: 1963 case Builtin::BI__builtin_operator_delete: { 1964 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1965 ExprResult Res = 1966 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1967 if (Res.isInvalid()) 1968 CorrectDelayedTyposInExpr(TheCallResult.get()); 1969 return Res; 1970 } 1971 case Builtin::BI__builtin_dump_struct: { 1972 // We first want to ensure we are called with 2 arguments 1973 if (checkArgCount(*this, TheCall, 2)) 1974 return ExprError(); 1975 // Ensure that the first argument is of type 'struct XX *' 1976 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1977 const QualType PtrArgType = PtrArg->getType(); 1978 if (!PtrArgType->isPointerType() || 1979 !PtrArgType->getPointeeType()->isRecordType()) { 1980 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1981 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1982 << "structure pointer"; 1983 return ExprError(); 1984 } 1985 1986 // Ensure that the second argument is of type 'FunctionType' 1987 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1988 const QualType FnPtrArgType = FnPtrArg->getType(); 1989 if (!FnPtrArgType->isPointerType()) { 1990 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1991 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1992 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1993 return ExprError(); 1994 } 1995 1996 const auto *FuncType = 1997 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1998 1999 if (!FuncType) { 2000 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 2001 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 2002 << FnPtrArgType << "'int (*)(const char *, ...)'"; 2003 return ExprError(); 2004 } 2005 2006 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 2007 if (!FT->getNumParams()) { 2008 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 2009 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 2010 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 2011 return ExprError(); 2012 } 2013 QualType PT = FT->getParamType(0); 2014 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 2015 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 2016 !PT->getPointeeType().isConstQualified()) { 2017 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 2018 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 2019 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 2020 return ExprError(); 2021 } 2022 } 2023 2024 TheCall->setType(Context.IntTy); 2025 break; 2026 } 2027 case Builtin::BI__builtin_expect_with_probability: { 2028 // We first want to ensure we are called with 3 arguments 2029 if (checkArgCount(*this, TheCall, 3)) 2030 return ExprError(); 2031 // then check probability is constant float in range [0.0, 1.0] 2032 const Expr *ProbArg = TheCall->getArg(2); 2033 SmallVector<PartialDiagnosticAt, 8> Notes; 2034 Expr::EvalResult Eval; 2035 Eval.Diag = &Notes; 2036 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 2037 !Eval.Val.isFloat()) { 2038 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 2039 << ProbArg->getSourceRange(); 2040 for (const PartialDiagnosticAt &PDiag : Notes) 2041 Diag(PDiag.first, PDiag.second); 2042 return ExprError(); 2043 } 2044 llvm::APFloat Probability = Eval.Val.getFloat(); 2045 bool LoseInfo = false; 2046 Probability.convert(llvm::APFloat::IEEEdouble(), 2047 llvm::RoundingMode::Dynamic, &LoseInfo); 2048 if (!(Probability >= llvm::APFloat(0.0) && 2049 Probability <= llvm::APFloat(1.0))) { 2050 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 2051 << ProbArg->getSourceRange(); 2052 return ExprError(); 2053 } 2054 break; 2055 } 2056 case Builtin::BI__builtin_preserve_access_index: 2057 if (SemaBuiltinPreserveAI(*this, TheCall)) 2058 return ExprError(); 2059 break; 2060 case Builtin::BI__builtin_call_with_static_chain: 2061 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 2062 return ExprError(); 2063 break; 2064 case Builtin::BI__exception_code: 2065 case Builtin::BI_exception_code: 2066 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 2067 diag::err_seh___except_block)) 2068 return ExprError(); 2069 break; 2070 case Builtin::BI__exception_info: 2071 case Builtin::BI_exception_info: 2072 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 2073 diag::err_seh___except_filter)) 2074 return ExprError(); 2075 break; 2076 case Builtin::BI__GetExceptionInfo: 2077 if (checkArgCount(*this, TheCall, 1)) 2078 return ExprError(); 2079 2080 if (CheckCXXThrowOperand( 2081 TheCall->getBeginLoc(), 2082 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 2083 TheCall)) 2084 return ExprError(); 2085 2086 TheCall->setType(Context.VoidPtrTy); 2087 break; 2088 // OpenCL v2.0, s6.13.16 - Pipe functions 2089 case Builtin::BIread_pipe: 2090 case Builtin::BIwrite_pipe: 2091 // Since those two functions are declared with var args, we need a semantic 2092 // check for the argument. 2093 if (SemaBuiltinRWPipe(*this, TheCall)) 2094 return ExprError(); 2095 break; 2096 case Builtin::BIreserve_read_pipe: 2097 case Builtin::BIreserve_write_pipe: 2098 case Builtin::BIwork_group_reserve_read_pipe: 2099 case Builtin::BIwork_group_reserve_write_pipe: 2100 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 2101 return ExprError(); 2102 break; 2103 case Builtin::BIsub_group_reserve_read_pipe: 2104 case Builtin::BIsub_group_reserve_write_pipe: 2105 if (checkOpenCLSubgroupExt(*this, TheCall) || 2106 SemaBuiltinReserveRWPipe(*this, TheCall)) 2107 return ExprError(); 2108 break; 2109 case Builtin::BIcommit_read_pipe: 2110 case Builtin::BIcommit_write_pipe: 2111 case Builtin::BIwork_group_commit_read_pipe: 2112 case Builtin::BIwork_group_commit_write_pipe: 2113 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 2114 return ExprError(); 2115 break; 2116 case Builtin::BIsub_group_commit_read_pipe: 2117 case Builtin::BIsub_group_commit_write_pipe: 2118 if (checkOpenCLSubgroupExt(*this, TheCall) || 2119 SemaBuiltinCommitRWPipe(*this, TheCall)) 2120 return ExprError(); 2121 break; 2122 case Builtin::BIget_pipe_num_packets: 2123 case Builtin::BIget_pipe_max_packets: 2124 if (SemaBuiltinPipePackets(*this, TheCall)) 2125 return ExprError(); 2126 break; 2127 case Builtin::BIto_global: 2128 case Builtin::BIto_local: 2129 case Builtin::BIto_private: 2130 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 2131 return ExprError(); 2132 break; 2133 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 2134 case Builtin::BIenqueue_kernel: 2135 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 2136 return ExprError(); 2137 break; 2138 case Builtin::BIget_kernel_work_group_size: 2139 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 2140 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 2141 return ExprError(); 2142 break; 2143 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 2144 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 2145 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 2146 return ExprError(); 2147 break; 2148 case Builtin::BI__builtin_os_log_format: 2149 Cleanup.setExprNeedsCleanups(true); 2150 LLVM_FALLTHROUGH; 2151 case Builtin::BI__builtin_os_log_format_buffer_size: 2152 if (SemaBuiltinOSLogFormat(TheCall)) 2153 return ExprError(); 2154 break; 2155 case Builtin::BI__builtin_frame_address: 2156 case Builtin::BI__builtin_return_address: { 2157 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 2158 return ExprError(); 2159 2160 // -Wframe-address warning if non-zero passed to builtin 2161 // return/frame address. 2162 Expr::EvalResult Result; 2163 if (!TheCall->getArg(0)->isValueDependent() && 2164 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 2165 Result.Val.getInt() != 0) 2166 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 2167 << ((BuiltinID == Builtin::BI__builtin_return_address) 2168 ? "__builtin_return_address" 2169 : "__builtin_frame_address") 2170 << TheCall->getSourceRange(); 2171 break; 2172 } 2173 2174 // __builtin_elementwise_abs restricts the element type to signed integers or 2175 // floating point types only. 2176 case Builtin::BI__builtin_elementwise_abs: { 2177 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall)) 2178 return ExprError(); 2179 2180 QualType ArgTy = TheCall->getArg(0)->getType(); 2181 QualType EltTy = ArgTy; 2182 2183 if (auto *VecTy = EltTy->getAs<VectorType>()) 2184 EltTy = VecTy->getElementType(); 2185 if (EltTy->isUnsignedIntegerType()) { 2186 Diag(TheCall->getArg(0)->getBeginLoc(), 2187 diag::err_builtin_invalid_arg_type) 2188 << 1 << /* signed integer or float ty*/ 3 << ArgTy; 2189 return ExprError(); 2190 } 2191 break; 2192 } 2193 2194 // These builtins restrict the element type to floating point 2195 // types only. 2196 case Builtin::BI__builtin_elementwise_ceil: 2197 case Builtin::BI__builtin_elementwise_floor: 2198 case Builtin::BI__builtin_elementwise_roundeven: 2199 case Builtin::BI__builtin_elementwise_trunc: { 2200 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall)) 2201 return ExprError(); 2202 2203 QualType ArgTy = TheCall->getArg(0)->getType(); 2204 QualType EltTy = ArgTy; 2205 2206 if (auto *VecTy = EltTy->getAs<VectorType>()) 2207 EltTy = VecTy->getElementType(); 2208 if (!EltTy->isFloatingType()) { 2209 Diag(TheCall->getArg(0)->getBeginLoc(), 2210 diag::err_builtin_invalid_arg_type) 2211 << 1 << /* float ty*/ 5 << ArgTy; 2212 2213 return ExprError(); 2214 } 2215 break; 2216 } 2217 2218 case Builtin::BI__builtin_elementwise_min: 2219 case Builtin::BI__builtin_elementwise_max: 2220 if (SemaBuiltinElementwiseMath(TheCall)) 2221 return ExprError(); 2222 break; 2223 case Builtin::BI__builtin_reduce_max: 2224 case Builtin::BI__builtin_reduce_min: { 2225 if (PrepareBuiltinReduceMathOneArgCall(TheCall)) 2226 return ExprError(); 2227 2228 const Expr *Arg = TheCall->getArg(0); 2229 const auto *TyA = Arg->getType()->getAs<VectorType>(); 2230 if (!TyA) { 2231 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2232 << 1 << /* vector ty*/ 4 << Arg->getType(); 2233 return ExprError(); 2234 } 2235 2236 TheCall->setType(TyA->getElementType()); 2237 break; 2238 } 2239 2240 // __builtin_reduce_xor supports vector of integers only. 2241 case Builtin::BI__builtin_reduce_xor: { 2242 if (PrepareBuiltinReduceMathOneArgCall(TheCall)) 2243 return ExprError(); 2244 2245 const Expr *Arg = TheCall->getArg(0); 2246 const auto *TyA = Arg->getType()->getAs<VectorType>(); 2247 if (!TyA || !TyA->getElementType()->isIntegerType()) { 2248 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2249 << 1 << /* vector of integers */ 6 << Arg->getType(); 2250 return ExprError(); 2251 } 2252 TheCall->setType(TyA->getElementType()); 2253 break; 2254 } 2255 2256 case Builtin::BI__builtin_matrix_transpose: 2257 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 2258 2259 case Builtin::BI__builtin_matrix_column_major_load: 2260 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 2261 2262 case Builtin::BI__builtin_matrix_column_major_store: 2263 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 2264 2265 case Builtin::BI__builtin_get_device_side_mangled_name: { 2266 auto Check = [](CallExpr *TheCall) { 2267 if (TheCall->getNumArgs() != 1) 2268 return false; 2269 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 2270 if (!DRE) 2271 return false; 2272 auto *D = DRE->getDecl(); 2273 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 2274 return false; 2275 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 2276 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 2277 }; 2278 if (!Check(TheCall)) { 2279 Diag(TheCall->getBeginLoc(), 2280 diag::err_hip_invalid_args_builtin_mangled_name); 2281 return ExprError(); 2282 } 2283 } 2284 } 2285 2286 // Since the target specific builtins for each arch overlap, only check those 2287 // of the arch we are compiling for. 2288 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 2289 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 2290 assert(Context.getAuxTargetInfo() && 2291 "Aux Target Builtin, but not an aux target?"); 2292 2293 if (CheckTSBuiltinFunctionCall( 2294 *Context.getAuxTargetInfo(), 2295 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2296 return ExprError(); 2297 } else { 2298 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2299 TheCall)) 2300 return ExprError(); 2301 } 2302 } 2303 2304 return TheCallResult; 2305 } 2306 2307 // Get the valid immediate range for the specified NEON type code. 2308 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2309 NeonTypeFlags Type(t); 2310 int IsQuad = ForceQuad ? true : Type.isQuad(); 2311 switch (Type.getEltType()) { 2312 case NeonTypeFlags::Int8: 2313 case NeonTypeFlags::Poly8: 2314 return shift ? 7 : (8 << IsQuad) - 1; 2315 case NeonTypeFlags::Int16: 2316 case NeonTypeFlags::Poly16: 2317 return shift ? 15 : (4 << IsQuad) - 1; 2318 case NeonTypeFlags::Int32: 2319 return shift ? 31 : (2 << IsQuad) - 1; 2320 case NeonTypeFlags::Int64: 2321 case NeonTypeFlags::Poly64: 2322 return shift ? 63 : (1 << IsQuad) - 1; 2323 case NeonTypeFlags::Poly128: 2324 return shift ? 127 : (1 << IsQuad) - 1; 2325 case NeonTypeFlags::Float16: 2326 assert(!shift && "cannot shift float types!"); 2327 return (4 << IsQuad) - 1; 2328 case NeonTypeFlags::Float32: 2329 assert(!shift && "cannot shift float types!"); 2330 return (2 << IsQuad) - 1; 2331 case NeonTypeFlags::Float64: 2332 assert(!shift && "cannot shift float types!"); 2333 return (1 << IsQuad) - 1; 2334 case NeonTypeFlags::BFloat16: 2335 assert(!shift && "cannot shift float types!"); 2336 return (4 << IsQuad) - 1; 2337 } 2338 llvm_unreachable("Invalid NeonTypeFlag!"); 2339 } 2340 2341 /// getNeonEltType - Return the QualType corresponding to the elements of 2342 /// the vector type specified by the NeonTypeFlags. This is used to check 2343 /// the pointer arguments for Neon load/store intrinsics. 2344 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2345 bool IsPolyUnsigned, bool IsInt64Long) { 2346 switch (Flags.getEltType()) { 2347 case NeonTypeFlags::Int8: 2348 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2349 case NeonTypeFlags::Int16: 2350 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2351 case NeonTypeFlags::Int32: 2352 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2353 case NeonTypeFlags::Int64: 2354 if (IsInt64Long) 2355 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2356 else 2357 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2358 : Context.LongLongTy; 2359 case NeonTypeFlags::Poly8: 2360 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2361 case NeonTypeFlags::Poly16: 2362 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2363 case NeonTypeFlags::Poly64: 2364 if (IsInt64Long) 2365 return Context.UnsignedLongTy; 2366 else 2367 return Context.UnsignedLongLongTy; 2368 case NeonTypeFlags::Poly128: 2369 break; 2370 case NeonTypeFlags::Float16: 2371 return Context.HalfTy; 2372 case NeonTypeFlags::Float32: 2373 return Context.FloatTy; 2374 case NeonTypeFlags::Float64: 2375 return Context.DoubleTy; 2376 case NeonTypeFlags::BFloat16: 2377 return Context.BFloat16Ty; 2378 } 2379 llvm_unreachable("Invalid NeonTypeFlag!"); 2380 } 2381 2382 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2383 // Range check SVE intrinsics that take immediate values. 2384 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2385 2386 switch (BuiltinID) { 2387 default: 2388 return false; 2389 #define GET_SVE_IMMEDIATE_CHECK 2390 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2391 #undef GET_SVE_IMMEDIATE_CHECK 2392 } 2393 2394 // Perform all the immediate checks for this builtin call. 2395 bool HasError = false; 2396 for (auto &I : ImmChecks) { 2397 int ArgNum, CheckTy, ElementSizeInBits; 2398 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2399 2400 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2401 2402 // Function that checks whether the operand (ArgNum) is an immediate 2403 // that is one of the predefined values. 2404 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2405 int ErrDiag) -> bool { 2406 // We can't check the value of a dependent argument. 2407 Expr *Arg = TheCall->getArg(ArgNum); 2408 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2409 return false; 2410 2411 // Check constant-ness first. 2412 llvm::APSInt Imm; 2413 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2414 return true; 2415 2416 if (!CheckImm(Imm.getSExtValue())) 2417 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2418 return false; 2419 }; 2420 2421 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2422 case SVETypeFlags::ImmCheck0_31: 2423 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2424 HasError = true; 2425 break; 2426 case SVETypeFlags::ImmCheck0_13: 2427 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2428 HasError = true; 2429 break; 2430 case SVETypeFlags::ImmCheck1_16: 2431 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2432 HasError = true; 2433 break; 2434 case SVETypeFlags::ImmCheck0_7: 2435 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2436 HasError = true; 2437 break; 2438 case SVETypeFlags::ImmCheckExtract: 2439 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2440 (2048 / ElementSizeInBits) - 1)) 2441 HasError = true; 2442 break; 2443 case SVETypeFlags::ImmCheckShiftRight: 2444 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2445 HasError = true; 2446 break; 2447 case SVETypeFlags::ImmCheckShiftRightNarrow: 2448 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2449 ElementSizeInBits / 2)) 2450 HasError = true; 2451 break; 2452 case SVETypeFlags::ImmCheckShiftLeft: 2453 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2454 ElementSizeInBits - 1)) 2455 HasError = true; 2456 break; 2457 case SVETypeFlags::ImmCheckLaneIndex: 2458 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2459 (128 / (1 * ElementSizeInBits)) - 1)) 2460 HasError = true; 2461 break; 2462 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2463 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2464 (128 / (2 * ElementSizeInBits)) - 1)) 2465 HasError = true; 2466 break; 2467 case SVETypeFlags::ImmCheckLaneIndexDot: 2468 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2469 (128 / (4 * ElementSizeInBits)) - 1)) 2470 HasError = true; 2471 break; 2472 case SVETypeFlags::ImmCheckComplexRot90_270: 2473 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2474 diag::err_rotation_argument_to_cadd)) 2475 HasError = true; 2476 break; 2477 case SVETypeFlags::ImmCheckComplexRotAll90: 2478 if (CheckImmediateInSet( 2479 [](int64_t V) { 2480 return V == 0 || V == 90 || V == 180 || V == 270; 2481 }, 2482 diag::err_rotation_argument_to_cmla)) 2483 HasError = true; 2484 break; 2485 case SVETypeFlags::ImmCheck0_1: 2486 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2487 HasError = true; 2488 break; 2489 case SVETypeFlags::ImmCheck0_2: 2490 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2491 HasError = true; 2492 break; 2493 case SVETypeFlags::ImmCheck0_3: 2494 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2495 HasError = true; 2496 break; 2497 } 2498 } 2499 2500 return HasError; 2501 } 2502 2503 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2504 unsigned BuiltinID, CallExpr *TheCall) { 2505 llvm::APSInt Result; 2506 uint64_t mask = 0; 2507 unsigned TV = 0; 2508 int PtrArgNum = -1; 2509 bool HasConstPtr = false; 2510 switch (BuiltinID) { 2511 #define GET_NEON_OVERLOAD_CHECK 2512 #include "clang/Basic/arm_neon.inc" 2513 #include "clang/Basic/arm_fp16.inc" 2514 #undef GET_NEON_OVERLOAD_CHECK 2515 } 2516 2517 // For NEON intrinsics which are overloaded on vector element type, validate 2518 // the immediate which specifies which variant to emit. 2519 unsigned ImmArg = TheCall->getNumArgs()-1; 2520 if (mask) { 2521 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2522 return true; 2523 2524 TV = Result.getLimitedValue(64); 2525 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2526 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2527 << TheCall->getArg(ImmArg)->getSourceRange(); 2528 } 2529 2530 if (PtrArgNum >= 0) { 2531 // Check that pointer arguments have the specified type. 2532 Expr *Arg = TheCall->getArg(PtrArgNum); 2533 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2534 Arg = ICE->getSubExpr(); 2535 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2536 QualType RHSTy = RHS.get()->getType(); 2537 2538 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2539 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2540 Arch == llvm::Triple::aarch64_32 || 2541 Arch == llvm::Triple::aarch64_be; 2542 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2543 QualType EltTy = 2544 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2545 if (HasConstPtr) 2546 EltTy = EltTy.withConst(); 2547 QualType LHSTy = Context.getPointerType(EltTy); 2548 AssignConvertType ConvTy; 2549 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2550 if (RHS.isInvalid()) 2551 return true; 2552 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2553 RHS.get(), AA_Assigning)) 2554 return true; 2555 } 2556 2557 // For NEON intrinsics which take an immediate value as part of the 2558 // instruction, range check them here. 2559 unsigned i = 0, l = 0, u = 0; 2560 switch (BuiltinID) { 2561 default: 2562 return false; 2563 #define GET_NEON_IMMEDIATE_CHECK 2564 #include "clang/Basic/arm_neon.inc" 2565 #include "clang/Basic/arm_fp16.inc" 2566 #undef GET_NEON_IMMEDIATE_CHECK 2567 } 2568 2569 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2570 } 2571 2572 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2573 switch (BuiltinID) { 2574 default: 2575 return false; 2576 #include "clang/Basic/arm_mve_builtin_sema.inc" 2577 } 2578 } 2579 2580 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2581 CallExpr *TheCall) { 2582 bool Err = false; 2583 switch (BuiltinID) { 2584 default: 2585 return false; 2586 #include "clang/Basic/arm_cde_builtin_sema.inc" 2587 } 2588 2589 if (Err) 2590 return true; 2591 2592 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2593 } 2594 2595 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2596 const Expr *CoprocArg, bool WantCDE) { 2597 if (isConstantEvaluated()) 2598 return false; 2599 2600 // We can't check the value of a dependent argument. 2601 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2602 return false; 2603 2604 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2605 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2606 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2607 2608 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2609 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2610 2611 if (IsCDECoproc != WantCDE) 2612 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2613 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2614 2615 return false; 2616 } 2617 2618 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2619 unsigned MaxWidth) { 2620 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2621 BuiltinID == ARM::BI__builtin_arm_ldaex || 2622 BuiltinID == ARM::BI__builtin_arm_strex || 2623 BuiltinID == ARM::BI__builtin_arm_stlex || 2624 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2625 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2626 BuiltinID == AArch64::BI__builtin_arm_strex || 2627 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2628 "unexpected ARM builtin"); 2629 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2630 BuiltinID == ARM::BI__builtin_arm_ldaex || 2631 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2632 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2633 2634 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2635 2636 // Ensure that we have the proper number of arguments. 2637 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2638 return true; 2639 2640 // Inspect the pointer argument of the atomic builtin. This should always be 2641 // a pointer type, whose element is an integral scalar or pointer type. 2642 // Because it is a pointer type, we don't have to worry about any implicit 2643 // casts here. 2644 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2645 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2646 if (PointerArgRes.isInvalid()) 2647 return true; 2648 PointerArg = PointerArgRes.get(); 2649 2650 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2651 if (!pointerType) { 2652 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2653 << PointerArg->getType() << PointerArg->getSourceRange(); 2654 return true; 2655 } 2656 2657 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2658 // task is to insert the appropriate casts into the AST. First work out just 2659 // what the appropriate type is. 2660 QualType ValType = pointerType->getPointeeType(); 2661 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2662 if (IsLdrex) 2663 AddrType.addConst(); 2664 2665 // Issue a warning if the cast is dodgy. 2666 CastKind CastNeeded = CK_NoOp; 2667 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2668 CastNeeded = CK_BitCast; 2669 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2670 << PointerArg->getType() << Context.getPointerType(AddrType) 2671 << AA_Passing << PointerArg->getSourceRange(); 2672 } 2673 2674 // Finally, do the cast and replace the argument with the corrected version. 2675 AddrType = Context.getPointerType(AddrType); 2676 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2677 if (PointerArgRes.isInvalid()) 2678 return true; 2679 PointerArg = PointerArgRes.get(); 2680 2681 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2682 2683 // In general, we allow ints, floats and pointers to be loaded and stored. 2684 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2685 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2686 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2687 << PointerArg->getType() << PointerArg->getSourceRange(); 2688 return true; 2689 } 2690 2691 // But ARM doesn't have instructions to deal with 128-bit versions. 2692 if (Context.getTypeSize(ValType) > MaxWidth) { 2693 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2694 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2695 << PointerArg->getType() << PointerArg->getSourceRange(); 2696 return true; 2697 } 2698 2699 switch (ValType.getObjCLifetime()) { 2700 case Qualifiers::OCL_None: 2701 case Qualifiers::OCL_ExplicitNone: 2702 // okay 2703 break; 2704 2705 case Qualifiers::OCL_Weak: 2706 case Qualifiers::OCL_Strong: 2707 case Qualifiers::OCL_Autoreleasing: 2708 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2709 << ValType << PointerArg->getSourceRange(); 2710 return true; 2711 } 2712 2713 if (IsLdrex) { 2714 TheCall->setType(ValType); 2715 return false; 2716 } 2717 2718 // Initialize the argument to be stored. 2719 ExprResult ValArg = TheCall->getArg(0); 2720 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2721 Context, ValType, /*consume*/ false); 2722 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2723 if (ValArg.isInvalid()) 2724 return true; 2725 TheCall->setArg(0, ValArg.get()); 2726 2727 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2728 // but the custom checker bypasses all default analysis. 2729 TheCall->setType(Context.IntTy); 2730 return false; 2731 } 2732 2733 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2734 CallExpr *TheCall) { 2735 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2736 BuiltinID == ARM::BI__builtin_arm_ldaex || 2737 BuiltinID == ARM::BI__builtin_arm_strex || 2738 BuiltinID == ARM::BI__builtin_arm_stlex) { 2739 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2740 } 2741 2742 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2743 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2744 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2745 } 2746 2747 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2748 BuiltinID == ARM::BI__builtin_arm_wsr64) 2749 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2750 2751 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2752 BuiltinID == ARM::BI__builtin_arm_rsrp || 2753 BuiltinID == ARM::BI__builtin_arm_wsr || 2754 BuiltinID == ARM::BI__builtin_arm_wsrp) 2755 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2756 2757 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2758 return true; 2759 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2760 return true; 2761 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2762 return true; 2763 2764 // For intrinsics which take an immediate value as part of the instruction, 2765 // range check them here. 2766 // FIXME: VFP Intrinsics should error if VFP not present. 2767 switch (BuiltinID) { 2768 default: return false; 2769 case ARM::BI__builtin_arm_ssat: 2770 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2771 case ARM::BI__builtin_arm_usat: 2772 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2773 case ARM::BI__builtin_arm_ssat16: 2774 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2775 case ARM::BI__builtin_arm_usat16: 2776 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2777 case ARM::BI__builtin_arm_vcvtr_f: 2778 case ARM::BI__builtin_arm_vcvtr_d: 2779 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2780 case ARM::BI__builtin_arm_dmb: 2781 case ARM::BI__builtin_arm_dsb: 2782 case ARM::BI__builtin_arm_isb: 2783 case ARM::BI__builtin_arm_dbg: 2784 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2785 case ARM::BI__builtin_arm_cdp: 2786 case ARM::BI__builtin_arm_cdp2: 2787 case ARM::BI__builtin_arm_mcr: 2788 case ARM::BI__builtin_arm_mcr2: 2789 case ARM::BI__builtin_arm_mrc: 2790 case ARM::BI__builtin_arm_mrc2: 2791 case ARM::BI__builtin_arm_mcrr: 2792 case ARM::BI__builtin_arm_mcrr2: 2793 case ARM::BI__builtin_arm_mrrc: 2794 case ARM::BI__builtin_arm_mrrc2: 2795 case ARM::BI__builtin_arm_ldc: 2796 case ARM::BI__builtin_arm_ldcl: 2797 case ARM::BI__builtin_arm_ldc2: 2798 case ARM::BI__builtin_arm_ldc2l: 2799 case ARM::BI__builtin_arm_stc: 2800 case ARM::BI__builtin_arm_stcl: 2801 case ARM::BI__builtin_arm_stc2: 2802 case ARM::BI__builtin_arm_stc2l: 2803 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2804 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2805 /*WantCDE*/ false); 2806 } 2807 } 2808 2809 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2810 unsigned BuiltinID, 2811 CallExpr *TheCall) { 2812 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2813 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2814 BuiltinID == AArch64::BI__builtin_arm_strex || 2815 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2816 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2817 } 2818 2819 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2820 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2821 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2822 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2823 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2824 } 2825 2826 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2827 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2828 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2829 2830 // Memory Tagging Extensions (MTE) Intrinsics 2831 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2832 BuiltinID == AArch64::BI__builtin_arm_addg || 2833 BuiltinID == AArch64::BI__builtin_arm_gmi || 2834 BuiltinID == AArch64::BI__builtin_arm_ldg || 2835 BuiltinID == AArch64::BI__builtin_arm_stg || 2836 BuiltinID == AArch64::BI__builtin_arm_subp) { 2837 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2838 } 2839 2840 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2841 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2842 BuiltinID == AArch64::BI__builtin_arm_wsr || 2843 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2844 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2845 2846 // Only check the valid encoding range. Any constant in this range would be 2847 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2848 // an exception for incorrect registers. This matches MSVC behavior. 2849 if (BuiltinID == AArch64::BI_ReadStatusReg || 2850 BuiltinID == AArch64::BI_WriteStatusReg) 2851 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2852 2853 if (BuiltinID == AArch64::BI__getReg) 2854 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2855 2856 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2857 return true; 2858 2859 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2860 return true; 2861 2862 // For intrinsics which take an immediate value as part of the instruction, 2863 // range check them here. 2864 unsigned i = 0, l = 0, u = 0; 2865 switch (BuiltinID) { 2866 default: return false; 2867 case AArch64::BI__builtin_arm_dmb: 2868 case AArch64::BI__builtin_arm_dsb: 2869 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2870 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2871 } 2872 2873 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2874 } 2875 2876 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2877 if (Arg->getType()->getAsPlaceholderType()) 2878 return false; 2879 2880 // The first argument needs to be a record field access. 2881 // If it is an array element access, we delay decision 2882 // to BPF backend to check whether the access is a 2883 // field access or not. 2884 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2885 isa<MemberExpr>(Arg->IgnoreParens()) || 2886 isa<ArraySubscriptExpr>(Arg->IgnoreParens())); 2887 } 2888 2889 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2890 QualType VectorTy, QualType EltTy) { 2891 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2892 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2893 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2894 << Call->getSourceRange() << VectorEltTy << EltTy; 2895 return false; 2896 } 2897 return true; 2898 } 2899 2900 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2901 QualType ArgType = Arg->getType(); 2902 if (ArgType->getAsPlaceholderType()) 2903 return false; 2904 2905 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2906 // format: 2907 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2908 // 2. <type> var; 2909 // __builtin_preserve_type_info(var, flag); 2910 if (!isa<DeclRefExpr>(Arg->IgnoreParens()) && 2911 !isa<UnaryOperator>(Arg->IgnoreParens())) 2912 return false; 2913 2914 // Typedef type. 2915 if (ArgType->getAs<TypedefType>()) 2916 return true; 2917 2918 // Record type or Enum type. 2919 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2920 if (const auto *RT = Ty->getAs<RecordType>()) { 2921 if (!RT->getDecl()->getDeclName().isEmpty()) 2922 return true; 2923 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2924 if (!ET->getDecl()->getDeclName().isEmpty()) 2925 return true; 2926 } 2927 2928 return false; 2929 } 2930 2931 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2932 QualType ArgType = Arg->getType(); 2933 if (ArgType->getAsPlaceholderType()) 2934 return false; 2935 2936 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2937 // format: 2938 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2939 // flag); 2940 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2941 if (!UO) 2942 return false; 2943 2944 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2945 if (!CE) 2946 return false; 2947 if (CE->getCastKind() != CK_IntegralToPointer && 2948 CE->getCastKind() != CK_NullToPointer) 2949 return false; 2950 2951 // The integer must be from an EnumConstantDecl. 2952 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2953 if (!DR) 2954 return false; 2955 2956 const EnumConstantDecl *Enumerator = 2957 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2958 if (!Enumerator) 2959 return false; 2960 2961 // The type must be EnumType. 2962 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2963 const auto *ET = Ty->getAs<EnumType>(); 2964 if (!ET) 2965 return false; 2966 2967 // The enum value must be supported. 2968 return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator); 2969 } 2970 2971 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2972 CallExpr *TheCall) { 2973 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2974 BuiltinID == BPF::BI__builtin_btf_type_id || 2975 BuiltinID == BPF::BI__builtin_preserve_type_info || 2976 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2977 "unexpected BPF builtin"); 2978 2979 if (checkArgCount(*this, TheCall, 2)) 2980 return true; 2981 2982 // The second argument needs to be a constant int 2983 Expr *Arg = TheCall->getArg(1); 2984 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2985 diag::kind kind; 2986 if (!Value) { 2987 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2988 kind = diag::err_preserve_field_info_not_const; 2989 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2990 kind = diag::err_btf_type_id_not_const; 2991 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2992 kind = diag::err_preserve_type_info_not_const; 2993 else 2994 kind = diag::err_preserve_enum_value_not_const; 2995 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2996 return true; 2997 } 2998 2999 // The first argument 3000 Arg = TheCall->getArg(0); 3001 bool InvalidArg = false; 3002 bool ReturnUnsignedInt = true; 3003 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 3004 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 3005 InvalidArg = true; 3006 kind = diag::err_preserve_field_info_not_field; 3007 } 3008 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 3009 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 3010 InvalidArg = true; 3011 kind = diag::err_preserve_type_info_invalid; 3012 } 3013 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 3014 if (!isValidBPFPreserveEnumValueArg(Arg)) { 3015 InvalidArg = true; 3016 kind = diag::err_preserve_enum_value_invalid; 3017 } 3018 ReturnUnsignedInt = false; 3019 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 3020 ReturnUnsignedInt = false; 3021 } 3022 3023 if (InvalidArg) { 3024 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 3025 return true; 3026 } 3027 3028 if (ReturnUnsignedInt) 3029 TheCall->setType(Context.UnsignedIntTy); 3030 else 3031 TheCall->setType(Context.UnsignedLongTy); 3032 return false; 3033 } 3034 3035 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3036 struct ArgInfo { 3037 uint8_t OpNum; 3038 bool IsSigned; 3039 uint8_t BitWidth; 3040 uint8_t Align; 3041 }; 3042 struct BuiltinInfo { 3043 unsigned BuiltinID; 3044 ArgInfo Infos[2]; 3045 }; 3046 3047 static BuiltinInfo Infos[] = { 3048 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 3049 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 3050 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 3051 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 3052 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 3053 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 3054 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 3055 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 3056 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 3057 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 3058 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 3059 3060 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 3061 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 3062 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 3063 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 3064 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 3065 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 3066 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 3067 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 3068 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 3069 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 3070 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 3071 3072 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 3073 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 3074 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 3075 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 3076 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 3077 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 3078 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 3079 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 3080 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 3081 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 3082 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 3083 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 3084 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 3085 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 3086 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 3087 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 3088 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 3089 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 3090 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 3091 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 3092 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 3093 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 3094 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 3095 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 3096 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 3097 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 3098 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 3099 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 3100 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 3101 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 3102 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 3103 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 3104 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 3105 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 3106 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 3107 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 3108 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 3109 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 3110 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 3111 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 3112 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 3113 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 3114 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 3115 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 3116 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 3117 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 3118 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 3119 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 3120 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 3121 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 3122 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 3123 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 3124 {{ 1, false, 6, 0 }} }, 3125 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 3126 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 3127 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 3128 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 3129 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 3130 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 3131 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 3132 {{ 1, false, 5, 0 }} }, 3133 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 3134 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 3135 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 3136 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 3137 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 3138 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 3139 { 2, false, 5, 0 }} }, 3140 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 3141 { 2, false, 6, 0 }} }, 3142 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 3143 { 3, false, 5, 0 }} }, 3144 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 3145 { 3, false, 6, 0 }} }, 3146 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 3147 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 3148 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 3149 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 3150 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 3151 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 3152 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 3153 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 3154 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 3155 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 3156 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 3157 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 3158 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 3159 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 3160 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 3161 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 3162 {{ 2, false, 4, 0 }, 3163 { 3, false, 5, 0 }} }, 3164 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 3165 {{ 2, false, 4, 0 }, 3166 { 3, false, 5, 0 }} }, 3167 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 3168 {{ 2, false, 4, 0 }, 3169 { 3, false, 5, 0 }} }, 3170 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 3171 {{ 2, false, 4, 0 }, 3172 { 3, false, 5, 0 }} }, 3173 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 3174 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 3175 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 3176 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 3177 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 3178 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 3179 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 3180 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 3181 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 3182 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 3183 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 3184 { 2, false, 5, 0 }} }, 3185 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 3186 { 2, false, 6, 0 }} }, 3187 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 3188 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 3189 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 3190 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 3191 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 3192 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 3193 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 3194 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 3195 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 3196 {{ 1, false, 4, 0 }} }, 3197 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 3198 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 3199 {{ 1, false, 4, 0 }} }, 3200 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 3201 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 3202 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 3203 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 3204 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 3205 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 3206 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 3207 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 3208 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 3209 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 3210 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 3211 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 3212 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 3213 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 3214 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 3215 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 3216 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 3217 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 3218 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 3219 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 3220 {{ 3, false, 1, 0 }} }, 3221 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 3222 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 3223 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 3224 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 3225 {{ 3, false, 1, 0 }} }, 3226 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 3227 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 3228 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 3229 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 3230 {{ 3, false, 1, 0 }} }, 3231 }; 3232 3233 // Use a dynamically initialized static to sort the table exactly once on 3234 // first run. 3235 static const bool SortOnce = 3236 (llvm::sort(Infos, 3237 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 3238 return LHS.BuiltinID < RHS.BuiltinID; 3239 }), 3240 true); 3241 (void)SortOnce; 3242 3243 const BuiltinInfo *F = llvm::partition_point( 3244 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 3245 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 3246 return false; 3247 3248 bool Error = false; 3249 3250 for (const ArgInfo &A : F->Infos) { 3251 // Ignore empty ArgInfo elements. 3252 if (A.BitWidth == 0) 3253 continue; 3254 3255 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 3256 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 3257 if (!A.Align) { 3258 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3259 } else { 3260 unsigned M = 1 << A.Align; 3261 Min *= M; 3262 Max *= M; 3263 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3264 Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 3265 } 3266 } 3267 return Error; 3268 } 3269 3270 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 3271 CallExpr *TheCall) { 3272 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 3273 } 3274 3275 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 3276 unsigned BuiltinID, CallExpr *TheCall) { 3277 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 3278 CheckMipsBuiltinArgument(BuiltinID, TheCall); 3279 } 3280 3281 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 3282 CallExpr *TheCall) { 3283 3284 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 3285 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3286 if (!TI.hasFeature("dsp")) 3287 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3288 } 3289 3290 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3291 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3292 if (!TI.hasFeature("dspr2")) 3293 return Diag(TheCall->getBeginLoc(), 3294 diag::err_mips_builtin_requires_dspr2); 3295 } 3296 3297 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3298 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3299 if (!TI.hasFeature("msa")) 3300 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3301 } 3302 3303 return false; 3304 } 3305 3306 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3307 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3308 // ordering for DSP is unspecified. MSA is ordered by the data format used 3309 // by the underlying instruction i.e., df/m, df/n and then by size. 3310 // 3311 // FIXME: The size tests here should instead be tablegen'd along with the 3312 // definitions from include/clang/Basic/BuiltinsMips.def. 3313 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3314 // be too. 3315 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3316 unsigned i = 0, l = 0, u = 0, m = 0; 3317 switch (BuiltinID) { 3318 default: return false; 3319 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3320 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3321 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3322 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3323 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3324 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3325 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3326 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3327 // df/m field. 3328 // These intrinsics take an unsigned 3 bit immediate. 3329 case Mips::BI__builtin_msa_bclri_b: 3330 case Mips::BI__builtin_msa_bnegi_b: 3331 case Mips::BI__builtin_msa_bseti_b: 3332 case Mips::BI__builtin_msa_sat_s_b: 3333 case Mips::BI__builtin_msa_sat_u_b: 3334 case Mips::BI__builtin_msa_slli_b: 3335 case Mips::BI__builtin_msa_srai_b: 3336 case Mips::BI__builtin_msa_srari_b: 3337 case Mips::BI__builtin_msa_srli_b: 3338 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3339 case Mips::BI__builtin_msa_binsli_b: 3340 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3341 // These intrinsics take an unsigned 4 bit immediate. 3342 case Mips::BI__builtin_msa_bclri_h: 3343 case Mips::BI__builtin_msa_bnegi_h: 3344 case Mips::BI__builtin_msa_bseti_h: 3345 case Mips::BI__builtin_msa_sat_s_h: 3346 case Mips::BI__builtin_msa_sat_u_h: 3347 case Mips::BI__builtin_msa_slli_h: 3348 case Mips::BI__builtin_msa_srai_h: 3349 case Mips::BI__builtin_msa_srari_h: 3350 case Mips::BI__builtin_msa_srli_h: 3351 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3352 case Mips::BI__builtin_msa_binsli_h: 3353 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3354 // These intrinsics take an unsigned 5 bit immediate. 3355 // The first block of intrinsics actually have an unsigned 5 bit field, 3356 // not a df/n field. 3357 case Mips::BI__builtin_msa_cfcmsa: 3358 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3359 case Mips::BI__builtin_msa_clei_u_b: 3360 case Mips::BI__builtin_msa_clei_u_h: 3361 case Mips::BI__builtin_msa_clei_u_w: 3362 case Mips::BI__builtin_msa_clei_u_d: 3363 case Mips::BI__builtin_msa_clti_u_b: 3364 case Mips::BI__builtin_msa_clti_u_h: 3365 case Mips::BI__builtin_msa_clti_u_w: 3366 case Mips::BI__builtin_msa_clti_u_d: 3367 case Mips::BI__builtin_msa_maxi_u_b: 3368 case Mips::BI__builtin_msa_maxi_u_h: 3369 case Mips::BI__builtin_msa_maxi_u_w: 3370 case Mips::BI__builtin_msa_maxi_u_d: 3371 case Mips::BI__builtin_msa_mini_u_b: 3372 case Mips::BI__builtin_msa_mini_u_h: 3373 case Mips::BI__builtin_msa_mini_u_w: 3374 case Mips::BI__builtin_msa_mini_u_d: 3375 case Mips::BI__builtin_msa_addvi_b: 3376 case Mips::BI__builtin_msa_addvi_h: 3377 case Mips::BI__builtin_msa_addvi_w: 3378 case Mips::BI__builtin_msa_addvi_d: 3379 case Mips::BI__builtin_msa_bclri_w: 3380 case Mips::BI__builtin_msa_bnegi_w: 3381 case Mips::BI__builtin_msa_bseti_w: 3382 case Mips::BI__builtin_msa_sat_s_w: 3383 case Mips::BI__builtin_msa_sat_u_w: 3384 case Mips::BI__builtin_msa_slli_w: 3385 case Mips::BI__builtin_msa_srai_w: 3386 case Mips::BI__builtin_msa_srari_w: 3387 case Mips::BI__builtin_msa_srli_w: 3388 case Mips::BI__builtin_msa_srlri_w: 3389 case Mips::BI__builtin_msa_subvi_b: 3390 case Mips::BI__builtin_msa_subvi_h: 3391 case Mips::BI__builtin_msa_subvi_w: 3392 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3393 case Mips::BI__builtin_msa_binsli_w: 3394 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3395 // These intrinsics take an unsigned 6 bit immediate. 3396 case Mips::BI__builtin_msa_bclri_d: 3397 case Mips::BI__builtin_msa_bnegi_d: 3398 case Mips::BI__builtin_msa_bseti_d: 3399 case Mips::BI__builtin_msa_sat_s_d: 3400 case Mips::BI__builtin_msa_sat_u_d: 3401 case Mips::BI__builtin_msa_slli_d: 3402 case Mips::BI__builtin_msa_srai_d: 3403 case Mips::BI__builtin_msa_srari_d: 3404 case Mips::BI__builtin_msa_srli_d: 3405 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3406 case Mips::BI__builtin_msa_binsli_d: 3407 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3408 // These intrinsics take a signed 5 bit immediate. 3409 case Mips::BI__builtin_msa_ceqi_b: 3410 case Mips::BI__builtin_msa_ceqi_h: 3411 case Mips::BI__builtin_msa_ceqi_w: 3412 case Mips::BI__builtin_msa_ceqi_d: 3413 case Mips::BI__builtin_msa_clti_s_b: 3414 case Mips::BI__builtin_msa_clti_s_h: 3415 case Mips::BI__builtin_msa_clti_s_w: 3416 case Mips::BI__builtin_msa_clti_s_d: 3417 case Mips::BI__builtin_msa_clei_s_b: 3418 case Mips::BI__builtin_msa_clei_s_h: 3419 case Mips::BI__builtin_msa_clei_s_w: 3420 case Mips::BI__builtin_msa_clei_s_d: 3421 case Mips::BI__builtin_msa_maxi_s_b: 3422 case Mips::BI__builtin_msa_maxi_s_h: 3423 case Mips::BI__builtin_msa_maxi_s_w: 3424 case Mips::BI__builtin_msa_maxi_s_d: 3425 case Mips::BI__builtin_msa_mini_s_b: 3426 case Mips::BI__builtin_msa_mini_s_h: 3427 case Mips::BI__builtin_msa_mini_s_w: 3428 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3429 // These intrinsics take an unsigned 8 bit immediate. 3430 case Mips::BI__builtin_msa_andi_b: 3431 case Mips::BI__builtin_msa_nori_b: 3432 case Mips::BI__builtin_msa_ori_b: 3433 case Mips::BI__builtin_msa_shf_b: 3434 case Mips::BI__builtin_msa_shf_h: 3435 case Mips::BI__builtin_msa_shf_w: 3436 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3437 case Mips::BI__builtin_msa_bseli_b: 3438 case Mips::BI__builtin_msa_bmnzi_b: 3439 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3440 // df/n format 3441 // These intrinsics take an unsigned 4 bit immediate. 3442 case Mips::BI__builtin_msa_copy_s_b: 3443 case Mips::BI__builtin_msa_copy_u_b: 3444 case Mips::BI__builtin_msa_insve_b: 3445 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3446 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3447 // These intrinsics take an unsigned 3 bit immediate. 3448 case Mips::BI__builtin_msa_copy_s_h: 3449 case Mips::BI__builtin_msa_copy_u_h: 3450 case Mips::BI__builtin_msa_insve_h: 3451 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3452 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3453 // These intrinsics take an unsigned 2 bit immediate. 3454 case Mips::BI__builtin_msa_copy_s_w: 3455 case Mips::BI__builtin_msa_copy_u_w: 3456 case Mips::BI__builtin_msa_insve_w: 3457 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3458 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3459 // These intrinsics take an unsigned 1 bit immediate. 3460 case Mips::BI__builtin_msa_copy_s_d: 3461 case Mips::BI__builtin_msa_copy_u_d: 3462 case Mips::BI__builtin_msa_insve_d: 3463 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3464 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3465 // Memory offsets and immediate loads. 3466 // These intrinsics take a signed 10 bit immediate. 3467 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3468 case Mips::BI__builtin_msa_ldi_h: 3469 case Mips::BI__builtin_msa_ldi_w: 3470 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3471 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3472 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3473 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3474 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3475 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3476 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3477 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3478 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3479 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3480 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3481 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3482 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3483 } 3484 3485 if (!m) 3486 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3487 3488 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3489 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3490 } 3491 3492 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3493 /// advancing the pointer over the consumed characters. The decoded type is 3494 /// returned. If the decoded type represents a constant integer with a 3495 /// constraint on its value then Mask is set to that value. The type descriptors 3496 /// used in Str are specific to PPC MMA builtins and are documented in the file 3497 /// defining the PPC builtins. 3498 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3499 unsigned &Mask) { 3500 bool RequireICE = false; 3501 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3502 switch (*Str++) { 3503 case 'V': 3504 return Context.getVectorType(Context.UnsignedCharTy, 16, 3505 VectorType::VectorKind::AltiVecVector); 3506 case 'i': { 3507 char *End; 3508 unsigned size = strtoul(Str, &End, 10); 3509 assert(End != Str && "Missing constant parameter constraint"); 3510 Str = End; 3511 Mask = size; 3512 return Context.IntTy; 3513 } 3514 case 'W': { 3515 char *End; 3516 unsigned size = strtoul(Str, &End, 10); 3517 assert(End != Str && "Missing PowerPC MMA type size"); 3518 Str = End; 3519 QualType Type; 3520 switch (size) { 3521 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3522 case size: Type = Context.Id##Ty; break; 3523 #include "clang/Basic/PPCTypes.def" 3524 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3525 } 3526 bool CheckVectorArgs = false; 3527 while (!CheckVectorArgs) { 3528 switch (*Str++) { 3529 case '*': 3530 Type = Context.getPointerType(Type); 3531 break; 3532 case 'C': 3533 Type = Type.withConst(); 3534 break; 3535 default: 3536 CheckVectorArgs = true; 3537 --Str; 3538 break; 3539 } 3540 } 3541 return Type; 3542 } 3543 default: 3544 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3545 } 3546 } 3547 3548 static bool isPPC_64Builtin(unsigned BuiltinID) { 3549 // These builtins only work on PPC 64bit targets. 3550 switch (BuiltinID) { 3551 case PPC::BI__builtin_divde: 3552 case PPC::BI__builtin_divdeu: 3553 case PPC::BI__builtin_bpermd: 3554 case PPC::BI__builtin_ppc_ldarx: 3555 case PPC::BI__builtin_ppc_stdcx: 3556 case PPC::BI__builtin_ppc_tdw: 3557 case PPC::BI__builtin_ppc_trapd: 3558 case PPC::BI__builtin_ppc_cmpeqb: 3559 case PPC::BI__builtin_ppc_setb: 3560 case PPC::BI__builtin_ppc_mulhd: 3561 case PPC::BI__builtin_ppc_mulhdu: 3562 case PPC::BI__builtin_ppc_maddhd: 3563 case PPC::BI__builtin_ppc_maddhdu: 3564 case PPC::BI__builtin_ppc_maddld: 3565 case PPC::BI__builtin_ppc_load8r: 3566 case PPC::BI__builtin_ppc_store8r: 3567 case PPC::BI__builtin_ppc_insert_exp: 3568 case PPC::BI__builtin_ppc_extract_sig: 3569 case PPC::BI__builtin_ppc_addex: 3570 case PPC::BI__builtin_darn: 3571 case PPC::BI__builtin_darn_raw: 3572 case PPC::BI__builtin_ppc_compare_and_swaplp: 3573 case PPC::BI__builtin_ppc_fetch_and_addlp: 3574 case PPC::BI__builtin_ppc_fetch_and_andlp: 3575 case PPC::BI__builtin_ppc_fetch_and_orlp: 3576 case PPC::BI__builtin_ppc_fetch_and_swaplp: 3577 return true; 3578 } 3579 return false; 3580 } 3581 3582 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3583 StringRef FeatureToCheck, unsigned DiagID, 3584 StringRef DiagArg = "") { 3585 if (S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3586 return false; 3587 3588 if (DiagArg.empty()) 3589 S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3590 else 3591 S.Diag(TheCall->getBeginLoc(), DiagID) 3592 << DiagArg << TheCall->getSourceRange(); 3593 3594 return true; 3595 } 3596 3597 /// Returns true if the argument consists of one contiguous run of 1s with any 3598 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so 3599 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, 3600 /// since all 1s are not contiguous. 3601 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { 3602 llvm::APSInt Result; 3603 // We can't check the value of a dependent argument. 3604 Expr *Arg = TheCall->getArg(ArgNum); 3605 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3606 return false; 3607 3608 // Check constant-ness first. 3609 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3610 return true; 3611 3612 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. 3613 if (Result.isShiftedMask() || (~Result).isShiftedMask()) 3614 return false; 3615 3616 return Diag(TheCall->getBeginLoc(), 3617 diag::err_argument_not_contiguous_bit_field) 3618 << ArgNum << Arg->getSourceRange(); 3619 } 3620 3621 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3622 CallExpr *TheCall) { 3623 unsigned i = 0, l = 0, u = 0; 3624 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3625 llvm::APSInt Result; 3626 3627 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3628 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3629 << TheCall->getSourceRange(); 3630 3631 switch (BuiltinID) { 3632 default: return false; 3633 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3634 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3635 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3636 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3637 case PPC::BI__builtin_altivec_dss: 3638 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3639 case PPC::BI__builtin_tbegin: 3640 case PPC::BI__builtin_tend: 3641 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) || 3642 SemaFeatureCheck(*this, TheCall, "htm", 3643 diag::err_ppc_builtin_requires_htm); 3644 case PPC::BI__builtin_tsr: 3645 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3646 SemaFeatureCheck(*this, TheCall, "htm", 3647 diag::err_ppc_builtin_requires_htm); 3648 case PPC::BI__builtin_tabortwc: 3649 case PPC::BI__builtin_tabortdc: 3650 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3651 SemaFeatureCheck(*this, TheCall, "htm", 3652 diag::err_ppc_builtin_requires_htm); 3653 case PPC::BI__builtin_tabortwci: 3654 case PPC::BI__builtin_tabortdci: 3655 return SemaFeatureCheck(*this, TheCall, "htm", 3656 diag::err_ppc_builtin_requires_htm) || 3657 (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3658 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31)); 3659 case PPC::BI__builtin_tabort: 3660 case PPC::BI__builtin_tcheck: 3661 case PPC::BI__builtin_treclaim: 3662 case PPC::BI__builtin_trechkpt: 3663 case PPC::BI__builtin_tendall: 3664 case PPC::BI__builtin_tresume: 3665 case PPC::BI__builtin_tsuspend: 3666 case PPC::BI__builtin_get_texasr: 3667 case PPC::BI__builtin_get_texasru: 3668 case PPC::BI__builtin_get_tfhar: 3669 case PPC::BI__builtin_get_tfiar: 3670 case PPC::BI__builtin_set_texasr: 3671 case PPC::BI__builtin_set_texasru: 3672 case PPC::BI__builtin_set_tfhar: 3673 case PPC::BI__builtin_set_tfiar: 3674 case PPC::BI__builtin_ttest: 3675 return SemaFeatureCheck(*this, TheCall, "htm", 3676 diag::err_ppc_builtin_requires_htm); 3677 // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05', 3678 // __builtin_(un)pack_longdouble are available only if long double uses IBM 3679 // extended double representation. 3680 case PPC::BI__builtin_unpack_longdouble: 3681 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1)) 3682 return true; 3683 LLVM_FALLTHROUGH; 3684 case PPC::BI__builtin_pack_longdouble: 3685 if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble()) 3686 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi) 3687 << "ibmlongdouble"; 3688 return false; 3689 case PPC::BI__builtin_altivec_dst: 3690 case PPC::BI__builtin_altivec_dstt: 3691 case PPC::BI__builtin_altivec_dstst: 3692 case PPC::BI__builtin_altivec_dststt: 3693 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3694 case PPC::BI__builtin_vsx_xxpermdi: 3695 case PPC::BI__builtin_vsx_xxsldwi: 3696 return SemaBuiltinVSX(TheCall); 3697 case PPC::BI__builtin_divwe: 3698 case PPC::BI__builtin_divweu: 3699 case PPC::BI__builtin_divde: 3700 case PPC::BI__builtin_divdeu: 3701 return SemaFeatureCheck(*this, TheCall, "extdiv", 3702 diag::err_ppc_builtin_only_on_arch, "7"); 3703 case PPC::BI__builtin_bpermd: 3704 return SemaFeatureCheck(*this, TheCall, "bpermd", 3705 diag::err_ppc_builtin_only_on_arch, "7"); 3706 case PPC::BI__builtin_unpack_vector_int128: 3707 return SemaFeatureCheck(*this, TheCall, "vsx", 3708 diag::err_ppc_builtin_only_on_arch, "7") || 3709 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3710 case PPC::BI__builtin_pack_vector_int128: 3711 return SemaFeatureCheck(*this, TheCall, "vsx", 3712 diag::err_ppc_builtin_only_on_arch, "7"); 3713 case PPC::BI__builtin_altivec_vgnb: 3714 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3715 case PPC::BI__builtin_altivec_vec_replace_elt: 3716 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3717 QualType VecTy = TheCall->getArg(0)->getType(); 3718 QualType EltTy = TheCall->getArg(1)->getType(); 3719 unsigned Width = Context.getIntWidth(EltTy); 3720 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3721 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3722 } 3723 case PPC::BI__builtin_vsx_xxeval: 3724 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3725 case PPC::BI__builtin_altivec_vsldbi: 3726 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3727 case PPC::BI__builtin_altivec_vsrdbi: 3728 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3729 case PPC::BI__builtin_vsx_xxpermx: 3730 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3731 case PPC::BI__builtin_ppc_tw: 3732 case PPC::BI__builtin_ppc_tdw: 3733 return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31); 3734 case PPC::BI__builtin_ppc_cmpeqb: 3735 case PPC::BI__builtin_ppc_setb: 3736 case PPC::BI__builtin_ppc_maddhd: 3737 case PPC::BI__builtin_ppc_maddhdu: 3738 case PPC::BI__builtin_ppc_maddld: 3739 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3740 diag::err_ppc_builtin_only_on_arch, "9"); 3741 case PPC::BI__builtin_ppc_cmprb: 3742 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3743 diag::err_ppc_builtin_only_on_arch, "9") || 3744 SemaBuiltinConstantArgRange(TheCall, 0, 0, 1); 3745 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must 3746 // be a constant that represents a contiguous bit field. 3747 case PPC::BI__builtin_ppc_rlwnm: 3748 return SemaValueIsRunOfOnes(TheCall, 2); 3749 case PPC::BI__builtin_ppc_rlwimi: 3750 case PPC::BI__builtin_ppc_rldimi: 3751 return SemaBuiltinConstantArg(TheCall, 2, Result) || 3752 SemaValueIsRunOfOnes(TheCall, 3); 3753 case PPC::BI__builtin_ppc_extract_exp: 3754 case PPC::BI__builtin_ppc_extract_sig: 3755 case PPC::BI__builtin_ppc_insert_exp: 3756 return SemaFeatureCheck(*this, TheCall, "power9-vector", 3757 diag::err_ppc_builtin_only_on_arch, "9"); 3758 case PPC::BI__builtin_ppc_addex: { 3759 if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3760 diag::err_ppc_builtin_only_on_arch, "9") || 3761 SemaBuiltinConstantArgRange(TheCall, 2, 0, 3)) 3762 return true; 3763 // Output warning for reserved values 1 to 3. 3764 int ArgValue = 3765 TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue(); 3766 if (ArgValue != 0) 3767 Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour) 3768 << ArgValue; 3769 return false; 3770 } 3771 case PPC::BI__builtin_ppc_mtfsb0: 3772 case PPC::BI__builtin_ppc_mtfsb1: 3773 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 3774 case PPC::BI__builtin_ppc_mtfsf: 3775 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255); 3776 case PPC::BI__builtin_ppc_mtfsfi: 3777 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3778 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3779 case PPC::BI__builtin_ppc_alignx: 3780 return SemaBuiltinConstantArgPower2(TheCall, 0); 3781 case PPC::BI__builtin_ppc_rdlam: 3782 return SemaValueIsRunOfOnes(TheCall, 2); 3783 case PPC::BI__builtin_ppc_icbt: 3784 case PPC::BI__builtin_ppc_sthcx: 3785 case PPC::BI__builtin_ppc_stbcx: 3786 case PPC::BI__builtin_ppc_lharx: 3787 case PPC::BI__builtin_ppc_lbarx: 3788 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3789 diag::err_ppc_builtin_only_on_arch, "8"); 3790 case PPC::BI__builtin_vsx_ldrmb: 3791 case PPC::BI__builtin_vsx_strmb: 3792 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3793 diag::err_ppc_builtin_only_on_arch, "8") || 3794 SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 3795 case PPC::BI__builtin_altivec_vcntmbb: 3796 case PPC::BI__builtin_altivec_vcntmbh: 3797 case PPC::BI__builtin_altivec_vcntmbw: 3798 case PPC::BI__builtin_altivec_vcntmbd: 3799 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3800 case PPC::BI__builtin_darn: 3801 case PPC::BI__builtin_darn_raw: 3802 case PPC::BI__builtin_darn_32: 3803 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3804 diag::err_ppc_builtin_only_on_arch, "9"); 3805 case PPC::BI__builtin_vsx_xxgenpcvbm: 3806 case PPC::BI__builtin_vsx_xxgenpcvhm: 3807 case PPC::BI__builtin_vsx_xxgenpcvwm: 3808 case PPC::BI__builtin_vsx_xxgenpcvdm: 3809 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3810 case PPC::BI__builtin_ppc_compare_exp_uo: 3811 case PPC::BI__builtin_ppc_compare_exp_lt: 3812 case PPC::BI__builtin_ppc_compare_exp_gt: 3813 case PPC::BI__builtin_ppc_compare_exp_eq: 3814 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3815 diag::err_ppc_builtin_only_on_arch, "9") || 3816 SemaFeatureCheck(*this, TheCall, "vsx", 3817 diag::err_ppc_builtin_requires_vsx); 3818 case PPC::BI__builtin_ppc_test_data_class: { 3819 // Check if the first argument of the __builtin_ppc_test_data_class call is 3820 // valid. The argument must be either a 'float' or a 'double'. 3821 QualType ArgType = TheCall->getArg(0)->getType(); 3822 if (ArgType != QualType(Context.FloatTy) && 3823 ArgType != QualType(Context.DoubleTy)) 3824 return Diag(TheCall->getBeginLoc(), 3825 diag::err_ppc_invalid_test_data_class_type); 3826 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3827 diag::err_ppc_builtin_only_on_arch, "9") || 3828 SemaFeatureCheck(*this, TheCall, "vsx", 3829 diag::err_ppc_builtin_requires_vsx) || 3830 SemaBuiltinConstantArgRange(TheCall, 1, 0, 127); 3831 } 3832 case PPC::BI__builtin_ppc_load8r: 3833 case PPC::BI__builtin_ppc_store8r: 3834 return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions", 3835 diag::err_ppc_builtin_only_on_arch, "7"); 3836 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3837 case PPC::BI__builtin_##Name: \ 3838 return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types); 3839 #include "clang/Basic/BuiltinsPPC.def" 3840 } 3841 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3842 } 3843 3844 // Check if the given type is a non-pointer PPC MMA type. This function is used 3845 // in Sema to prevent invalid uses of restricted PPC MMA types. 3846 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3847 if (Type->isPointerType() || Type->isArrayType()) 3848 return false; 3849 3850 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3851 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3852 if (false 3853 #include "clang/Basic/PPCTypes.def" 3854 ) { 3855 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3856 return true; 3857 } 3858 return false; 3859 } 3860 3861 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3862 CallExpr *TheCall) { 3863 // position of memory order and scope arguments in the builtin 3864 unsigned OrderIndex, ScopeIndex; 3865 switch (BuiltinID) { 3866 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3867 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3868 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3869 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3870 OrderIndex = 2; 3871 ScopeIndex = 3; 3872 break; 3873 case AMDGPU::BI__builtin_amdgcn_fence: 3874 OrderIndex = 0; 3875 ScopeIndex = 1; 3876 break; 3877 default: 3878 return false; 3879 } 3880 3881 ExprResult Arg = TheCall->getArg(OrderIndex); 3882 auto ArgExpr = Arg.get(); 3883 Expr::EvalResult ArgResult; 3884 3885 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3886 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3887 << ArgExpr->getType(); 3888 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3889 3890 // Check validity of memory ordering as per C11 / C++11's memody model. 3891 // Only fence needs check. Atomic dec/inc allow all memory orders. 3892 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3893 return Diag(ArgExpr->getBeginLoc(), 3894 diag::warn_atomic_op_has_invalid_memory_order) 3895 << ArgExpr->getSourceRange(); 3896 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3897 case llvm::AtomicOrderingCABI::relaxed: 3898 case llvm::AtomicOrderingCABI::consume: 3899 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3900 return Diag(ArgExpr->getBeginLoc(), 3901 diag::warn_atomic_op_has_invalid_memory_order) 3902 << ArgExpr->getSourceRange(); 3903 break; 3904 case llvm::AtomicOrderingCABI::acquire: 3905 case llvm::AtomicOrderingCABI::release: 3906 case llvm::AtomicOrderingCABI::acq_rel: 3907 case llvm::AtomicOrderingCABI::seq_cst: 3908 break; 3909 } 3910 3911 Arg = TheCall->getArg(ScopeIndex); 3912 ArgExpr = Arg.get(); 3913 Expr::EvalResult ArgResult1; 3914 // Check that sync scope is a constant literal 3915 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3916 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3917 << ArgExpr->getType(); 3918 3919 return false; 3920 } 3921 3922 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 3923 llvm::APSInt Result; 3924 3925 // We can't check the value of a dependent argument. 3926 Expr *Arg = TheCall->getArg(ArgNum); 3927 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3928 return false; 3929 3930 // Check constant-ness first. 3931 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3932 return true; 3933 3934 int64_t Val = Result.getSExtValue(); 3935 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 3936 return false; 3937 3938 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 3939 << Arg->getSourceRange(); 3940 } 3941 3942 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3943 unsigned BuiltinID, 3944 CallExpr *TheCall) { 3945 // CodeGenFunction can also detect this, but this gives a better error 3946 // message. 3947 bool FeatureMissing = false; 3948 SmallVector<StringRef> ReqFeatures; 3949 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3950 Features.split(ReqFeatures, ','); 3951 3952 // Check if each required feature is included 3953 for (StringRef F : ReqFeatures) { 3954 if (TI.hasFeature(F)) 3955 continue; 3956 3957 // If the feature is 64bit, alter the string so it will print better in 3958 // the diagnostic. 3959 if (F == "64bit") 3960 F = "RV64"; 3961 3962 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 3963 F.consume_front("experimental-"); 3964 std::string FeatureStr = F.str(); 3965 FeatureStr[0] = std::toupper(FeatureStr[0]); 3966 3967 // Error message 3968 FeatureMissing = true; 3969 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 3970 << TheCall->getSourceRange() << StringRef(FeatureStr); 3971 } 3972 3973 if (FeatureMissing) 3974 return true; 3975 3976 switch (BuiltinID) { 3977 case RISCVVector::BI__builtin_rvv_vsetvli: 3978 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 3979 CheckRISCVLMUL(TheCall, 2); 3980 case RISCVVector::BI__builtin_rvv_vsetvlimax: 3981 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 3982 CheckRISCVLMUL(TheCall, 1); 3983 } 3984 3985 return false; 3986 } 3987 3988 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3989 CallExpr *TheCall) { 3990 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3991 Expr *Arg = TheCall->getArg(0); 3992 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3993 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3994 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3995 << Arg->getSourceRange(); 3996 } 3997 3998 // For intrinsics which take an immediate value as part of the instruction, 3999 // range check them here. 4000 unsigned i = 0, l = 0, u = 0; 4001 switch (BuiltinID) { 4002 default: return false; 4003 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 4004 case SystemZ::BI__builtin_s390_verimb: 4005 case SystemZ::BI__builtin_s390_verimh: 4006 case SystemZ::BI__builtin_s390_verimf: 4007 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 4008 case SystemZ::BI__builtin_s390_vfaeb: 4009 case SystemZ::BI__builtin_s390_vfaeh: 4010 case SystemZ::BI__builtin_s390_vfaef: 4011 case SystemZ::BI__builtin_s390_vfaebs: 4012 case SystemZ::BI__builtin_s390_vfaehs: 4013 case SystemZ::BI__builtin_s390_vfaefs: 4014 case SystemZ::BI__builtin_s390_vfaezb: 4015 case SystemZ::BI__builtin_s390_vfaezh: 4016 case SystemZ::BI__builtin_s390_vfaezf: 4017 case SystemZ::BI__builtin_s390_vfaezbs: 4018 case SystemZ::BI__builtin_s390_vfaezhs: 4019 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 4020 case SystemZ::BI__builtin_s390_vfisb: 4021 case SystemZ::BI__builtin_s390_vfidb: 4022 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 4023 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 4024 case SystemZ::BI__builtin_s390_vftcisb: 4025 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 4026 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 4027 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 4028 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 4029 case SystemZ::BI__builtin_s390_vstrcb: 4030 case SystemZ::BI__builtin_s390_vstrch: 4031 case SystemZ::BI__builtin_s390_vstrcf: 4032 case SystemZ::BI__builtin_s390_vstrczb: 4033 case SystemZ::BI__builtin_s390_vstrczh: 4034 case SystemZ::BI__builtin_s390_vstrczf: 4035 case SystemZ::BI__builtin_s390_vstrcbs: 4036 case SystemZ::BI__builtin_s390_vstrchs: 4037 case SystemZ::BI__builtin_s390_vstrcfs: 4038 case SystemZ::BI__builtin_s390_vstrczbs: 4039 case SystemZ::BI__builtin_s390_vstrczhs: 4040 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 4041 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 4042 case SystemZ::BI__builtin_s390_vfminsb: 4043 case SystemZ::BI__builtin_s390_vfmaxsb: 4044 case SystemZ::BI__builtin_s390_vfmindb: 4045 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 4046 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 4047 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 4048 case SystemZ::BI__builtin_s390_vclfnhs: 4049 case SystemZ::BI__builtin_s390_vclfnls: 4050 case SystemZ::BI__builtin_s390_vcfn: 4051 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break; 4052 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break; 4053 } 4054 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 4055 } 4056 4057 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 4058 /// This checks that the target supports __builtin_cpu_supports and 4059 /// that the string argument is constant and valid. 4060 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 4061 CallExpr *TheCall) { 4062 Expr *Arg = TheCall->getArg(0); 4063 4064 // Check if the argument is a string literal. 4065 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4066 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 4067 << Arg->getSourceRange(); 4068 4069 // Check the contents of the string. 4070 StringRef Feature = 4071 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4072 if (!TI.validateCpuSupports(Feature)) 4073 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 4074 << Arg->getSourceRange(); 4075 return false; 4076 } 4077 4078 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 4079 /// This checks that the target supports __builtin_cpu_is and 4080 /// that the string argument is constant and valid. 4081 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 4082 Expr *Arg = TheCall->getArg(0); 4083 4084 // Check if the argument is a string literal. 4085 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4086 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 4087 << Arg->getSourceRange(); 4088 4089 // Check the contents of the string. 4090 StringRef Feature = 4091 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4092 if (!TI.validateCpuIs(Feature)) 4093 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 4094 << Arg->getSourceRange(); 4095 return false; 4096 } 4097 4098 // Check if the rounding mode is legal. 4099 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 4100 // Indicates if this instruction has rounding control or just SAE. 4101 bool HasRC = false; 4102 4103 unsigned ArgNum = 0; 4104 switch (BuiltinID) { 4105 default: 4106 return false; 4107 case X86::BI__builtin_ia32_vcvttsd2si32: 4108 case X86::BI__builtin_ia32_vcvttsd2si64: 4109 case X86::BI__builtin_ia32_vcvttsd2usi32: 4110 case X86::BI__builtin_ia32_vcvttsd2usi64: 4111 case X86::BI__builtin_ia32_vcvttss2si32: 4112 case X86::BI__builtin_ia32_vcvttss2si64: 4113 case X86::BI__builtin_ia32_vcvttss2usi32: 4114 case X86::BI__builtin_ia32_vcvttss2usi64: 4115 case X86::BI__builtin_ia32_vcvttsh2si32: 4116 case X86::BI__builtin_ia32_vcvttsh2si64: 4117 case X86::BI__builtin_ia32_vcvttsh2usi32: 4118 case X86::BI__builtin_ia32_vcvttsh2usi64: 4119 ArgNum = 1; 4120 break; 4121 case X86::BI__builtin_ia32_maxpd512: 4122 case X86::BI__builtin_ia32_maxps512: 4123 case X86::BI__builtin_ia32_minpd512: 4124 case X86::BI__builtin_ia32_minps512: 4125 case X86::BI__builtin_ia32_maxph512: 4126 case X86::BI__builtin_ia32_minph512: 4127 ArgNum = 2; 4128 break; 4129 case X86::BI__builtin_ia32_vcvtph2pd512_mask: 4130 case X86::BI__builtin_ia32_vcvtph2psx512_mask: 4131 case X86::BI__builtin_ia32_cvtps2pd512_mask: 4132 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 4133 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 4134 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 4135 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 4136 case X86::BI__builtin_ia32_cvttps2dq512_mask: 4137 case X86::BI__builtin_ia32_cvttps2qq512_mask: 4138 case X86::BI__builtin_ia32_cvttps2udq512_mask: 4139 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 4140 case X86::BI__builtin_ia32_vcvttph2w512_mask: 4141 case X86::BI__builtin_ia32_vcvttph2uw512_mask: 4142 case X86::BI__builtin_ia32_vcvttph2dq512_mask: 4143 case X86::BI__builtin_ia32_vcvttph2udq512_mask: 4144 case X86::BI__builtin_ia32_vcvttph2qq512_mask: 4145 case X86::BI__builtin_ia32_vcvttph2uqq512_mask: 4146 case X86::BI__builtin_ia32_exp2pd_mask: 4147 case X86::BI__builtin_ia32_exp2ps_mask: 4148 case X86::BI__builtin_ia32_getexppd512_mask: 4149 case X86::BI__builtin_ia32_getexpps512_mask: 4150 case X86::BI__builtin_ia32_getexpph512_mask: 4151 case X86::BI__builtin_ia32_rcp28pd_mask: 4152 case X86::BI__builtin_ia32_rcp28ps_mask: 4153 case X86::BI__builtin_ia32_rsqrt28pd_mask: 4154 case X86::BI__builtin_ia32_rsqrt28ps_mask: 4155 case X86::BI__builtin_ia32_vcomisd: 4156 case X86::BI__builtin_ia32_vcomiss: 4157 case X86::BI__builtin_ia32_vcomish: 4158 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 4159 ArgNum = 3; 4160 break; 4161 case X86::BI__builtin_ia32_cmppd512_mask: 4162 case X86::BI__builtin_ia32_cmpps512_mask: 4163 case X86::BI__builtin_ia32_cmpsd_mask: 4164 case X86::BI__builtin_ia32_cmpss_mask: 4165 case X86::BI__builtin_ia32_cmpsh_mask: 4166 case X86::BI__builtin_ia32_vcvtsh2sd_round_mask: 4167 case X86::BI__builtin_ia32_vcvtsh2ss_round_mask: 4168 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 4169 case X86::BI__builtin_ia32_getexpsd128_round_mask: 4170 case X86::BI__builtin_ia32_getexpss128_round_mask: 4171 case X86::BI__builtin_ia32_getexpsh128_round_mask: 4172 case X86::BI__builtin_ia32_getmantpd512_mask: 4173 case X86::BI__builtin_ia32_getmantps512_mask: 4174 case X86::BI__builtin_ia32_getmantph512_mask: 4175 case X86::BI__builtin_ia32_maxsd_round_mask: 4176 case X86::BI__builtin_ia32_maxss_round_mask: 4177 case X86::BI__builtin_ia32_maxsh_round_mask: 4178 case X86::BI__builtin_ia32_minsd_round_mask: 4179 case X86::BI__builtin_ia32_minss_round_mask: 4180 case X86::BI__builtin_ia32_minsh_round_mask: 4181 case X86::BI__builtin_ia32_rcp28sd_round_mask: 4182 case X86::BI__builtin_ia32_rcp28ss_round_mask: 4183 case X86::BI__builtin_ia32_reducepd512_mask: 4184 case X86::BI__builtin_ia32_reduceps512_mask: 4185 case X86::BI__builtin_ia32_reduceph512_mask: 4186 case X86::BI__builtin_ia32_rndscalepd_mask: 4187 case X86::BI__builtin_ia32_rndscaleps_mask: 4188 case X86::BI__builtin_ia32_rndscaleph_mask: 4189 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 4190 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 4191 ArgNum = 4; 4192 break; 4193 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4194 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4195 case X86::BI__builtin_ia32_fixupimmps512_mask: 4196 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4197 case X86::BI__builtin_ia32_fixupimmsd_mask: 4198 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4199 case X86::BI__builtin_ia32_fixupimmss_mask: 4200 case X86::BI__builtin_ia32_fixupimmss_maskz: 4201 case X86::BI__builtin_ia32_getmantsd_round_mask: 4202 case X86::BI__builtin_ia32_getmantss_round_mask: 4203 case X86::BI__builtin_ia32_getmantsh_round_mask: 4204 case X86::BI__builtin_ia32_rangepd512_mask: 4205 case X86::BI__builtin_ia32_rangeps512_mask: 4206 case X86::BI__builtin_ia32_rangesd128_round_mask: 4207 case X86::BI__builtin_ia32_rangess128_round_mask: 4208 case X86::BI__builtin_ia32_reducesd_mask: 4209 case X86::BI__builtin_ia32_reducess_mask: 4210 case X86::BI__builtin_ia32_reducesh_mask: 4211 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4212 case X86::BI__builtin_ia32_rndscaless_round_mask: 4213 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4214 ArgNum = 5; 4215 break; 4216 case X86::BI__builtin_ia32_vcvtsd2si64: 4217 case X86::BI__builtin_ia32_vcvtsd2si32: 4218 case X86::BI__builtin_ia32_vcvtsd2usi32: 4219 case X86::BI__builtin_ia32_vcvtsd2usi64: 4220 case X86::BI__builtin_ia32_vcvtss2si32: 4221 case X86::BI__builtin_ia32_vcvtss2si64: 4222 case X86::BI__builtin_ia32_vcvtss2usi32: 4223 case X86::BI__builtin_ia32_vcvtss2usi64: 4224 case X86::BI__builtin_ia32_vcvtsh2si32: 4225 case X86::BI__builtin_ia32_vcvtsh2si64: 4226 case X86::BI__builtin_ia32_vcvtsh2usi32: 4227 case X86::BI__builtin_ia32_vcvtsh2usi64: 4228 case X86::BI__builtin_ia32_sqrtpd512: 4229 case X86::BI__builtin_ia32_sqrtps512: 4230 case X86::BI__builtin_ia32_sqrtph512: 4231 ArgNum = 1; 4232 HasRC = true; 4233 break; 4234 case X86::BI__builtin_ia32_addph512: 4235 case X86::BI__builtin_ia32_divph512: 4236 case X86::BI__builtin_ia32_mulph512: 4237 case X86::BI__builtin_ia32_subph512: 4238 case X86::BI__builtin_ia32_addpd512: 4239 case X86::BI__builtin_ia32_addps512: 4240 case X86::BI__builtin_ia32_divpd512: 4241 case X86::BI__builtin_ia32_divps512: 4242 case X86::BI__builtin_ia32_mulpd512: 4243 case X86::BI__builtin_ia32_mulps512: 4244 case X86::BI__builtin_ia32_subpd512: 4245 case X86::BI__builtin_ia32_subps512: 4246 case X86::BI__builtin_ia32_cvtsi2sd64: 4247 case X86::BI__builtin_ia32_cvtsi2ss32: 4248 case X86::BI__builtin_ia32_cvtsi2ss64: 4249 case X86::BI__builtin_ia32_cvtusi2sd64: 4250 case X86::BI__builtin_ia32_cvtusi2ss32: 4251 case X86::BI__builtin_ia32_cvtusi2ss64: 4252 case X86::BI__builtin_ia32_vcvtusi2sh: 4253 case X86::BI__builtin_ia32_vcvtusi642sh: 4254 case X86::BI__builtin_ia32_vcvtsi2sh: 4255 case X86::BI__builtin_ia32_vcvtsi642sh: 4256 ArgNum = 2; 4257 HasRC = true; 4258 break; 4259 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 4260 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 4261 case X86::BI__builtin_ia32_vcvtpd2ph512_mask: 4262 case X86::BI__builtin_ia32_vcvtps2phx512_mask: 4263 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 4264 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 4265 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 4266 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 4267 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 4268 case X86::BI__builtin_ia32_cvtps2dq512_mask: 4269 case X86::BI__builtin_ia32_cvtps2qq512_mask: 4270 case X86::BI__builtin_ia32_cvtps2udq512_mask: 4271 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 4272 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 4273 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 4274 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 4275 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 4276 case X86::BI__builtin_ia32_vcvtdq2ph512_mask: 4277 case X86::BI__builtin_ia32_vcvtudq2ph512_mask: 4278 case X86::BI__builtin_ia32_vcvtw2ph512_mask: 4279 case X86::BI__builtin_ia32_vcvtuw2ph512_mask: 4280 case X86::BI__builtin_ia32_vcvtph2w512_mask: 4281 case X86::BI__builtin_ia32_vcvtph2uw512_mask: 4282 case X86::BI__builtin_ia32_vcvtph2dq512_mask: 4283 case X86::BI__builtin_ia32_vcvtph2udq512_mask: 4284 case X86::BI__builtin_ia32_vcvtph2qq512_mask: 4285 case X86::BI__builtin_ia32_vcvtph2uqq512_mask: 4286 case X86::BI__builtin_ia32_vcvtqq2ph512_mask: 4287 case X86::BI__builtin_ia32_vcvtuqq2ph512_mask: 4288 ArgNum = 3; 4289 HasRC = true; 4290 break; 4291 case X86::BI__builtin_ia32_addsh_round_mask: 4292 case X86::BI__builtin_ia32_addss_round_mask: 4293 case X86::BI__builtin_ia32_addsd_round_mask: 4294 case X86::BI__builtin_ia32_divsh_round_mask: 4295 case X86::BI__builtin_ia32_divss_round_mask: 4296 case X86::BI__builtin_ia32_divsd_round_mask: 4297 case X86::BI__builtin_ia32_mulsh_round_mask: 4298 case X86::BI__builtin_ia32_mulss_round_mask: 4299 case X86::BI__builtin_ia32_mulsd_round_mask: 4300 case X86::BI__builtin_ia32_subsh_round_mask: 4301 case X86::BI__builtin_ia32_subss_round_mask: 4302 case X86::BI__builtin_ia32_subsd_round_mask: 4303 case X86::BI__builtin_ia32_scalefph512_mask: 4304 case X86::BI__builtin_ia32_scalefpd512_mask: 4305 case X86::BI__builtin_ia32_scalefps512_mask: 4306 case X86::BI__builtin_ia32_scalefsd_round_mask: 4307 case X86::BI__builtin_ia32_scalefss_round_mask: 4308 case X86::BI__builtin_ia32_scalefsh_round_mask: 4309 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 4310 case X86::BI__builtin_ia32_vcvtss2sh_round_mask: 4311 case X86::BI__builtin_ia32_vcvtsd2sh_round_mask: 4312 case X86::BI__builtin_ia32_sqrtsd_round_mask: 4313 case X86::BI__builtin_ia32_sqrtss_round_mask: 4314 case X86::BI__builtin_ia32_sqrtsh_round_mask: 4315 case X86::BI__builtin_ia32_vfmaddsd3_mask: 4316 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 4317 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 4318 case X86::BI__builtin_ia32_vfmaddss3_mask: 4319 case X86::BI__builtin_ia32_vfmaddss3_maskz: 4320 case X86::BI__builtin_ia32_vfmaddss3_mask3: 4321 case X86::BI__builtin_ia32_vfmaddsh3_mask: 4322 case X86::BI__builtin_ia32_vfmaddsh3_maskz: 4323 case X86::BI__builtin_ia32_vfmaddsh3_mask3: 4324 case X86::BI__builtin_ia32_vfmaddpd512_mask: 4325 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 4326 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 4327 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 4328 case X86::BI__builtin_ia32_vfmaddps512_mask: 4329 case X86::BI__builtin_ia32_vfmaddps512_maskz: 4330 case X86::BI__builtin_ia32_vfmaddps512_mask3: 4331 case X86::BI__builtin_ia32_vfmsubps512_mask3: 4332 case X86::BI__builtin_ia32_vfmaddph512_mask: 4333 case X86::BI__builtin_ia32_vfmaddph512_maskz: 4334 case X86::BI__builtin_ia32_vfmaddph512_mask3: 4335 case X86::BI__builtin_ia32_vfmsubph512_mask3: 4336 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 4337 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 4338 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 4339 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 4340 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 4341 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 4342 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 4343 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 4344 case X86::BI__builtin_ia32_vfmaddsubph512_mask: 4345 case X86::BI__builtin_ia32_vfmaddsubph512_maskz: 4346 case X86::BI__builtin_ia32_vfmaddsubph512_mask3: 4347 case X86::BI__builtin_ia32_vfmsubaddph512_mask3: 4348 case X86::BI__builtin_ia32_vfmaddcsh_mask: 4349 case X86::BI__builtin_ia32_vfmaddcsh_round_mask: 4350 case X86::BI__builtin_ia32_vfmaddcsh_round_mask3: 4351 case X86::BI__builtin_ia32_vfmaddcph512_mask: 4352 case X86::BI__builtin_ia32_vfmaddcph512_maskz: 4353 case X86::BI__builtin_ia32_vfmaddcph512_mask3: 4354 case X86::BI__builtin_ia32_vfcmaddcsh_mask: 4355 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask: 4356 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3: 4357 case X86::BI__builtin_ia32_vfcmaddcph512_mask: 4358 case X86::BI__builtin_ia32_vfcmaddcph512_maskz: 4359 case X86::BI__builtin_ia32_vfcmaddcph512_mask3: 4360 case X86::BI__builtin_ia32_vfmulcsh_mask: 4361 case X86::BI__builtin_ia32_vfmulcph512_mask: 4362 case X86::BI__builtin_ia32_vfcmulcsh_mask: 4363 case X86::BI__builtin_ia32_vfcmulcph512_mask: 4364 ArgNum = 4; 4365 HasRC = true; 4366 break; 4367 } 4368 4369 llvm::APSInt Result; 4370 4371 // We can't check the value of a dependent argument. 4372 Expr *Arg = TheCall->getArg(ArgNum); 4373 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4374 return false; 4375 4376 // Check constant-ness first. 4377 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4378 return true; 4379 4380 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 4381 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 4382 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 4383 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 4384 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 4385 Result == 8/*ROUND_NO_EXC*/ || 4386 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 4387 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 4388 return false; 4389 4390 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 4391 << Arg->getSourceRange(); 4392 } 4393 4394 // Check if the gather/scatter scale is legal. 4395 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 4396 CallExpr *TheCall) { 4397 unsigned ArgNum = 0; 4398 switch (BuiltinID) { 4399 default: 4400 return false; 4401 case X86::BI__builtin_ia32_gatherpfdpd: 4402 case X86::BI__builtin_ia32_gatherpfdps: 4403 case X86::BI__builtin_ia32_gatherpfqpd: 4404 case X86::BI__builtin_ia32_gatherpfqps: 4405 case X86::BI__builtin_ia32_scatterpfdpd: 4406 case X86::BI__builtin_ia32_scatterpfdps: 4407 case X86::BI__builtin_ia32_scatterpfqpd: 4408 case X86::BI__builtin_ia32_scatterpfqps: 4409 ArgNum = 3; 4410 break; 4411 case X86::BI__builtin_ia32_gatherd_pd: 4412 case X86::BI__builtin_ia32_gatherd_pd256: 4413 case X86::BI__builtin_ia32_gatherq_pd: 4414 case X86::BI__builtin_ia32_gatherq_pd256: 4415 case X86::BI__builtin_ia32_gatherd_ps: 4416 case X86::BI__builtin_ia32_gatherd_ps256: 4417 case X86::BI__builtin_ia32_gatherq_ps: 4418 case X86::BI__builtin_ia32_gatherq_ps256: 4419 case X86::BI__builtin_ia32_gatherd_q: 4420 case X86::BI__builtin_ia32_gatherd_q256: 4421 case X86::BI__builtin_ia32_gatherq_q: 4422 case X86::BI__builtin_ia32_gatherq_q256: 4423 case X86::BI__builtin_ia32_gatherd_d: 4424 case X86::BI__builtin_ia32_gatherd_d256: 4425 case X86::BI__builtin_ia32_gatherq_d: 4426 case X86::BI__builtin_ia32_gatherq_d256: 4427 case X86::BI__builtin_ia32_gather3div2df: 4428 case X86::BI__builtin_ia32_gather3div2di: 4429 case X86::BI__builtin_ia32_gather3div4df: 4430 case X86::BI__builtin_ia32_gather3div4di: 4431 case X86::BI__builtin_ia32_gather3div4sf: 4432 case X86::BI__builtin_ia32_gather3div4si: 4433 case X86::BI__builtin_ia32_gather3div8sf: 4434 case X86::BI__builtin_ia32_gather3div8si: 4435 case X86::BI__builtin_ia32_gather3siv2df: 4436 case X86::BI__builtin_ia32_gather3siv2di: 4437 case X86::BI__builtin_ia32_gather3siv4df: 4438 case X86::BI__builtin_ia32_gather3siv4di: 4439 case X86::BI__builtin_ia32_gather3siv4sf: 4440 case X86::BI__builtin_ia32_gather3siv4si: 4441 case X86::BI__builtin_ia32_gather3siv8sf: 4442 case X86::BI__builtin_ia32_gather3siv8si: 4443 case X86::BI__builtin_ia32_gathersiv8df: 4444 case X86::BI__builtin_ia32_gathersiv16sf: 4445 case X86::BI__builtin_ia32_gatherdiv8df: 4446 case X86::BI__builtin_ia32_gatherdiv16sf: 4447 case X86::BI__builtin_ia32_gathersiv8di: 4448 case X86::BI__builtin_ia32_gathersiv16si: 4449 case X86::BI__builtin_ia32_gatherdiv8di: 4450 case X86::BI__builtin_ia32_gatherdiv16si: 4451 case X86::BI__builtin_ia32_scatterdiv2df: 4452 case X86::BI__builtin_ia32_scatterdiv2di: 4453 case X86::BI__builtin_ia32_scatterdiv4df: 4454 case X86::BI__builtin_ia32_scatterdiv4di: 4455 case X86::BI__builtin_ia32_scatterdiv4sf: 4456 case X86::BI__builtin_ia32_scatterdiv4si: 4457 case X86::BI__builtin_ia32_scatterdiv8sf: 4458 case X86::BI__builtin_ia32_scatterdiv8si: 4459 case X86::BI__builtin_ia32_scattersiv2df: 4460 case X86::BI__builtin_ia32_scattersiv2di: 4461 case X86::BI__builtin_ia32_scattersiv4df: 4462 case X86::BI__builtin_ia32_scattersiv4di: 4463 case X86::BI__builtin_ia32_scattersiv4sf: 4464 case X86::BI__builtin_ia32_scattersiv4si: 4465 case X86::BI__builtin_ia32_scattersiv8sf: 4466 case X86::BI__builtin_ia32_scattersiv8si: 4467 case X86::BI__builtin_ia32_scattersiv8df: 4468 case X86::BI__builtin_ia32_scattersiv16sf: 4469 case X86::BI__builtin_ia32_scatterdiv8df: 4470 case X86::BI__builtin_ia32_scatterdiv16sf: 4471 case X86::BI__builtin_ia32_scattersiv8di: 4472 case X86::BI__builtin_ia32_scattersiv16si: 4473 case X86::BI__builtin_ia32_scatterdiv8di: 4474 case X86::BI__builtin_ia32_scatterdiv16si: 4475 ArgNum = 4; 4476 break; 4477 } 4478 4479 llvm::APSInt Result; 4480 4481 // We can't check the value of a dependent argument. 4482 Expr *Arg = TheCall->getArg(ArgNum); 4483 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4484 return false; 4485 4486 // Check constant-ness first. 4487 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4488 return true; 4489 4490 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4491 return false; 4492 4493 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4494 << Arg->getSourceRange(); 4495 } 4496 4497 enum { TileRegLow = 0, TileRegHigh = 7 }; 4498 4499 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4500 ArrayRef<int> ArgNums) { 4501 for (int ArgNum : ArgNums) { 4502 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4503 return true; 4504 } 4505 return false; 4506 } 4507 4508 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4509 ArrayRef<int> ArgNums) { 4510 // Because the max number of tile register is TileRegHigh + 1, so here we use 4511 // each bit to represent the usage of them in bitset. 4512 std::bitset<TileRegHigh + 1> ArgValues; 4513 for (int ArgNum : ArgNums) { 4514 Expr *Arg = TheCall->getArg(ArgNum); 4515 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4516 continue; 4517 4518 llvm::APSInt Result; 4519 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4520 return true; 4521 int ArgExtValue = Result.getExtValue(); 4522 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4523 "Incorrect tile register num."); 4524 if (ArgValues.test(ArgExtValue)) 4525 return Diag(TheCall->getBeginLoc(), 4526 diag::err_x86_builtin_tile_arg_duplicate) 4527 << TheCall->getArg(ArgNum)->getSourceRange(); 4528 ArgValues.set(ArgExtValue); 4529 } 4530 return false; 4531 } 4532 4533 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 4534 ArrayRef<int> ArgNums) { 4535 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 4536 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 4537 } 4538 4539 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 4540 switch (BuiltinID) { 4541 default: 4542 return false; 4543 case X86::BI__builtin_ia32_tileloadd64: 4544 case X86::BI__builtin_ia32_tileloaddt164: 4545 case X86::BI__builtin_ia32_tilestored64: 4546 case X86::BI__builtin_ia32_tilezero: 4547 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 4548 case X86::BI__builtin_ia32_tdpbssd: 4549 case X86::BI__builtin_ia32_tdpbsud: 4550 case X86::BI__builtin_ia32_tdpbusd: 4551 case X86::BI__builtin_ia32_tdpbuud: 4552 case X86::BI__builtin_ia32_tdpbf16ps: 4553 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 4554 } 4555 } 4556 static bool isX86_32Builtin(unsigned BuiltinID) { 4557 // These builtins only work on x86-32 targets. 4558 switch (BuiltinID) { 4559 case X86::BI__builtin_ia32_readeflags_u32: 4560 case X86::BI__builtin_ia32_writeeflags_u32: 4561 return true; 4562 } 4563 4564 return false; 4565 } 4566 4567 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 4568 CallExpr *TheCall) { 4569 if (BuiltinID == X86::BI__builtin_cpu_supports) 4570 return SemaBuiltinCpuSupports(*this, TI, TheCall); 4571 4572 if (BuiltinID == X86::BI__builtin_cpu_is) 4573 return SemaBuiltinCpuIs(*this, TI, TheCall); 4574 4575 // Check for 32-bit only builtins on a 64-bit target. 4576 const llvm::Triple &TT = TI.getTriple(); 4577 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 4578 return Diag(TheCall->getCallee()->getBeginLoc(), 4579 diag::err_32_bit_builtin_64_bit_tgt); 4580 4581 // If the intrinsic has rounding or SAE make sure its valid. 4582 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 4583 return true; 4584 4585 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 4586 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 4587 return true; 4588 4589 // If the intrinsic has a tile arguments, make sure they are valid. 4590 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4591 return true; 4592 4593 // For intrinsics which take an immediate value as part of the instruction, 4594 // range check them here. 4595 int i = 0, l = 0, u = 0; 4596 switch (BuiltinID) { 4597 default: 4598 return false; 4599 case X86::BI__builtin_ia32_vec_ext_v2si: 4600 case X86::BI__builtin_ia32_vec_ext_v2di: 4601 case X86::BI__builtin_ia32_vextractf128_pd256: 4602 case X86::BI__builtin_ia32_vextractf128_ps256: 4603 case X86::BI__builtin_ia32_vextractf128_si256: 4604 case X86::BI__builtin_ia32_extract128i256: 4605 case X86::BI__builtin_ia32_extractf64x4_mask: 4606 case X86::BI__builtin_ia32_extracti64x4_mask: 4607 case X86::BI__builtin_ia32_extractf32x8_mask: 4608 case X86::BI__builtin_ia32_extracti32x8_mask: 4609 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4610 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4611 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4612 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4613 i = 1; l = 0; u = 1; 4614 break; 4615 case X86::BI__builtin_ia32_vec_set_v2di: 4616 case X86::BI__builtin_ia32_vinsertf128_pd256: 4617 case X86::BI__builtin_ia32_vinsertf128_ps256: 4618 case X86::BI__builtin_ia32_vinsertf128_si256: 4619 case X86::BI__builtin_ia32_insert128i256: 4620 case X86::BI__builtin_ia32_insertf32x8: 4621 case X86::BI__builtin_ia32_inserti32x8: 4622 case X86::BI__builtin_ia32_insertf64x4: 4623 case X86::BI__builtin_ia32_inserti64x4: 4624 case X86::BI__builtin_ia32_insertf64x2_256: 4625 case X86::BI__builtin_ia32_inserti64x2_256: 4626 case X86::BI__builtin_ia32_insertf32x4_256: 4627 case X86::BI__builtin_ia32_inserti32x4_256: 4628 i = 2; l = 0; u = 1; 4629 break; 4630 case X86::BI__builtin_ia32_vpermilpd: 4631 case X86::BI__builtin_ia32_vec_ext_v4hi: 4632 case X86::BI__builtin_ia32_vec_ext_v4si: 4633 case X86::BI__builtin_ia32_vec_ext_v4sf: 4634 case X86::BI__builtin_ia32_vec_ext_v4di: 4635 case X86::BI__builtin_ia32_extractf32x4_mask: 4636 case X86::BI__builtin_ia32_extracti32x4_mask: 4637 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4638 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4639 i = 1; l = 0; u = 3; 4640 break; 4641 case X86::BI_mm_prefetch: 4642 case X86::BI__builtin_ia32_vec_ext_v8hi: 4643 case X86::BI__builtin_ia32_vec_ext_v8si: 4644 i = 1; l = 0; u = 7; 4645 break; 4646 case X86::BI__builtin_ia32_sha1rnds4: 4647 case X86::BI__builtin_ia32_blendpd: 4648 case X86::BI__builtin_ia32_shufpd: 4649 case X86::BI__builtin_ia32_vec_set_v4hi: 4650 case X86::BI__builtin_ia32_vec_set_v4si: 4651 case X86::BI__builtin_ia32_vec_set_v4di: 4652 case X86::BI__builtin_ia32_shuf_f32x4_256: 4653 case X86::BI__builtin_ia32_shuf_f64x2_256: 4654 case X86::BI__builtin_ia32_shuf_i32x4_256: 4655 case X86::BI__builtin_ia32_shuf_i64x2_256: 4656 case X86::BI__builtin_ia32_insertf64x2_512: 4657 case X86::BI__builtin_ia32_inserti64x2_512: 4658 case X86::BI__builtin_ia32_insertf32x4: 4659 case X86::BI__builtin_ia32_inserti32x4: 4660 i = 2; l = 0; u = 3; 4661 break; 4662 case X86::BI__builtin_ia32_vpermil2pd: 4663 case X86::BI__builtin_ia32_vpermil2pd256: 4664 case X86::BI__builtin_ia32_vpermil2ps: 4665 case X86::BI__builtin_ia32_vpermil2ps256: 4666 i = 3; l = 0; u = 3; 4667 break; 4668 case X86::BI__builtin_ia32_cmpb128_mask: 4669 case X86::BI__builtin_ia32_cmpw128_mask: 4670 case X86::BI__builtin_ia32_cmpd128_mask: 4671 case X86::BI__builtin_ia32_cmpq128_mask: 4672 case X86::BI__builtin_ia32_cmpb256_mask: 4673 case X86::BI__builtin_ia32_cmpw256_mask: 4674 case X86::BI__builtin_ia32_cmpd256_mask: 4675 case X86::BI__builtin_ia32_cmpq256_mask: 4676 case X86::BI__builtin_ia32_cmpb512_mask: 4677 case X86::BI__builtin_ia32_cmpw512_mask: 4678 case X86::BI__builtin_ia32_cmpd512_mask: 4679 case X86::BI__builtin_ia32_cmpq512_mask: 4680 case X86::BI__builtin_ia32_ucmpb128_mask: 4681 case X86::BI__builtin_ia32_ucmpw128_mask: 4682 case X86::BI__builtin_ia32_ucmpd128_mask: 4683 case X86::BI__builtin_ia32_ucmpq128_mask: 4684 case X86::BI__builtin_ia32_ucmpb256_mask: 4685 case X86::BI__builtin_ia32_ucmpw256_mask: 4686 case X86::BI__builtin_ia32_ucmpd256_mask: 4687 case X86::BI__builtin_ia32_ucmpq256_mask: 4688 case X86::BI__builtin_ia32_ucmpb512_mask: 4689 case X86::BI__builtin_ia32_ucmpw512_mask: 4690 case X86::BI__builtin_ia32_ucmpd512_mask: 4691 case X86::BI__builtin_ia32_ucmpq512_mask: 4692 case X86::BI__builtin_ia32_vpcomub: 4693 case X86::BI__builtin_ia32_vpcomuw: 4694 case X86::BI__builtin_ia32_vpcomud: 4695 case X86::BI__builtin_ia32_vpcomuq: 4696 case X86::BI__builtin_ia32_vpcomb: 4697 case X86::BI__builtin_ia32_vpcomw: 4698 case X86::BI__builtin_ia32_vpcomd: 4699 case X86::BI__builtin_ia32_vpcomq: 4700 case X86::BI__builtin_ia32_vec_set_v8hi: 4701 case X86::BI__builtin_ia32_vec_set_v8si: 4702 i = 2; l = 0; u = 7; 4703 break; 4704 case X86::BI__builtin_ia32_vpermilpd256: 4705 case X86::BI__builtin_ia32_roundps: 4706 case X86::BI__builtin_ia32_roundpd: 4707 case X86::BI__builtin_ia32_roundps256: 4708 case X86::BI__builtin_ia32_roundpd256: 4709 case X86::BI__builtin_ia32_getmantpd128_mask: 4710 case X86::BI__builtin_ia32_getmantpd256_mask: 4711 case X86::BI__builtin_ia32_getmantps128_mask: 4712 case X86::BI__builtin_ia32_getmantps256_mask: 4713 case X86::BI__builtin_ia32_getmantpd512_mask: 4714 case X86::BI__builtin_ia32_getmantps512_mask: 4715 case X86::BI__builtin_ia32_getmantph128_mask: 4716 case X86::BI__builtin_ia32_getmantph256_mask: 4717 case X86::BI__builtin_ia32_getmantph512_mask: 4718 case X86::BI__builtin_ia32_vec_ext_v16qi: 4719 case X86::BI__builtin_ia32_vec_ext_v16hi: 4720 i = 1; l = 0; u = 15; 4721 break; 4722 case X86::BI__builtin_ia32_pblendd128: 4723 case X86::BI__builtin_ia32_blendps: 4724 case X86::BI__builtin_ia32_blendpd256: 4725 case X86::BI__builtin_ia32_shufpd256: 4726 case X86::BI__builtin_ia32_roundss: 4727 case X86::BI__builtin_ia32_roundsd: 4728 case X86::BI__builtin_ia32_rangepd128_mask: 4729 case X86::BI__builtin_ia32_rangepd256_mask: 4730 case X86::BI__builtin_ia32_rangepd512_mask: 4731 case X86::BI__builtin_ia32_rangeps128_mask: 4732 case X86::BI__builtin_ia32_rangeps256_mask: 4733 case X86::BI__builtin_ia32_rangeps512_mask: 4734 case X86::BI__builtin_ia32_getmantsd_round_mask: 4735 case X86::BI__builtin_ia32_getmantss_round_mask: 4736 case X86::BI__builtin_ia32_getmantsh_round_mask: 4737 case X86::BI__builtin_ia32_vec_set_v16qi: 4738 case X86::BI__builtin_ia32_vec_set_v16hi: 4739 i = 2; l = 0; u = 15; 4740 break; 4741 case X86::BI__builtin_ia32_vec_ext_v32qi: 4742 i = 1; l = 0; u = 31; 4743 break; 4744 case X86::BI__builtin_ia32_cmpps: 4745 case X86::BI__builtin_ia32_cmpss: 4746 case X86::BI__builtin_ia32_cmppd: 4747 case X86::BI__builtin_ia32_cmpsd: 4748 case X86::BI__builtin_ia32_cmpps256: 4749 case X86::BI__builtin_ia32_cmppd256: 4750 case X86::BI__builtin_ia32_cmpps128_mask: 4751 case X86::BI__builtin_ia32_cmppd128_mask: 4752 case X86::BI__builtin_ia32_cmpps256_mask: 4753 case X86::BI__builtin_ia32_cmppd256_mask: 4754 case X86::BI__builtin_ia32_cmpps512_mask: 4755 case X86::BI__builtin_ia32_cmppd512_mask: 4756 case X86::BI__builtin_ia32_cmpsd_mask: 4757 case X86::BI__builtin_ia32_cmpss_mask: 4758 case X86::BI__builtin_ia32_vec_set_v32qi: 4759 i = 2; l = 0; u = 31; 4760 break; 4761 case X86::BI__builtin_ia32_permdf256: 4762 case X86::BI__builtin_ia32_permdi256: 4763 case X86::BI__builtin_ia32_permdf512: 4764 case X86::BI__builtin_ia32_permdi512: 4765 case X86::BI__builtin_ia32_vpermilps: 4766 case X86::BI__builtin_ia32_vpermilps256: 4767 case X86::BI__builtin_ia32_vpermilpd512: 4768 case X86::BI__builtin_ia32_vpermilps512: 4769 case X86::BI__builtin_ia32_pshufd: 4770 case X86::BI__builtin_ia32_pshufd256: 4771 case X86::BI__builtin_ia32_pshufd512: 4772 case X86::BI__builtin_ia32_pshufhw: 4773 case X86::BI__builtin_ia32_pshufhw256: 4774 case X86::BI__builtin_ia32_pshufhw512: 4775 case X86::BI__builtin_ia32_pshuflw: 4776 case X86::BI__builtin_ia32_pshuflw256: 4777 case X86::BI__builtin_ia32_pshuflw512: 4778 case X86::BI__builtin_ia32_vcvtps2ph: 4779 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4780 case X86::BI__builtin_ia32_vcvtps2ph256: 4781 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4782 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4783 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4784 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4785 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4786 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4787 case X86::BI__builtin_ia32_rndscaleps_mask: 4788 case X86::BI__builtin_ia32_rndscalepd_mask: 4789 case X86::BI__builtin_ia32_rndscaleph_mask: 4790 case X86::BI__builtin_ia32_reducepd128_mask: 4791 case X86::BI__builtin_ia32_reducepd256_mask: 4792 case X86::BI__builtin_ia32_reducepd512_mask: 4793 case X86::BI__builtin_ia32_reduceps128_mask: 4794 case X86::BI__builtin_ia32_reduceps256_mask: 4795 case X86::BI__builtin_ia32_reduceps512_mask: 4796 case X86::BI__builtin_ia32_reduceph128_mask: 4797 case X86::BI__builtin_ia32_reduceph256_mask: 4798 case X86::BI__builtin_ia32_reduceph512_mask: 4799 case X86::BI__builtin_ia32_prold512: 4800 case X86::BI__builtin_ia32_prolq512: 4801 case X86::BI__builtin_ia32_prold128: 4802 case X86::BI__builtin_ia32_prold256: 4803 case X86::BI__builtin_ia32_prolq128: 4804 case X86::BI__builtin_ia32_prolq256: 4805 case X86::BI__builtin_ia32_prord512: 4806 case X86::BI__builtin_ia32_prorq512: 4807 case X86::BI__builtin_ia32_prord128: 4808 case X86::BI__builtin_ia32_prord256: 4809 case X86::BI__builtin_ia32_prorq128: 4810 case X86::BI__builtin_ia32_prorq256: 4811 case X86::BI__builtin_ia32_fpclasspd128_mask: 4812 case X86::BI__builtin_ia32_fpclasspd256_mask: 4813 case X86::BI__builtin_ia32_fpclassps128_mask: 4814 case X86::BI__builtin_ia32_fpclassps256_mask: 4815 case X86::BI__builtin_ia32_fpclassps512_mask: 4816 case X86::BI__builtin_ia32_fpclasspd512_mask: 4817 case X86::BI__builtin_ia32_fpclassph128_mask: 4818 case X86::BI__builtin_ia32_fpclassph256_mask: 4819 case X86::BI__builtin_ia32_fpclassph512_mask: 4820 case X86::BI__builtin_ia32_fpclasssd_mask: 4821 case X86::BI__builtin_ia32_fpclassss_mask: 4822 case X86::BI__builtin_ia32_fpclasssh_mask: 4823 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4824 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4825 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4826 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4827 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4828 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4829 case X86::BI__builtin_ia32_kshiftliqi: 4830 case X86::BI__builtin_ia32_kshiftlihi: 4831 case X86::BI__builtin_ia32_kshiftlisi: 4832 case X86::BI__builtin_ia32_kshiftlidi: 4833 case X86::BI__builtin_ia32_kshiftriqi: 4834 case X86::BI__builtin_ia32_kshiftrihi: 4835 case X86::BI__builtin_ia32_kshiftrisi: 4836 case X86::BI__builtin_ia32_kshiftridi: 4837 i = 1; l = 0; u = 255; 4838 break; 4839 case X86::BI__builtin_ia32_vperm2f128_pd256: 4840 case X86::BI__builtin_ia32_vperm2f128_ps256: 4841 case X86::BI__builtin_ia32_vperm2f128_si256: 4842 case X86::BI__builtin_ia32_permti256: 4843 case X86::BI__builtin_ia32_pblendw128: 4844 case X86::BI__builtin_ia32_pblendw256: 4845 case X86::BI__builtin_ia32_blendps256: 4846 case X86::BI__builtin_ia32_pblendd256: 4847 case X86::BI__builtin_ia32_palignr128: 4848 case X86::BI__builtin_ia32_palignr256: 4849 case X86::BI__builtin_ia32_palignr512: 4850 case X86::BI__builtin_ia32_alignq512: 4851 case X86::BI__builtin_ia32_alignd512: 4852 case X86::BI__builtin_ia32_alignd128: 4853 case X86::BI__builtin_ia32_alignd256: 4854 case X86::BI__builtin_ia32_alignq128: 4855 case X86::BI__builtin_ia32_alignq256: 4856 case X86::BI__builtin_ia32_vcomisd: 4857 case X86::BI__builtin_ia32_vcomiss: 4858 case X86::BI__builtin_ia32_shuf_f32x4: 4859 case X86::BI__builtin_ia32_shuf_f64x2: 4860 case X86::BI__builtin_ia32_shuf_i32x4: 4861 case X86::BI__builtin_ia32_shuf_i64x2: 4862 case X86::BI__builtin_ia32_shufpd512: 4863 case X86::BI__builtin_ia32_shufps: 4864 case X86::BI__builtin_ia32_shufps256: 4865 case X86::BI__builtin_ia32_shufps512: 4866 case X86::BI__builtin_ia32_dbpsadbw128: 4867 case X86::BI__builtin_ia32_dbpsadbw256: 4868 case X86::BI__builtin_ia32_dbpsadbw512: 4869 case X86::BI__builtin_ia32_vpshldd128: 4870 case X86::BI__builtin_ia32_vpshldd256: 4871 case X86::BI__builtin_ia32_vpshldd512: 4872 case X86::BI__builtin_ia32_vpshldq128: 4873 case X86::BI__builtin_ia32_vpshldq256: 4874 case X86::BI__builtin_ia32_vpshldq512: 4875 case X86::BI__builtin_ia32_vpshldw128: 4876 case X86::BI__builtin_ia32_vpshldw256: 4877 case X86::BI__builtin_ia32_vpshldw512: 4878 case X86::BI__builtin_ia32_vpshrdd128: 4879 case X86::BI__builtin_ia32_vpshrdd256: 4880 case X86::BI__builtin_ia32_vpshrdd512: 4881 case X86::BI__builtin_ia32_vpshrdq128: 4882 case X86::BI__builtin_ia32_vpshrdq256: 4883 case X86::BI__builtin_ia32_vpshrdq512: 4884 case X86::BI__builtin_ia32_vpshrdw128: 4885 case X86::BI__builtin_ia32_vpshrdw256: 4886 case X86::BI__builtin_ia32_vpshrdw512: 4887 i = 2; l = 0; u = 255; 4888 break; 4889 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4890 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4891 case X86::BI__builtin_ia32_fixupimmps512_mask: 4892 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4893 case X86::BI__builtin_ia32_fixupimmsd_mask: 4894 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4895 case X86::BI__builtin_ia32_fixupimmss_mask: 4896 case X86::BI__builtin_ia32_fixupimmss_maskz: 4897 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4898 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4899 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4900 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4901 case X86::BI__builtin_ia32_fixupimmps128_mask: 4902 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4903 case X86::BI__builtin_ia32_fixupimmps256_mask: 4904 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4905 case X86::BI__builtin_ia32_pternlogd512_mask: 4906 case X86::BI__builtin_ia32_pternlogd512_maskz: 4907 case X86::BI__builtin_ia32_pternlogq512_mask: 4908 case X86::BI__builtin_ia32_pternlogq512_maskz: 4909 case X86::BI__builtin_ia32_pternlogd128_mask: 4910 case X86::BI__builtin_ia32_pternlogd128_maskz: 4911 case X86::BI__builtin_ia32_pternlogd256_mask: 4912 case X86::BI__builtin_ia32_pternlogd256_maskz: 4913 case X86::BI__builtin_ia32_pternlogq128_mask: 4914 case X86::BI__builtin_ia32_pternlogq128_maskz: 4915 case X86::BI__builtin_ia32_pternlogq256_mask: 4916 case X86::BI__builtin_ia32_pternlogq256_maskz: 4917 i = 3; l = 0; u = 255; 4918 break; 4919 case X86::BI__builtin_ia32_gatherpfdpd: 4920 case X86::BI__builtin_ia32_gatherpfdps: 4921 case X86::BI__builtin_ia32_gatherpfqpd: 4922 case X86::BI__builtin_ia32_gatherpfqps: 4923 case X86::BI__builtin_ia32_scatterpfdpd: 4924 case X86::BI__builtin_ia32_scatterpfdps: 4925 case X86::BI__builtin_ia32_scatterpfqpd: 4926 case X86::BI__builtin_ia32_scatterpfqps: 4927 i = 4; l = 2; u = 3; 4928 break; 4929 case X86::BI__builtin_ia32_reducesd_mask: 4930 case X86::BI__builtin_ia32_reducess_mask: 4931 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4932 case X86::BI__builtin_ia32_rndscaless_round_mask: 4933 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4934 case X86::BI__builtin_ia32_reducesh_mask: 4935 i = 4; l = 0; u = 255; 4936 break; 4937 } 4938 4939 // Note that we don't force a hard error on the range check here, allowing 4940 // template-generated or macro-generated dead code to potentially have out-of- 4941 // range values. These need to code generate, but don't need to necessarily 4942 // make any sense. We use a warning that defaults to an error. 4943 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4944 } 4945 4946 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4947 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4948 /// Returns true when the format fits the function and the FormatStringInfo has 4949 /// been populated. 4950 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4951 FormatStringInfo *FSI) { 4952 FSI->HasVAListArg = Format->getFirstArg() == 0; 4953 FSI->FormatIdx = Format->getFormatIdx() - 1; 4954 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4955 4956 // The way the format attribute works in GCC, the implicit this argument 4957 // of member functions is counted. However, it doesn't appear in our own 4958 // lists, so decrement format_idx in that case. 4959 if (IsCXXMember) { 4960 if(FSI->FormatIdx == 0) 4961 return false; 4962 --FSI->FormatIdx; 4963 if (FSI->FirstDataArg != 0) 4964 --FSI->FirstDataArg; 4965 } 4966 return true; 4967 } 4968 4969 /// Checks if a the given expression evaluates to null. 4970 /// 4971 /// Returns true if the value evaluates to null. 4972 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4973 // If the expression has non-null type, it doesn't evaluate to null. 4974 if (auto nullability 4975 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4976 if (*nullability == NullabilityKind::NonNull) 4977 return false; 4978 } 4979 4980 // As a special case, transparent unions initialized with zero are 4981 // considered null for the purposes of the nonnull attribute. 4982 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4983 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4984 if (const CompoundLiteralExpr *CLE = 4985 dyn_cast<CompoundLiteralExpr>(Expr)) 4986 if (const InitListExpr *ILE = 4987 dyn_cast<InitListExpr>(CLE->getInitializer())) 4988 Expr = ILE->getInit(0); 4989 } 4990 4991 bool Result; 4992 return (!Expr->isValueDependent() && 4993 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4994 !Result); 4995 } 4996 4997 static void CheckNonNullArgument(Sema &S, 4998 const Expr *ArgExpr, 4999 SourceLocation CallSiteLoc) { 5000 if (CheckNonNullExpr(S, ArgExpr)) 5001 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 5002 S.PDiag(diag::warn_null_arg) 5003 << ArgExpr->getSourceRange()); 5004 } 5005 5006 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 5007 FormatStringInfo FSI; 5008 if ((GetFormatStringType(Format) == FST_NSString) && 5009 getFormatStringInfo(Format, false, &FSI)) { 5010 Idx = FSI.FormatIdx; 5011 return true; 5012 } 5013 return false; 5014 } 5015 5016 /// Diagnose use of %s directive in an NSString which is being passed 5017 /// as formatting string to formatting method. 5018 static void 5019 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 5020 const NamedDecl *FDecl, 5021 Expr **Args, 5022 unsigned NumArgs) { 5023 unsigned Idx = 0; 5024 bool Format = false; 5025 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 5026 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 5027 Idx = 2; 5028 Format = true; 5029 } 5030 else 5031 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 5032 if (S.GetFormatNSStringIdx(I, Idx)) { 5033 Format = true; 5034 break; 5035 } 5036 } 5037 if (!Format || NumArgs <= Idx) 5038 return; 5039 const Expr *FormatExpr = Args[Idx]; 5040 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 5041 FormatExpr = CSCE->getSubExpr(); 5042 const StringLiteral *FormatString; 5043 if (const ObjCStringLiteral *OSL = 5044 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 5045 FormatString = OSL->getString(); 5046 else 5047 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 5048 if (!FormatString) 5049 return; 5050 if (S.FormatStringHasSArg(FormatString)) { 5051 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 5052 << "%s" << 1 << 1; 5053 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 5054 << FDecl->getDeclName(); 5055 } 5056 } 5057 5058 /// Determine whether the given type has a non-null nullability annotation. 5059 static bool isNonNullType(ASTContext &ctx, QualType type) { 5060 if (auto nullability = type->getNullability(ctx)) 5061 return *nullability == NullabilityKind::NonNull; 5062 5063 return false; 5064 } 5065 5066 static void CheckNonNullArguments(Sema &S, 5067 const NamedDecl *FDecl, 5068 const FunctionProtoType *Proto, 5069 ArrayRef<const Expr *> Args, 5070 SourceLocation CallSiteLoc) { 5071 assert((FDecl || Proto) && "Need a function declaration or prototype"); 5072 5073 // Already checked by by constant evaluator. 5074 if (S.isConstantEvaluated()) 5075 return; 5076 // Check the attributes attached to the method/function itself. 5077 llvm::SmallBitVector NonNullArgs; 5078 if (FDecl) { 5079 // Handle the nonnull attribute on the function/method declaration itself. 5080 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 5081 if (!NonNull->args_size()) { 5082 // Easy case: all pointer arguments are nonnull. 5083 for (const auto *Arg : Args) 5084 if (S.isValidPointerAttrType(Arg->getType())) 5085 CheckNonNullArgument(S, Arg, CallSiteLoc); 5086 return; 5087 } 5088 5089 for (const ParamIdx &Idx : NonNull->args()) { 5090 unsigned IdxAST = Idx.getASTIndex(); 5091 if (IdxAST >= Args.size()) 5092 continue; 5093 if (NonNullArgs.empty()) 5094 NonNullArgs.resize(Args.size()); 5095 NonNullArgs.set(IdxAST); 5096 } 5097 } 5098 } 5099 5100 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 5101 // Handle the nonnull attribute on the parameters of the 5102 // function/method. 5103 ArrayRef<ParmVarDecl*> parms; 5104 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 5105 parms = FD->parameters(); 5106 else 5107 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 5108 5109 unsigned ParamIndex = 0; 5110 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 5111 I != E; ++I, ++ParamIndex) { 5112 const ParmVarDecl *PVD = *I; 5113 if (PVD->hasAttr<NonNullAttr>() || 5114 isNonNullType(S.Context, PVD->getType())) { 5115 if (NonNullArgs.empty()) 5116 NonNullArgs.resize(Args.size()); 5117 5118 NonNullArgs.set(ParamIndex); 5119 } 5120 } 5121 } else { 5122 // If we have a non-function, non-method declaration but no 5123 // function prototype, try to dig out the function prototype. 5124 if (!Proto) { 5125 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 5126 QualType type = VD->getType().getNonReferenceType(); 5127 if (auto pointerType = type->getAs<PointerType>()) 5128 type = pointerType->getPointeeType(); 5129 else if (auto blockType = type->getAs<BlockPointerType>()) 5130 type = blockType->getPointeeType(); 5131 // FIXME: data member pointers? 5132 5133 // Dig out the function prototype, if there is one. 5134 Proto = type->getAs<FunctionProtoType>(); 5135 } 5136 } 5137 5138 // Fill in non-null argument information from the nullability 5139 // information on the parameter types (if we have them). 5140 if (Proto) { 5141 unsigned Index = 0; 5142 for (auto paramType : Proto->getParamTypes()) { 5143 if (isNonNullType(S.Context, paramType)) { 5144 if (NonNullArgs.empty()) 5145 NonNullArgs.resize(Args.size()); 5146 5147 NonNullArgs.set(Index); 5148 } 5149 5150 ++Index; 5151 } 5152 } 5153 } 5154 5155 // Check for non-null arguments. 5156 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 5157 ArgIndex != ArgIndexEnd; ++ArgIndex) { 5158 if (NonNullArgs[ArgIndex]) 5159 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 5160 } 5161 } 5162 5163 /// Warn if a pointer or reference argument passed to a function points to an 5164 /// object that is less aligned than the parameter. This can happen when 5165 /// creating a typedef with a lower alignment than the original type and then 5166 /// calling functions defined in terms of the original type. 5167 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 5168 StringRef ParamName, QualType ArgTy, 5169 QualType ParamTy) { 5170 5171 // If a function accepts a pointer or reference type 5172 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 5173 return; 5174 5175 // If the parameter is a pointer type, get the pointee type for the 5176 // argument too. If the parameter is a reference type, don't try to get 5177 // the pointee type for the argument. 5178 if (ParamTy->isPointerType()) 5179 ArgTy = ArgTy->getPointeeType(); 5180 5181 // Remove reference or pointer 5182 ParamTy = ParamTy->getPointeeType(); 5183 5184 // Find expected alignment, and the actual alignment of the passed object. 5185 // getTypeAlignInChars requires complete types 5186 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 5187 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 5188 ArgTy->isUndeducedType()) 5189 return; 5190 5191 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 5192 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 5193 5194 // If the argument is less aligned than the parameter, there is a 5195 // potential alignment issue. 5196 if (ArgAlign < ParamAlign) 5197 Diag(Loc, diag::warn_param_mismatched_alignment) 5198 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 5199 << ParamName << (FDecl != nullptr) << FDecl; 5200 } 5201 5202 /// Handles the checks for format strings, non-POD arguments to vararg 5203 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 5204 /// attributes. 5205 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 5206 const Expr *ThisArg, ArrayRef<const Expr *> Args, 5207 bool IsMemberFunction, SourceLocation Loc, 5208 SourceRange Range, VariadicCallType CallType) { 5209 // FIXME: We should check as much as we can in the template definition. 5210 if (CurContext->isDependentContext()) 5211 return; 5212 5213 // Printf and scanf checking. 5214 llvm::SmallBitVector CheckedVarArgs; 5215 if (FDecl) { 5216 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 5217 // Only create vector if there are format attributes. 5218 CheckedVarArgs.resize(Args.size()); 5219 5220 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 5221 CheckedVarArgs); 5222 } 5223 } 5224 5225 // Refuse POD arguments that weren't caught by the format string 5226 // checks above. 5227 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 5228 if (CallType != VariadicDoesNotApply && 5229 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 5230 unsigned NumParams = Proto ? Proto->getNumParams() 5231 : FDecl && isa<FunctionDecl>(FDecl) 5232 ? cast<FunctionDecl>(FDecl)->getNumParams() 5233 : FDecl && isa<ObjCMethodDecl>(FDecl) 5234 ? cast<ObjCMethodDecl>(FDecl)->param_size() 5235 : 0; 5236 5237 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 5238 // Args[ArgIdx] can be null in malformed code. 5239 if (const Expr *Arg = Args[ArgIdx]) { 5240 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 5241 checkVariadicArgument(Arg, CallType); 5242 } 5243 } 5244 } 5245 5246 if (FDecl || Proto) { 5247 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 5248 5249 // Type safety checking. 5250 if (FDecl) { 5251 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 5252 CheckArgumentWithTypeTag(I, Args, Loc); 5253 } 5254 } 5255 5256 // Check that passed arguments match the alignment of original arguments. 5257 // Try to get the missing prototype from the declaration. 5258 if (!Proto && FDecl) { 5259 const auto *FT = FDecl->getFunctionType(); 5260 if (isa_and_nonnull<FunctionProtoType>(FT)) 5261 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 5262 } 5263 if (Proto) { 5264 // For variadic functions, we may have more args than parameters. 5265 // For some K&R functions, we may have less args than parameters. 5266 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 5267 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 5268 // Args[ArgIdx] can be null in malformed code. 5269 if (const Expr *Arg = Args[ArgIdx]) { 5270 if (Arg->containsErrors()) 5271 continue; 5272 5273 QualType ParamTy = Proto->getParamType(ArgIdx); 5274 QualType ArgTy = Arg->getType(); 5275 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 5276 ArgTy, ParamTy); 5277 } 5278 } 5279 } 5280 5281 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 5282 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 5283 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 5284 if (!Arg->isValueDependent()) { 5285 Expr::EvalResult Align; 5286 if (Arg->EvaluateAsInt(Align, Context)) { 5287 const llvm::APSInt &I = Align.Val.getInt(); 5288 if (!I.isPowerOf2()) 5289 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 5290 << Arg->getSourceRange(); 5291 5292 if (I > Sema::MaximumAlignment) 5293 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 5294 << Arg->getSourceRange() << Sema::MaximumAlignment; 5295 } 5296 } 5297 } 5298 5299 if (FD) 5300 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 5301 } 5302 5303 /// CheckConstructorCall - Check a constructor call for correctness and safety 5304 /// properties not enforced by the C type system. 5305 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 5306 ArrayRef<const Expr *> Args, 5307 const FunctionProtoType *Proto, 5308 SourceLocation Loc) { 5309 VariadicCallType CallType = 5310 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 5311 5312 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 5313 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 5314 Context.getPointerType(Ctor->getThisObjectType())); 5315 5316 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 5317 Loc, SourceRange(), CallType); 5318 } 5319 5320 /// CheckFunctionCall - Check a direct function call for various correctness 5321 /// and safety properties not strictly enforced by the C type system. 5322 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 5323 const FunctionProtoType *Proto) { 5324 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 5325 isa<CXXMethodDecl>(FDecl); 5326 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 5327 IsMemberOperatorCall; 5328 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 5329 TheCall->getCallee()); 5330 Expr** Args = TheCall->getArgs(); 5331 unsigned NumArgs = TheCall->getNumArgs(); 5332 5333 Expr *ImplicitThis = nullptr; 5334 if (IsMemberOperatorCall) { 5335 // If this is a call to a member operator, hide the first argument 5336 // from checkCall. 5337 // FIXME: Our choice of AST representation here is less than ideal. 5338 ImplicitThis = Args[0]; 5339 ++Args; 5340 --NumArgs; 5341 } else if (IsMemberFunction) 5342 ImplicitThis = 5343 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 5344 5345 if (ImplicitThis) { 5346 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 5347 // used. 5348 QualType ThisType = ImplicitThis->getType(); 5349 if (!ThisType->isPointerType()) { 5350 assert(!ThisType->isReferenceType()); 5351 ThisType = Context.getPointerType(ThisType); 5352 } 5353 5354 QualType ThisTypeFromDecl = 5355 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 5356 5357 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 5358 ThisTypeFromDecl); 5359 } 5360 5361 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 5362 IsMemberFunction, TheCall->getRParenLoc(), 5363 TheCall->getCallee()->getSourceRange(), CallType); 5364 5365 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5366 // None of the checks below are needed for functions that don't have 5367 // simple names (e.g., C++ conversion functions). 5368 if (!FnInfo) 5369 return false; 5370 5371 CheckTCBEnforcement(TheCall, FDecl); 5372 5373 CheckAbsoluteValueFunction(TheCall, FDecl); 5374 CheckMaxUnsignedZero(TheCall, FDecl); 5375 5376 if (getLangOpts().ObjC) 5377 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 5378 5379 unsigned CMId = FDecl->getMemoryFunctionKind(); 5380 5381 // Handle memory setting and copying functions. 5382 switch (CMId) { 5383 case 0: 5384 return false; 5385 case Builtin::BIstrlcpy: // fallthrough 5386 case Builtin::BIstrlcat: 5387 CheckStrlcpycatArguments(TheCall, FnInfo); 5388 break; 5389 case Builtin::BIstrncat: 5390 CheckStrncatArguments(TheCall, FnInfo); 5391 break; 5392 case Builtin::BIfree: 5393 CheckFreeArguments(TheCall); 5394 break; 5395 default: 5396 CheckMemaccessArguments(TheCall, CMId, FnInfo); 5397 } 5398 5399 return false; 5400 } 5401 5402 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 5403 ArrayRef<const Expr *> Args) { 5404 VariadicCallType CallType = 5405 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 5406 5407 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 5408 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 5409 CallType); 5410 5411 return false; 5412 } 5413 5414 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 5415 const FunctionProtoType *Proto) { 5416 QualType Ty; 5417 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 5418 Ty = V->getType().getNonReferenceType(); 5419 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 5420 Ty = F->getType().getNonReferenceType(); 5421 else 5422 return false; 5423 5424 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 5425 !Ty->isFunctionProtoType()) 5426 return false; 5427 5428 VariadicCallType CallType; 5429 if (!Proto || !Proto->isVariadic()) { 5430 CallType = VariadicDoesNotApply; 5431 } else if (Ty->isBlockPointerType()) { 5432 CallType = VariadicBlock; 5433 } else { // Ty->isFunctionPointerType() 5434 CallType = VariadicFunction; 5435 } 5436 5437 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 5438 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5439 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5440 TheCall->getCallee()->getSourceRange(), CallType); 5441 5442 return false; 5443 } 5444 5445 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 5446 /// such as function pointers returned from functions. 5447 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 5448 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 5449 TheCall->getCallee()); 5450 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 5451 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5452 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5453 TheCall->getCallee()->getSourceRange(), CallType); 5454 5455 return false; 5456 } 5457 5458 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 5459 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 5460 return false; 5461 5462 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 5463 switch (Op) { 5464 case AtomicExpr::AO__c11_atomic_init: 5465 case AtomicExpr::AO__opencl_atomic_init: 5466 llvm_unreachable("There is no ordering argument for an init"); 5467 5468 case AtomicExpr::AO__c11_atomic_load: 5469 case AtomicExpr::AO__opencl_atomic_load: 5470 case AtomicExpr::AO__hip_atomic_load: 5471 case AtomicExpr::AO__atomic_load_n: 5472 case AtomicExpr::AO__atomic_load: 5473 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5474 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5475 5476 case AtomicExpr::AO__c11_atomic_store: 5477 case AtomicExpr::AO__opencl_atomic_store: 5478 case AtomicExpr::AO__hip_atomic_store: 5479 case AtomicExpr::AO__atomic_store: 5480 case AtomicExpr::AO__atomic_store_n: 5481 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5482 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5483 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5484 5485 default: 5486 return true; 5487 } 5488 } 5489 5490 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5491 AtomicExpr::AtomicOp Op) { 5492 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5493 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5494 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5495 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5496 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5497 Op); 5498 } 5499 5500 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5501 SourceLocation RParenLoc, MultiExprArg Args, 5502 AtomicExpr::AtomicOp Op, 5503 AtomicArgumentOrder ArgOrder) { 5504 // All the non-OpenCL operations take one of the following forms. 5505 // The OpenCL operations take the __c11 forms with one extra argument for 5506 // synchronization scope. 5507 enum { 5508 // C __c11_atomic_init(A *, C) 5509 Init, 5510 5511 // C __c11_atomic_load(A *, int) 5512 Load, 5513 5514 // void __atomic_load(A *, CP, int) 5515 LoadCopy, 5516 5517 // void __atomic_store(A *, CP, int) 5518 Copy, 5519 5520 // C __c11_atomic_add(A *, M, int) 5521 Arithmetic, 5522 5523 // C __atomic_exchange_n(A *, CP, int) 5524 Xchg, 5525 5526 // void __atomic_exchange(A *, C *, CP, int) 5527 GNUXchg, 5528 5529 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 5530 C11CmpXchg, 5531 5532 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 5533 GNUCmpXchg 5534 } Form = Init; 5535 5536 const unsigned NumForm = GNUCmpXchg + 1; 5537 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 5538 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 5539 // where: 5540 // C is an appropriate type, 5541 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 5542 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 5543 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 5544 // the int parameters are for orderings. 5545 5546 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 5547 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 5548 "need to update code for modified forms"); 5549 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 5550 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 5551 AtomicExpr::AO__atomic_load, 5552 "need to update code for modified C11 atomics"); 5553 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 5554 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 5555 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load && 5556 Op <= AtomicExpr::AO__hip_atomic_fetch_max; 5557 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 5558 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 5559 IsOpenCL; 5560 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 5561 Op == AtomicExpr::AO__atomic_store_n || 5562 Op == AtomicExpr::AO__atomic_exchange_n || 5563 Op == AtomicExpr::AO__atomic_compare_exchange_n; 5564 bool IsAddSub = false; 5565 5566 switch (Op) { 5567 case AtomicExpr::AO__c11_atomic_init: 5568 case AtomicExpr::AO__opencl_atomic_init: 5569 Form = Init; 5570 break; 5571 5572 case AtomicExpr::AO__c11_atomic_load: 5573 case AtomicExpr::AO__opencl_atomic_load: 5574 case AtomicExpr::AO__hip_atomic_load: 5575 case AtomicExpr::AO__atomic_load_n: 5576 Form = Load; 5577 break; 5578 5579 case AtomicExpr::AO__atomic_load: 5580 Form = LoadCopy; 5581 break; 5582 5583 case AtomicExpr::AO__c11_atomic_store: 5584 case AtomicExpr::AO__opencl_atomic_store: 5585 case AtomicExpr::AO__hip_atomic_store: 5586 case AtomicExpr::AO__atomic_store: 5587 case AtomicExpr::AO__atomic_store_n: 5588 Form = Copy; 5589 break; 5590 case AtomicExpr::AO__hip_atomic_fetch_add: 5591 case AtomicExpr::AO__hip_atomic_fetch_min: 5592 case AtomicExpr::AO__hip_atomic_fetch_max: 5593 case AtomicExpr::AO__c11_atomic_fetch_add: 5594 case AtomicExpr::AO__c11_atomic_fetch_sub: 5595 case AtomicExpr::AO__opencl_atomic_fetch_add: 5596 case AtomicExpr::AO__opencl_atomic_fetch_sub: 5597 case AtomicExpr::AO__atomic_fetch_add: 5598 case AtomicExpr::AO__atomic_fetch_sub: 5599 case AtomicExpr::AO__atomic_add_fetch: 5600 case AtomicExpr::AO__atomic_sub_fetch: 5601 IsAddSub = true; 5602 Form = Arithmetic; 5603 break; 5604 case AtomicExpr::AO__c11_atomic_fetch_and: 5605 case AtomicExpr::AO__c11_atomic_fetch_or: 5606 case AtomicExpr::AO__c11_atomic_fetch_xor: 5607 case AtomicExpr::AO__hip_atomic_fetch_and: 5608 case AtomicExpr::AO__hip_atomic_fetch_or: 5609 case AtomicExpr::AO__hip_atomic_fetch_xor: 5610 case AtomicExpr::AO__c11_atomic_fetch_nand: 5611 case AtomicExpr::AO__opencl_atomic_fetch_and: 5612 case AtomicExpr::AO__opencl_atomic_fetch_or: 5613 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5614 case AtomicExpr::AO__atomic_fetch_and: 5615 case AtomicExpr::AO__atomic_fetch_or: 5616 case AtomicExpr::AO__atomic_fetch_xor: 5617 case AtomicExpr::AO__atomic_fetch_nand: 5618 case AtomicExpr::AO__atomic_and_fetch: 5619 case AtomicExpr::AO__atomic_or_fetch: 5620 case AtomicExpr::AO__atomic_xor_fetch: 5621 case AtomicExpr::AO__atomic_nand_fetch: 5622 Form = Arithmetic; 5623 break; 5624 case AtomicExpr::AO__c11_atomic_fetch_min: 5625 case AtomicExpr::AO__c11_atomic_fetch_max: 5626 case AtomicExpr::AO__opencl_atomic_fetch_min: 5627 case AtomicExpr::AO__opencl_atomic_fetch_max: 5628 case AtomicExpr::AO__atomic_min_fetch: 5629 case AtomicExpr::AO__atomic_max_fetch: 5630 case AtomicExpr::AO__atomic_fetch_min: 5631 case AtomicExpr::AO__atomic_fetch_max: 5632 Form = Arithmetic; 5633 break; 5634 5635 case AtomicExpr::AO__c11_atomic_exchange: 5636 case AtomicExpr::AO__hip_atomic_exchange: 5637 case AtomicExpr::AO__opencl_atomic_exchange: 5638 case AtomicExpr::AO__atomic_exchange_n: 5639 Form = Xchg; 5640 break; 5641 5642 case AtomicExpr::AO__atomic_exchange: 5643 Form = GNUXchg; 5644 break; 5645 5646 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5647 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5648 case AtomicExpr::AO__hip_atomic_compare_exchange_strong: 5649 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5650 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5651 case AtomicExpr::AO__hip_atomic_compare_exchange_weak: 5652 Form = C11CmpXchg; 5653 break; 5654 5655 case AtomicExpr::AO__atomic_compare_exchange: 5656 case AtomicExpr::AO__atomic_compare_exchange_n: 5657 Form = GNUCmpXchg; 5658 break; 5659 } 5660 5661 unsigned AdjustedNumArgs = NumArgs[Form]; 5662 if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init) 5663 ++AdjustedNumArgs; 5664 // Check we have the right number of arguments. 5665 if (Args.size() < AdjustedNumArgs) { 5666 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5667 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5668 << ExprRange; 5669 return ExprError(); 5670 } else if (Args.size() > AdjustedNumArgs) { 5671 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5672 diag::err_typecheck_call_too_many_args) 5673 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5674 << ExprRange; 5675 return ExprError(); 5676 } 5677 5678 // Inspect the first argument of the atomic operation. 5679 Expr *Ptr = Args[0]; 5680 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5681 if (ConvertedPtr.isInvalid()) 5682 return ExprError(); 5683 5684 Ptr = ConvertedPtr.get(); 5685 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5686 if (!pointerType) { 5687 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5688 << Ptr->getType() << Ptr->getSourceRange(); 5689 return ExprError(); 5690 } 5691 5692 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5693 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5694 QualType ValType = AtomTy; // 'C' 5695 if (IsC11) { 5696 if (!AtomTy->isAtomicType()) { 5697 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5698 << Ptr->getType() << Ptr->getSourceRange(); 5699 return ExprError(); 5700 } 5701 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5702 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5703 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5704 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5705 << Ptr->getSourceRange(); 5706 return ExprError(); 5707 } 5708 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5709 } else if (Form != Load && Form != LoadCopy) { 5710 if (ValType.isConstQualified()) { 5711 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5712 << Ptr->getType() << Ptr->getSourceRange(); 5713 return ExprError(); 5714 } 5715 } 5716 5717 // For an arithmetic operation, the implied arithmetic must be well-formed. 5718 if (Form == Arithmetic) { 5719 // GCC does not enforce these rules for GNU atomics, but we do to help catch 5720 // trivial type errors. 5721 auto IsAllowedValueType = [&](QualType ValType) { 5722 if (ValType->isIntegerType()) 5723 return true; 5724 if (ValType->isPointerType()) 5725 return true; 5726 if (!ValType->isFloatingType()) 5727 return false; 5728 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5729 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5730 &Context.getTargetInfo().getLongDoubleFormat() == 5731 &llvm::APFloat::x87DoubleExtended()) 5732 return false; 5733 return true; 5734 }; 5735 if (IsAddSub && !IsAllowedValueType(ValType)) { 5736 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5737 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5738 return ExprError(); 5739 } 5740 if (!IsAddSub && !ValType->isIntegerType()) { 5741 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5742 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5743 return ExprError(); 5744 } 5745 if (IsC11 && ValType->isPointerType() && 5746 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5747 diag::err_incomplete_type)) { 5748 return ExprError(); 5749 } 5750 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5751 // For __atomic_*_n operations, the value type must be a scalar integral or 5752 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5753 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5754 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5755 return ExprError(); 5756 } 5757 5758 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5759 !AtomTy->isScalarType()) { 5760 // For GNU atomics, require a trivially-copyable type. This is not part of 5761 // the GNU atomics specification but we enforce it for consistency with 5762 // other atomics which generally all require a trivially-copyable type. This 5763 // is because atomics just copy bits. 5764 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5765 << Ptr->getType() << Ptr->getSourceRange(); 5766 return ExprError(); 5767 } 5768 5769 switch (ValType.getObjCLifetime()) { 5770 case Qualifiers::OCL_None: 5771 case Qualifiers::OCL_ExplicitNone: 5772 // okay 5773 break; 5774 5775 case Qualifiers::OCL_Weak: 5776 case Qualifiers::OCL_Strong: 5777 case Qualifiers::OCL_Autoreleasing: 5778 // FIXME: Can this happen? By this point, ValType should be known 5779 // to be trivially copyable. 5780 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5781 << ValType << Ptr->getSourceRange(); 5782 return ExprError(); 5783 } 5784 5785 // All atomic operations have an overload which takes a pointer to a volatile 5786 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5787 // into the result or the other operands. Similarly atomic_load takes a 5788 // pointer to a const 'A'. 5789 ValType.removeLocalVolatile(); 5790 ValType.removeLocalConst(); 5791 QualType ResultType = ValType; 5792 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5793 Form == Init) 5794 ResultType = Context.VoidTy; 5795 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5796 ResultType = Context.BoolTy; 5797 5798 // The type of a parameter passed 'by value'. In the GNU atomics, such 5799 // arguments are actually passed as pointers. 5800 QualType ByValType = ValType; // 'CP' 5801 bool IsPassedByAddress = false; 5802 if (!IsC11 && !IsHIP && !IsN) { 5803 ByValType = Ptr->getType(); 5804 IsPassedByAddress = true; 5805 } 5806 5807 SmallVector<Expr *, 5> APIOrderedArgs; 5808 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5809 APIOrderedArgs.push_back(Args[0]); 5810 switch (Form) { 5811 case Init: 5812 case Load: 5813 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5814 break; 5815 case LoadCopy: 5816 case Copy: 5817 case Arithmetic: 5818 case Xchg: 5819 APIOrderedArgs.push_back(Args[2]); // Val1 5820 APIOrderedArgs.push_back(Args[1]); // Order 5821 break; 5822 case GNUXchg: 5823 APIOrderedArgs.push_back(Args[2]); // Val1 5824 APIOrderedArgs.push_back(Args[3]); // Val2 5825 APIOrderedArgs.push_back(Args[1]); // Order 5826 break; 5827 case C11CmpXchg: 5828 APIOrderedArgs.push_back(Args[2]); // Val1 5829 APIOrderedArgs.push_back(Args[4]); // Val2 5830 APIOrderedArgs.push_back(Args[1]); // Order 5831 APIOrderedArgs.push_back(Args[3]); // OrderFail 5832 break; 5833 case GNUCmpXchg: 5834 APIOrderedArgs.push_back(Args[2]); // Val1 5835 APIOrderedArgs.push_back(Args[4]); // Val2 5836 APIOrderedArgs.push_back(Args[5]); // Weak 5837 APIOrderedArgs.push_back(Args[1]); // Order 5838 APIOrderedArgs.push_back(Args[3]); // OrderFail 5839 break; 5840 } 5841 } else 5842 APIOrderedArgs.append(Args.begin(), Args.end()); 5843 5844 // The first argument's non-CV pointer type is used to deduce the type of 5845 // subsequent arguments, except for: 5846 // - weak flag (always converted to bool) 5847 // - memory order (always converted to int) 5848 // - scope (always converted to int) 5849 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5850 QualType Ty; 5851 if (i < NumVals[Form] + 1) { 5852 switch (i) { 5853 case 0: 5854 // The first argument is always a pointer. It has a fixed type. 5855 // It is always dereferenced, a nullptr is undefined. 5856 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5857 // Nothing else to do: we already know all we want about this pointer. 5858 continue; 5859 case 1: 5860 // The second argument is the non-atomic operand. For arithmetic, this 5861 // is always passed by value, and for a compare_exchange it is always 5862 // passed by address. For the rest, GNU uses by-address and C11 uses 5863 // by-value. 5864 assert(Form != Load); 5865 if (Form == Arithmetic && ValType->isPointerType()) 5866 Ty = Context.getPointerDiffType(); 5867 else if (Form == Init || Form == Arithmetic) 5868 Ty = ValType; 5869 else if (Form == Copy || Form == Xchg) { 5870 if (IsPassedByAddress) { 5871 // The value pointer is always dereferenced, a nullptr is undefined. 5872 CheckNonNullArgument(*this, APIOrderedArgs[i], 5873 ExprRange.getBegin()); 5874 } 5875 Ty = ByValType; 5876 } else { 5877 Expr *ValArg = APIOrderedArgs[i]; 5878 // The value pointer is always dereferenced, a nullptr is undefined. 5879 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5880 LangAS AS = LangAS::Default; 5881 // Keep address space of non-atomic pointer type. 5882 if (const PointerType *PtrTy = 5883 ValArg->getType()->getAs<PointerType>()) { 5884 AS = PtrTy->getPointeeType().getAddressSpace(); 5885 } 5886 Ty = Context.getPointerType( 5887 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5888 } 5889 break; 5890 case 2: 5891 // The third argument to compare_exchange / GNU exchange is the desired 5892 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5893 if (IsPassedByAddress) 5894 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5895 Ty = ByValType; 5896 break; 5897 case 3: 5898 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5899 Ty = Context.BoolTy; 5900 break; 5901 } 5902 } else { 5903 // The order(s) and scope are always converted to int. 5904 Ty = Context.IntTy; 5905 } 5906 5907 InitializedEntity Entity = 5908 InitializedEntity::InitializeParameter(Context, Ty, false); 5909 ExprResult Arg = APIOrderedArgs[i]; 5910 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5911 if (Arg.isInvalid()) 5912 return true; 5913 APIOrderedArgs[i] = Arg.get(); 5914 } 5915 5916 // Permute the arguments into a 'consistent' order. 5917 SmallVector<Expr*, 5> SubExprs; 5918 SubExprs.push_back(Ptr); 5919 switch (Form) { 5920 case Init: 5921 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5922 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5923 break; 5924 case Load: 5925 SubExprs.push_back(APIOrderedArgs[1]); // Order 5926 break; 5927 case LoadCopy: 5928 case Copy: 5929 case Arithmetic: 5930 case Xchg: 5931 SubExprs.push_back(APIOrderedArgs[2]); // Order 5932 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5933 break; 5934 case GNUXchg: 5935 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5936 SubExprs.push_back(APIOrderedArgs[3]); // Order 5937 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5938 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5939 break; 5940 case C11CmpXchg: 5941 SubExprs.push_back(APIOrderedArgs[3]); // Order 5942 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5943 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5944 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5945 break; 5946 case GNUCmpXchg: 5947 SubExprs.push_back(APIOrderedArgs[4]); // Order 5948 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5949 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5950 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5951 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5952 break; 5953 } 5954 5955 if (SubExprs.size() >= 2 && Form != Init) { 5956 if (Optional<llvm::APSInt> Result = 5957 SubExprs[1]->getIntegerConstantExpr(Context)) 5958 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5959 Diag(SubExprs[1]->getBeginLoc(), 5960 diag::warn_atomic_op_has_invalid_memory_order) 5961 << SubExprs[1]->getSourceRange(); 5962 } 5963 5964 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5965 auto *Scope = Args[Args.size() - 1]; 5966 if (Optional<llvm::APSInt> Result = 5967 Scope->getIntegerConstantExpr(Context)) { 5968 if (!ScopeModel->isValid(Result->getZExtValue())) 5969 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5970 << Scope->getSourceRange(); 5971 } 5972 SubExprs.push_back(Scope); 5973 } 5974 5975 AtomicExpr *AE = new (Context) 5976 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5977 5978 if ((Op == AtomicExpr::AO__c11_atomic_load || 5979 Op == AtomicExpr::AO__c11_atomic_store || 5980 Op == AtomicExpr::AO__opencl_atomic_load || 5981 Op == AtomicExpr::AO__hip_atomic_load || 5982 Op == AtomicExpr::AO__opencl_atomic_store || 5983 Op == AtomicExpr::AO__hip_atomic_store) && 5984 Context.AtomicUsesUnsupportedLibcall(AE)) 5985 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5986 << ((Op == AtomicExpr::AO__c11_atomic_load || 5987 Op == AtomicExpr::AO__opencl_atomic_load || 5988 Op == AtomicExpr::AO__hip_atomic_load) 5989 ? 0 5990 : 1); 5991 5992 if (ValType->isBitIntType()) { 5993 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit); 5994 return ExprError(); 5995 } 5996 5997 return AE; 5998 } 5999 6000 /// checkBuiltinArgument - Given a call to a builtin function, perform 6001 /// normal type-checking on the given argument, updating the call in 6002 /// place. This is useful when a builtin function requires custom 6003 /// type-checking for some of its arguments but not necessarily all of 6004 /// them. 6005 /// 6006 /// Returns true on error. 6007 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 6008 FunctionDecl *Fn = E->getDirectCallee(); 6009 assert(Fn && "builtin call without direct callee!"); 6010 6011 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 6012 InitializedEntity Entity = 6013 InitializedEntity::InitializeParameter(S.Context, Param); 6014 6015 ExprResult Arg = E->getArg(0); 6016 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 6017 if (Arg.isInvalid()) 6018 return true; 6019 6020 E->setArg(ArgIndex, Arg.get()); 6021 return false; 6022 } 6023 6024 /// We have a call to a function like __sync_fetch_and_add, which is an 6025 /// overloaded function based on the pointer type of its first argument. 6026 /// The main BuildCallExpr routines have already promoted the types of 6027 /// arguments because all of these calls are prototyped as void(...). 6028 /// 6029 /// This function goes through and does final semantic checking for these 6030 /// builtins, as well as generating any warnings. 6031 ExprResult 6032 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 6033 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 6034 Expr *Callee = TheCall->getCallee(); 6035 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 6036 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6037 6038 // Ensure that we have at least one argument to do type inference from. 6039 if (TheCall->getNumArgs() < 1) { 6040 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6041 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 6042 return ExprError(); 6043 } 6044 6045 // Inspect the first argument of the atomic builtin. This should always be 6046 // a pointer type, whose element is an integral scalar or pointer type. 6047 // Because it is a pointer type, we don't have to worry about any implicit 6048 // casts here. 6049 // FIXME: We don't allow floating point scalars as input. 6050 Expr *FirstArg = TheCall->getArg(0); 6051 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 6052 if (FirstArgResult.isInvalid()) 6053 return ExprError(); 6054 FirstArg = FirstArgResult.get(); 6055 TheCall->setArg(0, FirstArg); 6056 6057 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 6058 if (!pointerType) { 6059 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 6060 << FirstArg->getType() << FirstArg->getSourceRange(); 6061 return ExprError(); 6062 } 6063 6064 QualType ValType = pointerType->getPointeeType(); 6065 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6066 !ValType->isBlockPointerType()) { 6067 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 6068 << FirstArg->getType() << FirstArg->getSourceRange(); 6069 return ExprError(); 6070 } 6071 6072 if (ValType.isConstQualified()) { 6073 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 6074 << FirstArg->getType() << FirstArg->getSourceRange(); 6075 return ExprError(); 6076 } 6077 6078 switch (ValType.getObjCLifetime()) { 6079 case Qualifiers::OCL_None: 6080 case Qualifiers::OCL_ExplicitNone: 6081 // okay 6082 break; 6083 6084 case Qualifiers::OCL_Weak: 6085 case Qualifiers::OCL_Strong: 6086 case Qualifiers::OCL_Autoreleasing: 6087 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 6088 << ValType << FirstArg->getSourceRange(); 6089 return ExprError(); 6090 } 6091 6092 // Strip any qualifiers off ValType. 6093 ValType = ValType.getUnqualifiedType(); 6094 6095 // The majority of builtins return a value, but a few have special return 6096 // types, so allow them to override appropriately below. 6097 QualType ResultType = ValType; 6098 6099 // We need to figure out which concrete builtin this maps onto. For example, 6100 // __sync_fetch_and_add with a 2 byte object turns into 6101 // __sync_fetch_and_add_2. 6102 #define BUILTIN_ROW(x) \ 6103 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 6104 Builtin::BI##x##_8, Builtin::BI##x##_16 } 6105 6106 static const unsigned BuiltinIndices[][5] = { 6107 BUILTIN_ROW(__sync_fetch_and_add), 6108 BUILTIN_ROW(__sync_fetch_and_sub), 6109 BUILTIN_ROW(__sync_fetch_and_or), 6110 BUILTIN_ROW(__sync_fetch_and_and), 6111 BUILTIN_ROW(__sync_fetch_and_xor), 6112 BUILTIN_ROW(__sync_fetch_and_nand), 6113 6114 BUILTIN_ROW(__sync_add_and_fetch), 6115 BUILTIN_ROW(__sync_sub_and_fetch), 6116 BUILTIN_ROW(__sync_and_and_fetch), 6117 BUILTIN_ROW(__sync_or_and_fetch), 6118 BUILTIN_ROW(__sync_xor_and_fetch), 6119 BUILTIN_ROW(__sync_nand_and_fetch), 6120 6121 BUILTIN_ROW(__sync_val_compare_and_swap), 6122 BUILTIN_ROW(__sync_bool_compare_and_swap), 6123 BUILTIN_ROW(__sync_lock_test_and_set), 6124 BUILTIN_ROW(__sync_lock_release), 6125 BUILTIN_ROW(__sync_swap) 6126 }; 6127 #undef BUILTIN_ROW 6128 6129 // Determine the index of the size. 6130 unsigned SizeIndex; 6131 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 6132 case 1: SizeIndex = 0; break; 6133 case 2: SizeIndex = 1; break; 6134 case 4: SizeIndex = 2; break; 6135 case 8: SizeIndex = 3; break; 6136 case 16: SizeIndex = 4; break; 6137 default: 6138 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 6139 << FirstArg->getType() << FirstArg->getSourceRange(); 6140 return ExprError(); 6141 } 6142 6143 // Each of these builtins has one pointer argument, followed by some number of 6144 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 6145 // that we ignore. Find out which row of BuiltinIndices to read from as well 6146 // as the number of fixed args. 6147 unsigned BuiltinID = FDecl->getBuiltinID(); 6148 unsigned BuiltinIndex, NumFixed = 1; 6149 bool WarnAboutSemanticsChange = false; 6150 switch (BuiltinID) { 6151 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 6152 case Builtin::BI__sync_fetch_and_add: 6153 case Builtin::BI__sync_fetch_and_add_1: 6154 case Builtin::BI__sync_fetch_and_add_2: 6155 case Builtin::BI__sync_fetch_and_add_4: 6156 case Builtin::BI__sync_fetch_and_add_8: 6157 case Builtin::BI__sync_fetch_and_add_16: 6158 BuiltinIndex = 0; 6159 break; 6160 6161 case Builtin::BI__sync_fetch_and_sub: 6162 case Builtin::BI__sync_fetch_and_sub_1: 6163 case Builtin::BI__sync_fetch_and_sub_2: 6164 case Builtin::BI__sync_fetch_and_sub_4: 6165 case Builtin::BI__sync_fetch_and_sub_8: 6166 case Builtin::BI__sync_fetch_and_sub_16: 6167 BuiltinIndex = 1; 6168 break; 6169 6170 case Builtin::BI__sync_fetch_and_or: 6171 case Builtin::BI__sync_fetch_and_or_1: 6172 case Builtin::BI__sync_fetch_and_or_2: 6173 case Builtin::BI__sync_fetch_and_or_4: 6174 case Builtin::BI__sync_fetch_and_or_8: 6175 case Builtin::BI__sync_fetch_and_or_16: 6176 BuiltinIndex = 2; 6177 break; 6178 6179 case Builtin::BI__sync_fetch_and_and: 6180 case Builtin::BI__sync_fetch_and_and_1: 6181 case Builtin::BI__sync_fetch_and_and_2: 6182 case Builtin::BI__sync_fetch_and_and_4: 6183 case Builtin::BI__sync_fetch_and_and_8: 6184 case Builtin::BI__sync_fetch_and_and_16: 6185 BuiltinIndex = 3; 6186 break; 6187 6188 case Builtin::BI__sync_fetch_and_xor: 6189 case Builtin::BI__sync_fetch_and_xor_1: 6190 case Builtin::BI__sync_fetch_and_xor_2: 6191 case Builtin::BI__sync_fetch_and_xor_4: 6192 case Builtin::BI__sync_fetch_and_xor_8: 6193 case Builtin::BI__sync_fetch_and_xor_16: 6194 BuiltinIndex = 4; 6195 break; 6196 6197 case Builtin::BI__sync_fetch_and_nand: 6198 case Builtin::BI__sync_fetch_and_nand_1: 6199 case Builtin::BI__sync_fetch_and_nand_2: 6200 case Builtin::BI__sync_fetch_and_nand_4: 6201 case Builtin::BI__sync_fetch_and_nand_8: 6202 case Builtin::BI__sync_fetch_and_nand_16: 6203 BuiltinIndex = 5; 6204 WarnAboutSemanticsChange = true; 6205 break; 6206 6207 case Builtin::BI__sync_add_and_fetch: 6208 case Builtin::BI__sync_add_and_fetch_1: 6209 case Builtin::BI__sync_add_and_fetch_2: 6210 case Builtin::BI__sync_add_and_fetch_4: 6211 case Builtin::BI__sync_add_and_fetch_8: 6212 case Builtin::BI__sync_add_and_fetch_16: 6213 BuiltinIndex = 6; 6214 break; 6215 6216 case Builtin::BI__sync_sub_and_fetch: 6217 case Builtin::BI__sync_sub_and_fetch_1: 6218 case Builtin::BI__sync_sub_and_fetch_2: 6219 case Builtin::BI__sync_sub_and_fetch_4: 6220 case Builtin::BI__sync_sub_and_fetch_8: 6221 case Builtin::BI__sync_sub_and_fetch_16: 6222 BuiltinIndex = 7; 6223 break; 6224 6225 case Builtin::BI__sync_and_and_fetch: 6226 case Builtin::BI__sync_and_and_fetch_1: 6227 case Builtin::BI__sync_and_and_fetch_2: 6228 case Builtin::BI__sync_and_and_fetch_4: 6229 case Builtin::BI__sync_and_and_fetch_8: 6230 case Builtin::BI__sync_and_and_fetch_16: 6231 BuiltinIndex = 8; 6232 break; 6233 6234 case Builtin::BI__sync_or_and_fetch: 6235 case Builtin::BI__sync_or_and_fetch_1: 6236 case Builtin::BI__sync_or_and_fetch_2: 6237 case Builtin::BI__sync_or_and_fetch_4: 6238 case Builtin::BI__sync_or_and_fetch_8: 6239 case Builtin::BI__sync_or_and_fetch_16: 6240 BuiltinIndex = 9; 6241 break; 6242 6243 case Builtin::BI__sync_xor_and_fetch: 6244 case Builtin::BI__sync_xor_and_fetch_1: 6245 case Builtin::BI__sync_xor_and_fetch_2: 6246 case Builtin::BI__sync_xor_and_fetch_4: 6247 case Builtin::BI__sync_xor_and_fetch_8: 6248 case Builtin::BI__sync_xor_and_fetch_16: 6249 BuiltinIndex = 10; 6250 break; 6251 6252 case Builtin::BI__sync_nand_and_fetch: 6253 case Builtin::BI__sync_nand_and_fetch_1: 6254 case Builtin::BI__sync_nand_and_fetch_2: 6255 case Builtin::BI__sync_nand_and_fetch_4: 6256 case Builtin::BI__sync_nand_and_fetch_8: 6257 case Builtin::BI__sync_nand_and_fetch_16: 6258 BuiltinIndex = 11; 6259 WarnAboutSemanticsChange = true; 6260 break; 6261 6262 case Builtin::BI__sync_val_compare_and_swap: 6263 case Builtin::BI__sync_val_compare_and_swap_1: 6264 case Builtin::BI__sync_val_compare_and_swap_2: 6265 case Builtin::BI__sync_val_compare_and_swap_4: 6266 case Builtin::BI__sync_val_compare_and_swap_8: 6267 case Builtin::BI__sync_val_compare_and_swap_16: 6268 BuiltinIndex = 12; 6269 NumFixed = 2; 6270 break; 6271 6272 case Builtin::BI__sync_bool_compare_and_swap: 6273 case Builtin::BI__sync_bool_compare_and_swap_1: 6274 case Builtin::BI__sync_bool_compare_and_swap_2: 6275 case Builtin::BI__sync_bool_compare_and_swap_4: 6276 case Builtin::BI__sync_bool_compare_and_swap_8: 6277 case Builtin::BI__sync_bool_compare_and_swap_16: 6278 BuiltinIndex = 13; 6279 NumFixed = 2; 6280 ResultType = Context.BoolTy; 6281 break; 6282 6283 case Builtin::BI__sync_lock_test_and_set: 6284 case Builtin::BI__sync_lock_test_and_set_1: 6285 case Builtin::BI__sync_lock_test_and_set_2: 6286 case Builtin::BI__sync_lock_test_and_set_4: 6287 case Builtin::BI__sync_lock_test_and_set_8: 6288 case Builtin::BI__sync_lock_test_and_set_16: 6289 BuiltinIndex = 14; 6290 break; 6291 6292 case Builtin::BI__sync_lock_release: 6293 case Builtin::BI__sync_lock_release_1: 6294 case Builtin::BI__sync_lock_release_2: 6295 case Builtin::BI__sync_lock_release_4: 6296 case Builtin::BI__sync_lock_release_8: 6297 case Builtin::BI__sync_lock_release_16: 6298 BuiltinIndex = 15; 6299 NumFixed = 0; 6300 ResultType = Context.VoidTy; 6301 break; 6302 6303 case Builtin::BI__sync_swap: 6304 case Builtin::BI__sync_swap_1: 6305 case Builtin::BI__sync_swap_2: 6306 case Builtin::BI__sync_swap_4: 6307 case Builtin::BI__sync_swap_8: 6308 case Builtin::BI__sync_swap_16: 6309 BuiltinIndex = 16; 6310 break; 6311 } 6312 6313 // Now that we know how many fixed arguments we expect, first check that we 6314 // have at least that many. 6315 if (TheCall->getNumArgs() < 1+NumFixed) { 6316 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6317 << 0 << 1 + NumFixed << TheCall->getNumArgs() 6318 << Callee->getSourceRange(); 6319 return ExprError(); 6320 } 6321 6322 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 6323 << Callee->getSourceRange(); 6324 6325 if (WarnAboutSemanticsChange) { 6326 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 6327 << Callee->getSourceRange(); 6328 } 6329 6330 // Get the decl for the concrete builtin from this, we can tell what the 6331 // concrete integer type we should convert to is. 6332 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 6333 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 6334 FunctionDecl *NewBuiltinDecl; 6335 if (NewBuiltinID == BuiltinID) 6336 NewBuiltinDecl = FDecl; 6337 else { 6338 // Perform builtin lookup to avoid redeclaring it. 6339 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 6340 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 6341 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 6342 assert(Res.getFoundDecl()); 6343 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 6344 if (!NewBuiltinDecl) 6345 return ExprError(); 6346 } 6347 6348 // The first argument --- the pointer --- has a fixed type; we 6349 // deduce the types of the rest of the arguments accordingly. Walk 6350 // the remaining arguments, converting them to the deduced value type. 6351 for (unsigned i = 0; i != NumFixed; ++i) { 6352 ExprResult Arg = TheCall->getArg(i+1); 6353 6354 // GCC does an implicit conversion to the pointer or integer ValType. This 6355 // can fail in some cases (1i -> int**), check for this error case now. 6356 // Initialize the argument. 6357 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6358 ValType, /*consume*/ false); 6359 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6360 if (Arg.isInvalid()) 6361 return ExprError(); 6362 6363 // Okay, we have something that *can* be converted to the right type. Check 6364 // to see if there is a potentially weird extension going on here. This can 6365 // happen when you do an atomic operation on something like an char* and 6366 // pass in 42. The 42 gets converted to char. This is even more strange 6367 // for things like 45.123 -> char, etc. 6368 // FIXME: Do this check. 6369 TheCall->setArg(i+1, Arg.get()); 6370 } 6371 6372 // Create a new DeclRefExpr to refer to the new decl. 6373 DeclRefExpr *NewDRE = DeclRefExpr::Create( 6374 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 6375 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 6376 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 6377 6378 // Set the callee in the CallExpr. 6379 // FIXME: This loses syntactic information. 6380 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 6381 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 6382 CK_BuiltinFnToFnPtr); 6383 TheCall->setCallee(PromotedCall.get()); 6384 6385 // Change the result type of the call to match the original value type. This 6386 // is arbitrary, but the codegen for these builtins ins design to handle it 6387 // gracefully. 6388 TheCall->setType(ResultType); 6389 6390 // Prohibit problematic uses of bit-precise integer types with atomic 6391 // builtins. The arguments would have already been converted to the first 6392 // argument's type, so only need to check the first argument. 6393 const auto *BitIntValType = ValType->getAs<BitIntType>(); 6394 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) { 6395 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 6396 return ExprError(); 6397 } 6398 6399 return TheCallResult; 6400 } 6401 6402 /// SemaBuiltinNontemporalOverloaded - We have a call to 6403 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 6404 /// overloaded function based on the pointer type of its last argument. 6405 /// 6406 /// This function goes through and does final semantic checking for these 6407 /// builtins. 6408 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 6409 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 6410 DeclRefExpr *DRE = 6411 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6412 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6413 unsigned BuiltinID = FDecl->getBuiltinID(); 6414 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 6415 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 6416 "Unexpected nontemporal load/store builtin!"); 6417 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 6418 unsigned numArgs = isStore ? 2 : 1; 6419 6420 // Ensure that we have the proper number of arguments. 6421 if (checkArgCount(*this, TheCall, numArgs)) 6422 return ExprError(); 6423 6424 // Inspect the last argument of the nontemporal builtin. This should always 6425 // be a pointer type, from which we imply the type of the memory access. 6426 // Because it is a pointer type, we don't have to worry about any implicit 6427 // casts here. 6428 Expr *PointerArg = TheCall->getArg(numArgs - 1); 6429 ExprResult PointerArgResult = 6430 DefaultFunctionArrayLvalueConversion(PointerArg); 6431 6432 if (PointerArgResult.isInvalid()) 6433 return ExprError(); 6434 PointerArg = PointerArgResult.get(); 6435 TheCall->setArg(numArgs - 1, PointerArg); 6436 6437 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 6438 if (!pointerType) { 6439 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 6440 << PointerArg->getType() << PointerArg->getSourceRange(); 6441 return ExprError(); 6442 } 6443 6444 QualType ValType = pointerType->getPointeeType(); 6445 6446 // Strip any qualifiers off ValType. 6447 ValType = ValType.getUnqualifiedType(); 6448 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6449 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 6450 !ValType->isVectorType()) { 6451 Diag(DRE->getBeginLoc(), 6452 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 6453 << PointerArg->getType() << PointerArg->getSourceRange(); 6454 return ExprError(); 6455 } 6456 6457 if (!isStore) { 6458 TheCall->setType(ValType); 6459 return TheCallResult; 6460 } 6461 6462 ExprResult ValArg = TheCall->getArg(0); 6463 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6464 Context, ValType, /*consume*/ false); 6465 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 6466 if (ValArg.isInvalid()) 6467 return ExprError(); 6468 6469 TheCall->setArg(0, ValArg.get()); 6470 TheCall->setType(Context.VoidTy); 6471 return TheCallResult; 6472 } 6473 6474 /// CheckObjCString - Checks that the argument to the builtin 6475 /// CFString constructor is correct 6476 /// Note: It might also make sense to do the UTF-16 conversion here (would 6477 /// simplify the backend). 6478 bool Sema::CheckObjCString(Expr *Arg) { 6479 Arg = Arg->IgnoreParenCasts(); 6480 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 6481 6482 if (!Literal || !Literal->isAscii()) { 6483 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 6484 << Arg->getSourceRange(); 6485 return true; 6486 } 6487 6488 if (Literal->containsNonAsciiOrNull()) { 6489 StringRef String = Literal->getString(); 6490 unsigned NumBytes = String.size(); 6491 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6492 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6493 llvm::UTF16 *ToPtr = &ToBuf[0]; 6494 6495 llvm::ConversionResult Result = 6496 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6497 ToPtr + NumBytes, llvm::strictConversion); 6498 // Check for conversion failure. 6499 if (Result != llvm::conversionOK) 6500 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6501 << Arg->getSourceRange(); 6502 } 6503 return false; 6504 } 6505 6506 /// CheckObjCString - Checks that the format string argument to the os_log() 6507 /// and os_trace() functions is correct, and converts it to const char *. 6508 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6509 Arg = Arg->IgnoreParenCasts(); 6510 auto *Literal = dyn_cast<StringLiteral>(Arg); 6511 if (!Literal) { 6512 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6513 Literal = ObjcLiteral->getString(); 6514 } 6515 } 6516 6517 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6518 return ExprError( 6519 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 6520 << Arg->getSourceRange()); 6521 } 6522 6523 ExprResult Result(Literal); 6524 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 6525 InitializedEntity Entity = 6526 InitializedEntity::InitializeParameter(Context, ResultTy, false); 6527 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 6528 return Result; 6529 } 6530 6531 /// Check that the user is calling the appropriate va_start builtin for the 6532 /// target and calling convention. 6533 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 6534 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 6535 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 6536 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 6537 TT.getArch() == llvm::Triple::aarch64_32); 6538 bool IsWindows = TT.isOSWindows(); 6539 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 6540 if (IsX64 || IsAArch64) { 6541 CallingConv CC = CC_C; 6542 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 6543 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 6544 if (IsMSVAStart) { 6545 // Don't allow this in System V ABI functions. 6546 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 6547 return S.Diag(Fn->getBeginLoc(), 6548 diag::err_ms_va_start_used_in_sysv_function); 6549 } else { 6550 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 6551 // On x64 Windows, don't allow this in System V ABI functions. 6552 // (Yes, that means there's no corresponding way to support variadic 6553 // System V ABI functions on Windows.) 6554 if ((IsWindows && CC == CC_X86_64SysV) || 6555 (!IsWindows && CC == CC_Win64)) 6556 return S.Diag(Fn->getBeginLoc(), 6557 diag::err_va_start_used_in_wrong_abi_function) 6558 << !IsWindows; 6559 } 6560 return false; 6561 } 6562 6563 if (IsMSVAStart) 6564 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 6565 return false; 6566 } 6567 6568 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 6569 ParmVarDecl **LastParam = nullptr) { 6570 // Determine whether the current function, block, or obj-c method is variadic 6571 // and get its parameter list. 6572 bool IsVariadic = false; 6573 ArrayRef<ParmVarDecl *> Params; 6574 DeclContext *Caller = S.CurContext; 6575 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 6576 IsVariadic = Block->isVariadic(); 6577 Params = Block->parameters(); 6578 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 6579 IsVariadic = FD->isVariadic(); 6580 Params = FD->parameters(); 6581 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 6582 IsVariadic = MD->isVariadic(); 6583 // FIXME: This isn't correct for methods (results in bogus warning). 6584 Params = MD->parameters(); 6585 } else if (isa<CapturedDecl>(Caller)) { 6586 // We don't support va_start in a CapturedDecl. 6587 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 6588 return true; 6589 } else { 6590 // This must be some other declcontext that parses exprs. 6591 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 6592 return true; 6593 } 6594 6595 if (!IsVariadic) { 6596 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 6597 return true; 6598 } 6599 6600 if (LastParam) 6601 *LastParam = Params.empty() ? nullptr : Params.back(); 6602 6603 return false; 6604 } 6605 6606 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 6607 /// for validity. Emit an error and return true on failure; return false 6608 /// on success. 6609 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 6610 Expr *Fn = TheCall->getCallee(); 6611 6612 if (checkVAStartABI(*this, BuiltinID, Fn)) 6613 return true; 6614 6615 if (checkArgCount(*this, TheCall, 2)) 6616 return true; 6617 6618 // Type-check the first argument normally. 6619 if (checkBuiltinArgument(*this, TheCall, 0)) 6620 return true; 6621 6622 // Check that the current function is variadic, and get its last parameter. 6623 ParmVarDecl *LastParam; 6624 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6625 return true; 6626 6627 // Verify that the second argument to the builtin is the last argument of the 6628 // current function or method. 6629 bool SecondArgIsLastNamedArgument = false; 6630 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6631 6632 // These are valid if SecondArgIsLastNamedArgument is false after the next 6633 // block. 6634 QualType Type; 6635 SourceLocation ParamLoc; 6636 bool IsCRegister = false; 6637 6638 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6639 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6640 SecondArgIsLastNamedArgument = PV == LastParam; 6641 6642 Type = PV->getType(); 6643 ParamLoc = PV->getLocation(); 6644 IsCRegister = 6645 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6646 } 6647 } 6648 6649 if (!SecondArgIsLastNamedArgument) 6650 Diag(TheCall->getArg(1)->getBeginLoc(), 6651 diag::warn_second_arg_of_va_start_not_last_named_param); 6652 else if (IsCRegister || Type->isReferenceType() || 6653 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6654 // Promotable integers are UB, but enumerations need a bit of 6655 // extra checking to see what their promotable type actually is. 6656 if (!Type->isPromotableIntegerType()) 6657 return false; 6658 if (!Type->isEnumeralType()) 6659 return true; 6660 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6661 return !(ED && 6662 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6663 }()) { 6664 unsigned Reason = 0; 6665 if (Type->isReferenceType()) Reason = 1; 6666 else if (IsCRegister) Reason = 2; 6667 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6668 Diag(ParamLoc, diag::note_parameter_type) << Type; 6669 } 6670 6671 TheCall->setType(Context.VoidTy); 6672 return false; 6673 } 6674 6675 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6676 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool { 6677 const LangOptions &LO = getLangOpts(); 6678 6679 if (LO.CPlusPlus) 6680 return Arg->getType() 6681 .getCanonicalType() 6682 .getTypePtr() 6683 ->getPointeeType() 6684 .withoutLocalFastQualifiers() == Context.CharTy; 6685 6686 // In C, allow aliasing through `char *`, this is required for AArch64 at 6687 // least. 6688 return true; 6689 }; 6690 6691 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6692 // const char *named_addr); 6693 6694 Expr *Func = Call->getCallee(); 6695 6696 if (Call->getNumArgs() < 3) 6697 return Diag(Call->getEndLoc(), 6698 diag::err_typecheck_call_too_few_args_at_least) 6699 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6700 6701 // Type-check the first argument normally. 6702 if (checkBuiltinArgument(*this, Call, 0)) 6703 return true; 6704 6705 // Check that the current function is variadic. 6706 if (checkVAStartIsInVariadicFunction(*this, Func)) 6707 return true; 6708 6709 // __va_start on Windows does not validate the parameter qualifiers 6710 6711 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6712 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6713 6714 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6715 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6716 6717 const QualType &ConstCharPtrTy = 6718 Context.getPointerType(Context.CharTy.withConst()); 6719 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1)) 6720 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6721 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6722 << 0 /* qualifier difference */ 6723 << 3 /* parameter mismatch */ 6724 << 2 << Arg1->getType() << ConstCharPtrTy; 6725 6726 const QualType SizeTy = Context.getSizeType(); 6727 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6728 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6729 << Arg2->getType() << SizeTy << 1 /* different class */ 6730 << 0 /* qualifier difference */ 6731 << 3 /* parameter mismatch */ 6732 << 3 << Arg2->getType() << SizeTy; 6733 6734 return false; 6735 } 6736 6737 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6738 /// friends. This is declared to take (...), so we have to check everything. 6739 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6740 if (checkArgCount(*this, TheCall, 2)) 6741 return true; 6742 6743 ExprResult OrigArg0 = TheCall->getArg(0); 6744 ExprResult OrigArg1 = TheCall->getArg(1); 6745 6746 // Do standard promotions between the two arguments, returning their common 6747 // type. 6748 QualType Res = UsualArithmeticConversions( 6749 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6750 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6751 return true; 6752 6753 // Make sure any conversions are pushed back into the call; this is 6754 // type safe since unordered compare builtins are declared as "_Bool 6755 // foo(...)". 6756 TheCall->setArg(0, OrigArg0.get()); 6757 TheCall->setArg(1, OrigArg1.get()); 6758 6759 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6760 return false; 6761 6762 // If the common type isn't a real floating type, then the arguments were 6763 // invalid for this operation. 6764 if (Res.isNull() || !Res->isRealFloatingType()) 6765 return Diag(OrigArg0.get()->getBeginLoc(), 6766 diag::err_typecheck_call_invalid_ordered_compare) 6767 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6768 << SourceRange(OrigArg0.get()->getBeginLoc(), 6769 OrigArg1.get()->getEndLoc()); 6770 6771 return false; 6772 } 6773 6774 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6775 /// __builtin_isnan and friends. This is declared to take (...), so we have 6776 /// to check everything. We expect the last argument to be a floating point 6777 /// value. 6778 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6779 if (checkArgCount(*this, TheCall, NumArgs)) 6780 return true; 6781 6782 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6783 // on all preceding parameters just being int. Try all of those. 6784 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6785 Expr *Arg = TheCall->getArg(i); 6786 6787 if (Arg->isTypeDependent()) 6788 return false; 6789 6790 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6791 6792 if (Res.isInvalid()) 6793 return true; 6794 TheCall->setArg(i, Res.get()); 6795 } 6796 6797 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6798 6799 if (OrigArg->isTypeDependent()) 6800 return false; 6801 6802 // Usual Unary Conversions will convert half to float, which we want for 6803 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6804 // type how it is, but do normal L->Rvalue conversions. 6805 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6806 OrigArg = UsualUnaryConversions(OrigArg).get(); 6807 else 6808 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6809 TheCall->setArg(NumArgs - 1, OrigArg); 6810 6811 // This operation requires a non-_Complex floating-point number. 6812 if (!OrigArg->getType()->isRealFloatingType()) 6813 return Diag(OrigArg->getBeginLoc(), 6814 diag::err_typecheck_call_invalid_unary_fp) 6815 << OrigArg->getType() << OrigArg->getSourceRange(); 6816 6817 return false; 6818 } 6819 6820 /// Perform semantic analysis for a call to __builtin_complex. 6821 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6822 if (checkArgCount(*this, TheCall, 2)) 6823 return true; 6824 6825 bool Dependent = false; 6826 for (unsigned I = 0; I != 2; ++I) { 6827 Expr *Arg = TheCall->getArg(I); 6828 QualType T = Arg->getType(); 6829 if (T->isDependentType()) { 6830 Dependent = true; 6831 continue; 6832 } 6833 6834 // Despite supporting _Complex int, GCC requires a real floating point type 6835 // for the operands of __builtin_complex. 6836 if (!T->isRealFloatingType()) { 6837 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6838 << Arg->getType() << Arg->getSourceRange(); 6839 } 6840 6841 ExprResult Converted = DefaultLvalueConversion(Arg); 6842 if (Converted.isInvalid()) 6843 return true; 6844 TheCall->setArg(I, Converted.get()); 6845 } 6846 6847 if (Dependent) { 6848 TheCall->setType(Context.DependentTy); 6849 return false; 6850 } 6851 6852 Expr *Real = TheCall->getArg(0); 6853 Expr *Imag = TheCall->getArg(1); 6854 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6855 return Diag(Real->getBeginLoc(), 6856 diag::err_typecheck_call_different_arg_types) 6857 << Real->getType() << Imag->getType() 6858 << Real->getSourceRange() << Imag->getSourceRange(); 6859 } 6860 6861 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6862 // don't allow this builtin to form those types either. 6863 // FIXME: Should we allow these types? 6864 if (Real->getType()->isFloat16Type()) 6865 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6866 << "_Float16"; 6867 if (Real->getType()->isHalfType()) 6868 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6869 << "half"; 6870 6871 TheCall->setType(Context.getComplexType(Real->getType())); 6872 return false; 6873 } 6874 6875 // Customized Sema Checking for VSX builtins that have the following signature: 6876 // vector [...] builtinName(vector [...], vector [...], const int); 6877 // Which takes the same type of vectors (any legal vector type) for the first 6878 // two arguments and takes compile time constant for the third argument. 6879 // Example builtins are : 6880 // vector double vec_xxpermdi(vector double, vector double, int); 6881 // vector short vec_xxsldwi(vector short, vector short, int); 6882 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6883 unsigned ExpectedNumArgs = 3; 6884 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6885 return true; 6886 6887 // Check the third argument is a compile time constant 6888 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6889 return Diag(TheCall->getBeginLoc(), 6890 diag::err_vsx_builtin_nonconstant_argument) 6891 << 3 /* argument index */ << TheCall->getDirectCallee() 6892 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6893 TheCall->getArg(2)->getEndLoc()); 6894 6895 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6896 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6897 6898 // Check the type of argument 1 and argument 2 are vectors. 6899 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6900 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6901 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6902 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6903 << TheCall->getDirectCallee() 6904 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6905 TheCall->getArg(1)->getEndLoc()); 6906 } 6907 6908 // Check the first two arguments are the same type. 6909 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6910 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6911 << TheCall->getDirectCallee() 6912 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6913 TheCall->getArg(1)->getEndLoc()); 6914 } 6915 6916 // When default clang type checking is turned off and the customized type 6917 // checking is used, the returning type of the function must be explicitly 6918 // set. Otherwise it is _Bool by default. 6919 TheCall->setType(Arg1Ty); 6920 6921 return false; 6922 } 6923 6924 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6925 // This is declared to take (...), so we have to check everything. 6926 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6927 if (TheCall->getNumArgs() < 2) 6928 return ExprError(Diag(TheCall->getEndLoc(), 6929 diag::err_typecheck_call_too_few_args_at_least) 6930 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6931 << TheCall->getSourceRange()); 6932 6933 // Determine which of the following types of shufflevector we're checking: 6934 // 1) unary, vector mask: (lhs, mask) 6935 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6936 QualType resType = TheCall->getArg(0)->getType(); 6937 unsigned numElements = 0; 6938 6939 if (!TheCall->getArg(0)->isTypeDependent() && 6940 !TheCall->getArg(1)->isTypeDependent()) { 6941 QualType LHSType = TheCall->getArg(0)->getType(); 6942 QualType RHSType = TheCall->getArg(1)->getType(); 6943 6944 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6945 return ExprError( 6946 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6947 << TheCall->getDirectCallee() 6948 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6949 TheCall->getArg(1)->getEndLoc())); 6950 6951 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6952 unsigned numResElements = TheCall->getNumArgs() - 2; 6953 6954 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6955 // with mask. If so, verify that RHS is an integer vector type with the 6956 // same number of elts as lhs. 6957 if (TheCall->getNumArgs() == 2) { 6958 if (!RHSType->hasIntegerRepresentation() || 6959 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6960 return ExprError(Diag(TheCall->getBeginLoc(), 6961 diag::err_vec_builtin_incompatible_vector) 6962 << TheCall->getDirectCallee() 6963 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6964 TheCall->getArg(1)->getEndLoc())); 6965 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6966 return ExprError(Diag(TheCall->getBeginLoc(), 6967 diag::err_vec_builtin_incompatible_vector) 6968 << TheCall->getDirectCallee() 6969 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6970 TheCall->getArg(1)->getEndLoc())); 6971 } else if (numElements != numResElements) { 6972 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6973 resType = Context.getVectorType(eltType, numResElements, 6974 VectorType::GenericVector); 6975 } 6976 } 6977 6978 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6979 if (TheCall->getArg(i)->isTypeDependent() || 6980 TheCall->getArg(i)->isValueDependent()) 6981 continue; 6982 6983 Optional<llvm::APSInt> Result; 6984 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6985 return ExprError(Diag(TheCall->getBeginLoc(), 6986 diag::err_shufflevector_nonconstant_argument) 6987 << TheCall->getArg(i)->getSourceRange()); 6988 6989 // Allow -1 which will be translated to undef in the IR. 6990 if (Result->isSigned() && Result->isAllOnes()) 6991 continue; 6992 6993 if (Result->getActiveBits() > 64 || 6994 Result->getZExtValue() >= numElements * 2) 6995 return ExprError(Diag(TheCall->getBeginLoc(), 6996 diag::err_shufflevector_argument_too_large) 6997 << TheCall->getArg(i)->getSourceRange()); 6998 } 6999 7000 SmallVector<Expr*, 32> exprs; 7001 7002 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 7003 exprs.push_back(TheCall->getArg(i)); 7004 TheCall->setArg(i, nullptr); 7005 } 7006 7007 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 7008 TheCall->getCallee()->getBeginLoc(), 7009 TheCall->getRParenLoc()); 7010 } 7011 7012 /// SemaConvertVectorExpr - Handle __builtin_convertvector 7013 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 7014 SourceLocation BuiltinLoc, 7015 SourceLocation RParenLoc) { 7016 ExprValueKind VK = VK_PRValue; 7017 ExprObjectKind OK = OK_Ordinary; 7018 QualType DstTy = TInfo->getType(); 7019 QualType SrcTy = E->getType(); 7020 7021 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 7022 return ExprError(Diag(BuiltinLoc, 7023 diag::err_convertvector_non_vector) 7024 << E->getSourceRange()); 7025 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 7026 return ExprError(Diag(BuiltinLoc, 7027 diag::err_convertvector_non_vector_type)); 7028 7029 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 7030 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 7031 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 7032 if (SrcElts != DstElts) 7033 return ExprError(Diag(BuiltinLoc, 7034 diag::err_convertvector_incompatible_vector) 7035 << E->getSourceRange()); 7036 } 7037 7038 return new (Context) 7039 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 7040 } 7041 7042 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 7043 // This is declared to take (const void*, ...) and can take two 7044 // optional constant int args. 7045 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 7046 unsigned NumArgs = TheCall->getNumArgs(); 7047 7048 if (NumArgs > 3) 7049 return Diag(TheCall->getEndLoc(), 7050 diag::err_typecheck_call_too_many_args_at_most) 7051 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 7052 7053 // Argument 0 is checked for us and the remaining arguments must be 7054 // constant integers. 7055 for (unsigned i = 1; i != NumArgs; ++i) 7056 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 7057 return true; 7058 7059 return false; 7060 } 7061 7062 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 7063 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 7064 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 7065 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 7066 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7067 if (checkArgCount(*this, TheCall, 1)) 7068 return true; 7069 Expr *Arg = TheCall->getArg(0); 7070 if (Arg->isInstantiationDependent()) 7071 return false; 7072 7073 QualType ArgTy = Arg->getType(); 7074 if (!ArgTy->hasFloatingRepresentation()) 7075 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 7076 << ArgTy; 7077 if (Arg->isLValue()) { 7078 ExprResult FirstArg = DefaultLvalueConversion(Arg); 7079 TheCall->setArg(0, FirstArg.get()); 7080 } 7081 TheCall->setType(TheCall->getArg(0)->getType()); 7082 return false; 7083 } 7084 7085 /// SemaBuiltinAssume - Handle __assume (MS Extension). 7086 // __assume does not evaluate its arguments, and should warn if its argument 7087 // has side effects. 7088 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 7089 Expr *Arg = TheCall->getArg(0); 7090 if (Arg->isInstantiationDependent()) return false; 7091 7092 if (Arg->HasSideEffects(Context)) 7093 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 7094 << Arg->getSourceRange() 7095 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 7096 7097 return false; 7098 } 7099 7100 /// Handle __builtin_alloca_with_align. This is declared 7101 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 7102 /// than 8. 7103 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 7104 // The alignment must be a constant integer. 7105 Expr *Arg = TheCall->getArg(1); 7106 7107 // We can't check the value of a dependent argument. 7108 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 7109 if (const auto *UE = 7110 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 7111 if (UE->getKind() == UETT_AlignOf || 7112 UE->getKind() == UETT_PreferredAlignOf) 7113 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 7114 << Arg->getSourceRange(); 7115 7116 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 7117 7118 if (!Result.isPowerOf2()) 7119 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 7120 << Arg->getSourceRange(); 7121 7122 if (Result < Context.getCharWidth()) 7123 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 7124 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 7125 7126 if (Result > std::numeric_limits<int32_t>::max()) 7127 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 7128 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 7129 } 7130 7131 return false; 7132 } 7133 7134 /// Handle __builtin_assume_aligned. This is declared 7135 /// as (const void*, size_t, ...) and can take one optional constant int arg. 7136 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 7137 unsigned NumArgs = TheCall->getNumArgs(); 7138 7139 if (NumArgs > 3) 7140 return Diag(TheCall->getEndLoc(), 7141 diag::err_typecheck_call_too_many_args_at_most) 7142 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 7143 7144 // The alignment must be a constant integer. 7145 Expr *Arg = TheCall->getArg(1); 7146 7147 // We can't check the value of a dependent argument. 7148 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 7149 llvm::APSInt Result; 7150 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7151 return true; 7152 7153 if (!Result.isPowerOf2()) 7154 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 7155 << Arg->getSourceRange(); 7156 7157 if (Result > Sema::MaximumAlignment) 7158 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 7159 << Arg->getSourceRange() << Sema::MaximumAlignment; 7160 } 7161 7162 if (NumArgs > 2) { 7163 ExprResult Arg(TheCall->getArg(2)); 7164 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 7165 Context.getSizeType(), false); 7166 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 7167 if (Arg.isInvalid()) return true; 7168 TheCall->setArg(2, Arg.get()); 7169 } 7170 7171 return false; 7172 } 7173 7174 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 7175 unsigned BuiltinID = 7176 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 7177 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 7178 7179 unsigned NumArgs = TheCall->getNumArgs(); 7180 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 7181 if (NumArgs < NumRequiredArgs) { 7182 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 7183 << 0 /* function call */ << NumRequiredArgs << NumArgs 7184 << TheCall->getSourceRange(); 7185 } 7186 if (NumArgs >= NumRequiredArgs + 0x100) { 7187 return Diag(TheCall->getEndLoc(), 7188 diag::err_typecheck_call_too_many_args_at_most) 7189 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 7190 << TheCall->getSourceRange(); 7191 } 7192 unsigned i = 0; 7193 7194 // For formatting call, check buffer arg. 7195 if (!IsSizeCall) { 7196 ExprResult Arg(TheCall->getArg(i)); 7197 InitializedEntity Entity = InitializedEntity::InitializeParameter( 7198 Context, Context.VoidPtrTy, false); 7199 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 7200 if (Arg.isInvalid()) 7201 return true; 7202 TheCall->setArg(i, Arg.get()); 7203 i++; 7204 } 7205 7206 // Check string literal arg. 7207 unsigned FormatIdx = i; 7208 { 7209 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 7210 if (Arg.isInvalid()) 7211 return true; 7212 TheCall->setArg(i, Arg.get()); 7213 i++; 7214 } 7215 7216 // Make sure variadic args are scalar. 7217 unsigned FirstDataArg = i; 7218 while (i < NumArgs) { 7219 ExprResult Arg = DefaultVariadicArgumentPromotion( 7220 TheCall->getArg(i), VariadicFunction, nullptr); 7221 if (Arg.isInvalid()) 7222 return true; 7223 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 7224 if (ArgSize.getQuantity() >= 0x100) { 7225 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 7226 << i << (int)ArgSize.getQuantity() << 0xff 7227 << TheCall->getSourceRange(); 7228 } 7229 TheCall->setArg(i, Arg.get()); 7230 i++; 7231 } 7232 7233 // Check formatting specifiers. NOTE: We're only doing this for the non-size 7234 // call to avoid duplicate diagnostics. 7235 if (!IsSizeCall) { 7236 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 7237 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 7238 bool Success = CheckFormatArguments( 7239 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 7240 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 7241 CheckedVarArgs); 7242 if (!Success) 7243 return true; 7244 } 7245 7246 if (IsSizeCall) { 7247 TheCall->setType(Context.getSizeType()); 7248 } else { 7249 TheCall->setType(Context.VoidPtrTy); 7250 } 7251 return false; 7252 } 7253 7254 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 7255 /// TheCall is a constant expression. 7256 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 7257 llvm::APSInt &Result) { 7258 Expr *Arg = TheCall->getArg(ArgNum); 7259 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 7260 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 7261 7262 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 7263 7264 Optional<llvm::APSInt> R; 7265 if (!(R = Arg->getIntegerConstantExpr(Context))) 7266 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 7267 << FDecl->getDeclName() << Arg->getSourceRange(); 7268 Result = *R; 7269 return false; 7270 } 7271 7272 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 7273 /// TheCall is a constant expression in the range [Low, High]. 7274 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 7275 int Low, int High, bool RangeIsError) { 7276 if (isConstantEvaluated()) 7277 return false; 7278 llvm::APSInt Result; 7279 7280 // We can't check the value of a dependent argument. 7281 Expr *Arg = TheCall->getArg(ArgNum); 7282 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7283 return false; 7284 7285 // Check constant-ness first. 7286 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7287 return true; 7288 7289 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 7290 if (RangeIsError) 7291 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 7292 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 7293 else 7294 // Defer the warning until we know if the code will be emitted so that 7295 // dead code can ignore this. 7296 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 7297 PDiag(diag::warn_argument_invalid_range) 7298 << toString(Result, 10) << Low << High 7299 << Arg->getSourceRange()); 7300 } 7301 7302 return false; 7303 } 7304 7305 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 7306 /// TheCall is a constant expression is a multiple of Num.. 7307 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 7308 unsigned Num) { 7309 llvm::APSInt Result; 7310 7311 // We can't check the value of a dependent argument. 7312 Expr *Arg = TheCall->getArg(ArgNum); 7313 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7314 return false; 7315 7316 // Check constant-ness first. 7317 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7318 return true; 7319 7320 if (Result.getSExtValue() % Num != 0) 7321 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 7322 << Num << Arg->getSourceRange(); 7323 7324 return false; 7325 } 7326 7327 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 7328 /// constant expression representing a power of 2. 7329 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 7330 llvm::APSInt Result; 7331 7332 // We can't check the value of a dependent argument. 7333 Expr *Arg = TheCall->getArg(ArgNum); 7334 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7335 return false; 7336 7337 // Check constant-ness first. 7338 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7339 return true; 7340 7341 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 7342 // and only if x is a power of 2. 7343 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 7344 return false; 7345 7346 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 7347 << Arg->getSourceRange(); 7348 } 7349 7350 static bool IsShiftedByte(llvm::APSInt Value) { 7351 if (Value.isNegative()) 7352 return false; 7353 7354 // Check if it's a shifted byte, by shifting it down 7355 while (true) { 7356 // If the value fits in the bottom byte, the check passes. 7357 if (Value < 0x100) 7358 return true; 7359 7360 // Otherwise, if the value has _any_ bits in the bottom byte, the check 7361 // fails. 7362 if ((Value & 0xFF) != 0) 7363 return false; 7364 7365 // If the bottom 8 bits are all 0, but something above that is nonzero, 7366 // then shifting the value right by 8 bits won't affect whether it's a 7367 // shifted byte or not. So do that, and go round again. 7368 Value >>= 8; 7369 } 7370 } 7371 7372 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 7373 /// a constant expression representing an arbitrary byte value shifted left by 7374 /// a multiple of 8 bits. 7375 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 7376 unsigned ArgBits) { 7377 llvm::APSInt Result; 7378 7379 // We can't check the value of a dependent argument. 7380 Expr *Arg = TheCall->getArg(ArgNum); 7381 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7382 return false; 7383 7384 // Check constant-ness first. 7385 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7386 return true; 7387 7388 // Truncate to the given size. 7389 Result = Result.getLoBits(ArgBits); 7390 Result.setIsUnsigned(true); 7391 7392 if (IsShiftedByte(Result)) 7393 return false; 7394 7395 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 7396 << Arg->getSourceRange(); 7397 } 7398 7399 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 7400 /// TheCall is a constant expression representing either a shifted byte value, 7401 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 7402 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 7403 /// Arm MVE intrinsics. 7404 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 7405 int ArgNum, 7406 unsigned ArgBits) { 7407 llvm::APSInt Result; 7408 7409 // We can't check the value of a dependent argument. 7410 Expr *Arg = TheCall->getArg(ArgNum); 7411 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7412 return false; 7413 7414 // Check constant-ness first. 7415 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7416 return true; 7417 7418 // Truncate to the given size. 7419 Result = Result.getLoBits(ArgBits); 7420 Result.setIsUnsigned(true); 7421 7422 // Check to see if it's in either of the required forms. 7423 if (IsShiftedByte(Result) || 7424 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 7425 return false; 7426 7427 return Diag(TheCall->getBeginLoc(), 7428 diag::err_argument_not_shifted_byte_or_xxff) 7429 << Arg->getSourceRange(); 7430 } 7431 7432 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 7433 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 7434 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 7435 if (checkArgCount(*this, TheCall, 2)) 7436 return true; 7437 Expr *Arg0 = TheCall->getArg(0); 7438 Expr *Arg1 = TheCall->getArg(1); 7439 7440 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7441 if (FirstArg.isInvalid()) 7442 return true; 7443 QualType FirstArgType = FirstArg.get()->getType(); 7444 if (!FirstArgType->isAnyPointerType()) 7445 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7446 << "first" << FirstArgType << Arg0->getSourceRange(); 7447 TheCall->setArg(0, FirstArg.get()); 7448 7449 ExprResult SecArg = DefaultLvalueConversion(Arg1); 7450 if (SecArg.isInvalid()) 7451 return true; 7452 QualType SecArgType = SecArg.get()->getType(); 7453 if (!SecArgType->isIntegerType()) 7454 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7455 << "second" << SecArgType << Arg1->getSourceRange(); 7456 7457 // Derive the return type from the pointer argument. 7458 TheCall->setType(FirstArgType); 7459 return false; 7460 } 7461 7462 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 7463 if (checkArgCount(*this, TheCall, 2)) 7464 return true; 7465 7466 Expr *Arg0 = TheCall->getArg(0); 7467 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7468 if (FirstArg.isInvalid()) 7469 return true; 7470 QualType FirstArgType = FirstArg.get()->getType(); 7471 if (!FirstArgType->isAnyPointerType()) 7472 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7473 << "first" << FirstArgType << Arg0->getSourceRange(); 7474 TheCall->setArg(0, FirstArg.get()); 7475 7476 // Derive the return type from the pointer argument. 7477 TheCall->setType(FirstArgType); 7478 7479 // Second arg must be an constant in range [0,15] 7480 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7481 } 7482 7483 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 7484 if (checkArgCount(*this, TheCall, 2)) 7485 return true; 7486 Expr *Arg0 = TheCall->getArg(0); 7487 Expr *Arg1 = TheCall->getArg(1); 7488 7489 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7490 if (FirstArg.isInvalid()) 7491 return true; 7492 QualType FirstArgType = FirstArg.get()->getType(); 7493 if (!FirstArgType->isAnyPointerType()) 7494 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7495 << "first" << FirstArgType << Arg0->getSourceRange(); 7496 7497 QualType SecArgType = Arg1->getType(); 7498 if (!SecArgType->isIntegerType()) 7499 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7500 << "second" << SecArgType << Arg1->getSourceRange(); 7501 TheCall->setType(Context.IntTy); 7502 return false; 7503 } 7504 7505 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7506 BuiltinID == AArch64::BI__builtin_arm_stg) { 7507 if (checkArgCount(*this, TheCall, 1)) 7508 return true; 7509 Expr *Arg0 = TheCall->getArg(0); 7510 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7511 if (FirstArg.isInvalid()) 7512 return true; 7513 7514 QualType FirstArgType = FirstArg.get()->getType(); 7515 if (!FirstArgType->isAnyPointerType()) 7516 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7517 << "first" << FirstArgType << Arg0->getSourceRange(); 7518 TheCall->setArg(0, FirstArg.get()); 7519 7520 // Derive the return type from the pointer argument. 7521 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 7522 TheCall->setType(FirstArgType); 7523 return false; 7524 } 7525 7526 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 7527 Expr *ArgA = TheCall->getArg(0); 7528 Expr *ArgB = TheCall->getArg(1); 7529 7530 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 7531 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 7532 7533 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 7534 return true; 7535 7536 QualType ArgTypeA = ArgExprA.get()->getType(); 7537 QualType ArgTypeB = ArgExprB.get()->getType(); 7538 7539 auto isNull = [&] (Expr *E) -> bool { 7540 return E->isNullPointerConstant( 7541 Context, Expr::NPC_ValueDependentIsNotNull); }; 7542 7543 // argument should be either a pointer or null 7544 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 7545 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7546 << "first" << ArgTypeA << ArgA->getSourceRange(); 7547 7548 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 7549 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7550 << "second" << ArgTypeB << ArgB->getSourceRange(); 7551 7552 // Ensure Pointee types are compatible 7553 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 7554 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 7555 QualType pointeeA = ArgTypeA->getPointeeType(); 7556 QualType pointeeB = ArgTypeB->getPointeeType(); 7557 if (!Context.typesAreCompatible( 7558 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 7559 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 7560 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 7561 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 7562 << ArgB->getSourceRange(); 7563 } 7564 } 7565 7566 // at least one argument should be pointer type 7567 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 7568 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 7569 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 7570 7571 if (isNull(ArgA)) // adopt type of the other pointer 7572 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 7573 7574 if (isNull(ArgB)) 7575 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 7576 7577 TheCall->setArg(0, ArgExprA.get()); 7578 TheCall->setArg(1, ArgExprB.get()); 7579 TheCall->setType(Context.LongLongTy); 7580 return false; 7581 } 7582 assert(false && "Unhandled ARM MTE intrinsic"); 7583 return true; 7584 } 7585 7586 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 7587 /// TheCall is an ARM/AArch64 special register string literal. 7588 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 7589 int ArgNum, unsigned ExpectedFieldNum, 7590 bool AllowName) { 7591 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 7592 BuiltinID == ARM::BI__builtin_arm_wsr64 || 7593 BuiltinID == ARM::BI__builtin_arm_rsr || 7594 BuiltinID == ARM::BI__builtin_arm_rsrp || 7595 BuiltinID == ARM::BI__builtin_arm_wsr || 7596 BuiltinID == ARM::BI__builtin_arm_wsrp; 7597 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 7598 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 7599 BuiltinID == AArch64::BI__builtin_arm_rsr || 7600 BuiltinID == AArch64::BI__builtin_arm_rsrp || 7601 BuiltinID == AArch64::BI__builtin_arm_wsr || 7602 BuiltinID == AArch64::BI__builtin_arm_wsrp; 7603 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 7604 7605 // We can't check the value of a dependent argument. 7606 Expr *Arg = TheCall->getArg(ArgNum); 7607 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7608 return false; 7609 7610 // Check if the argument is a string literal. 7611 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 7612 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 7613 << Arg->getSourceRange(); 7614 7615 // Check the type of special register given. 7616 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 7617 SmallVector<StringRef, 6> Fields; 7618 Reg.split(Fields, ":"); 7619 7620 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 7621 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7622 << Arg->getSourceRange(); 7623 7624 // If the string is the name of a register then we cannot check that it is 7625 // valid here but if the string is of one the forms described in ACLE then we 7626 // can check that the supplied fields are integers and within the valid 7627 // ranges. 7628 if (Fields.size() > 1) { 7629 bool FiveFields = Fields.size() == 5; 7630 7631 bool ValidString = true; 7632 if (IsARMBuiltin) { 7633 ValidString &= Fields[0].startswith_insensitive("cp") || 7634 Fields[0].startswith_insensitive("p"); 7635 if (ValidString) 7636 Fields[0] = Fields[0].drop_front( 7637 Fields[0].startswith_insensitive("cp") ? 2 : 1); 7638 7639 ValidString &= Fields[2].startswith_insensitive("c"); 7640 if (ValidString) 7641 Fields[2] = Fields[2].drop_front(1); 7642 7643 if (FiveFields) { 7644 ValidString &= Fields[3].startswith_insensitive("c"); 7645 if (ValidString) 7646 Fields[3] = Fields[3].drop_front(1); 7647 } 7648 } 7649 7650 SmallVector<int, 5> Ranges; 7651 if (FiveFields) 7652 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 7653 else 7654 Ranges.append({15, 7, 15}); 7655 7656 for (unsigned i=0; i<Fields.size(); ++i) { 7657 int IntField; 7658 ValidString &= !Fields[i].getAsInteger(10, IntField); 7659 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7660 } 7661 7662 if (!ValidString) 7663 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7664 << Arg->getSourceRange(); 7665 } else if (IsAArch64Builtin && Fields.size() == 1) { 7666 // If the register name is one of those that appear in the condition below 7667 // and the special register builtin being used is one of the write builtins, 7668 // then we require that the argument provided for writing to the register 7669 // is an integer constant expression. This is because it will be lowered to 7670 // an MSR (immediate) instruction, so we need to know the immediate at 7671 // compile time. 7672 if (TheCall->getNumArgs() != 2) 7673 return false; 7674 7675 std::string RegLower = Reg.lower(); 7676 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7677 RegLower != "pan" && RegLower != "uao") 7678 return false; 7679 7680 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7681 } 7682 7683 return false; 7684 } 7685 7686 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7687 /// Emit an error and return true on failure; return false on success. 7688 /// TypeStr is a string containing the type descriptor of the value returned by 7689 /// the builtin and the descriptors of the expected type of the arguments. 7690 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID, 7691 const char *TypeStr) { 7692 7693 assert((TypeStr[0] != '\0') && 7694 "Invalid types in PPC MMA builtin declaration"); 7695 7696 switch (BuiltinID) { 7697 default: 7698 // This function is called in CheckPPCBuiltinFunctionCall where the 7699 // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here 7700 // we are isolating the pair vector memop builtins that can be used with mma 7701 // off so the default case is every builtin that requires mma and paired 7702 // vector memops. 7703 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7704 diag::err_ppc_builtin_only_on_arch, "10") || 7705 SemaFeatureCheck(*this, TheCall, "mma", 7706 diag::err_ppc_builtin_only_on_arch, "10")) 7707 return true; 7708 break; 7709 case PPC::BI__builtin_vsx_lxvp: 7710 case PPC::BI__builtin_vsx_stxvp: 7711 case PPC::BI__builtin_vsx_assemble_pair: 7712 case PPC::BI__builtin_vsx_disassemble_pair: 7713 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7714 diag::err_ppc_builtin_only_on_arch, "10")) 7715 return true; 7716 break; 7717 } 7718 7719 unsigned Mask = 0; 7720 unsigned ArgNum = 0; 7721 7722 // The first type in TypeStr is the type of the value returned by the 7723 // builtin. So we first read that type and change the type of TheCall. 7724 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7725 TheCall->setType(type); 7726 7727 while (*TypeStr != '\0') { 7728 Mask = 0; 7729 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7730 if (ArgNum >= TheCall->getNumArgs()) { 7731 ArgNum++; 7732 break; 7733 } 7734 7735 Expr *Arg = TheCall->getArg(ArgNum); 7736 QualType PassedType = Arg->getType(); 7737 QualType StrippedRVType = PassedType.getCanonicalType(); 7738 7739 // Strip Restrict/Volatile qualifiers. 7740 if (StrippedRVType.isRestrictQualified() || 7741 StrippedRVType.isVolatileQualified()) 7742 StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType(); 7743 7744 // The only case where the argument type and expected type are allowed to 7745 // mismatch is if the argument type is a non-void pointer (or array) and 7746 // expected type is a void pointer. 7747 if (StrippedRVType != ExpectedType) 7748 if (!(ExpectedType->isVoidPointerType() && 7749 (StrippedRVType->isPointerType() || StrippedRVType->isArrayType()))) 7750 return Diag(Arg->getBeginLoc(), 7751 diag::err_typecheck_convert_incompatible) 7752 << PassedType << ExpectedType << 1 << 0 << 0; 7753 7754 // If the value of the Mask is not 0, we have a constraint in the size of 7755 // the integer argument so here we ensure the argument is a constant that 7756 // is in the valid range. 7757 if (Mask != 0 && 7758 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7759 return true; 7760 7761 ArgNum++; 7762 } 7763 7764 // In case we exited early from the previous loop, there are other types to 7765 // read from TypeStr. So we need to read them all to ensure we have the right 7766 // number of arguments in TheCall and if it is not the case, to display a 7767 // better error message. 7768 while (*TypeStr != '\0') { 7769 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7770 ArgNum++; 7771 } 7772 if (checkArgCount(*this, TheCall, ArgNum)) 7773 return true; 7774 7775 return false; 7776 } 7777 7778 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7779 /// This checks that the target supports __builtin_longjmp and 7780 /// that val is a constant 1. 7781 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7782 if (!Context.getTargetInfo().hasSjLjLowering()) 7783 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7784 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7785 7786 Expr *Arg = TheCall->getArg(1); 7787 llvm::APSInt Result; 7788 7789 // TODO: This is less than ideal. Overload this to take a value. 7790 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7791 return true; 7792 7793 if (Result != 1) 7794 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7795 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7796 7797 return false; 7798 } 7799 7800 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7801 /// This checks that the target supports __builtin_setjmp. 7802 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7803 if (!Context.getTargetInfo().hasSjLjLowering()) 7804 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7805 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7806 return false; 7807 } 7808 7809 namespace { 7810 7811 class UncoveredArgHandler { 7812 enum { Unknown = -1, AllCovered = -2 }; 7813 7814 signed FirstUncoveredArg = Unknown; 7815 SmallVector<const Expr *, 4> DiagnosticExprs; 7816 7817 public: 7818 UncoveredArgHandler() = default; 7819 7820 bool hasUncoveredArg() const { 7821 return (FirstUncoveredArg >= 0); 7822 } 7823 7824 unsigned getUncoveredArg() const { 7825 assert(hasUncoveredArg() && "no uncovered argument"); 7826 return FirstUncoveredArg; 7827 } 7828 7829 void setAllCovered() { 7830 // A string has been found with all arguments covered, so clear out 7831 // the diagnostics. 7832 DiagnosticExprs.clear(); 7833 FirstUncoveredArg = AllCovered; 7834 } 7835 7836 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7837 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7838 7839 // Don't update if a previous string covers all arguments. 7840 if (FirstUncoveredArg == AllCovered) 7841 return; 7842 7843 // UncoveredArgHandler tracks the highest uncovered argument index 7844 // and with it all the strings that match this index. 7845 if (NewFirstUncoveredArg == FirstUncoveredArg) 7846 DiagnosticExprs.push_back(StrExpr); 7847 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7848 DiagnosticExprs.clear(); 7849 DiagnosticExprs.push_back(StrExpr); 7850 FirstUncoveredArg = NewFirstUncoveredArg; 7851 } 7852 } 7853 7854 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7855 }; 7856 7857 enum StringLiteralCheckType { 7858 SLCT_NotALiteral, 7859 SLCT_UncheckedLiteral, 7860 SLCT_CheckedLiteral 7861 }; 7862 7863 } // namespace 7864 7865 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7866 BinaryOperatorKind BinOpKind, 7867 bool AddendIsRight) { 7868 unsigned BitWidth = Offset.getBitWidth(); 7869 unsigned AddendBitWidth = Addend.getBitWidth(); 7870 // There might be negative interim results. 7871 if (Addend.isUnsigned()) { 7872 Addend = Addend.zext(++AddendBitWidth); 7873 Addend.setIsSigned(true); 7874 } 7875 // Adjust the bit width of the APSInts. 7876 if (AddendBitWidth > BitWidth) { 7877 Offset = Offset.sext(AddendBitWidth); 7878 BitWidth = AddendBitWidth; 7879 } else if (BitWidth > AddendBitWidth) { 7880 Addend = Addend.sext(BitWidth); 7881 } 7882 7883 bool Ov = false; 7884 llvm::APSInt ResOffset = Offset; 7885 if (BinOpKind == BO_Add) 7886 ResOffset = Offset.sadd_ov(Addend, Ov); 7887 else { 7888 assert(AddendIsRight && BinOpKind == BO_Sub && 7889 "operator must be add or sub with addend on the right"); 7890 ResOffset = Offset.ssub_ov(Addend, Ov); 7891 } 7892 7893 // We add an offset to a pointer here so we should support an offset as big as 7894 // possible. 7895 if (Ov) { 7896 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7897 "index (intermediate) result too big"); 7898 Offset = Offset.sext(2 * BitWidth); 7899 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7900 return; 7901 } 7902 7903 Offset = ResOffset; 7904 } 7905 7906 namespace { 7907 7908 // This is a wrapper class around StringLiteral to support offsetted string 7909 // literals as format strings. It takes the offset into account when returning 7910 // the string and its length or the source locations to display notes correctly. 7911 class FormatStringLiteral { 7912 const StringLiteral *FExpr; 7913 int64_t Offset; 7914 7915 public: 7916 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7917 : FExpr(fexpr), Offset(Offset) {} 7918 7919 StringRef getString() const { 7920 return FExpr->getString().drop_front(Offset); 7921 } 7922 7923 unsigned getByteLength() const { 7924 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7925 } 7926 7927 unsigned getLength() const { return FExpr->getLength() - Offset; } 7928 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7929 7930 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7931 7932 QualType getType() const { return FExpr->getType(); } 7933 7934 bool isAscii() const { return FExpr->isAscii(); } 7935 bool isWide() const { return FExpr->isWide(); } 7936 bool isUTF8() const { return FExpr->isUTF8(); } 7937 bool isUTF16() const { return FExpr->isUTF16(); } 7938 bool isUTF32() const { return FExpr->isUTF32(); } 7939 bool isPascal() const { return FExpr->isPascal(); } 7940 7941 SourceLocation getLocationOfByte( 7942 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7943 const TargetInfo &Target, unsigned *StartToken = nullptr, 7944 unsigned *StartTokenByteOffset = nullptr) const { 7945 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7946 StartToken, StartTokenByteOffset); 7947 } 7948 7949 SourceLocation getBeginLoc() const LLVM_READONLY { 7950 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7951 } 7952 7953 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7954 }; 7955 7956 } // namespace 7957 7958 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7959 const Expr *OrigFormatExpr, 7960 ArrayRef<const Expr *> Args, 7961 bool HasVAListArg, unsigned format_idx, 7962 unsigned firstDataArg, 7963 Sema::FormatStringType Type, 7964 bool inFunctionCall, 7965 Sema::VariadicCallType CallType, 7966 llvm::SmallBitVector &CheckedVarArgs, 7967 UncoveredArgHandler &UncoveredArg, 7968 bool IgnoreStringsWithoutSpecifiers); 7969 7970 // Determine if an expression is a string literal or constant string. 7971 // If this function returns false on the arguments to a function expecting a 7972 // format string, we will usually need to emit a warning. 7973 // True string literals are then checked by CheckFormatString. 7974 static StringLiteralCheckType 7975 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7976 bool HasVAListArg, unsigned format_idx, 7977 unsigned firstDataArg, Sema::FormatStringType Type, 7978 Sema::VariadicCallType CallType, bool InFunctionCall, 7979 llvm::SmallBitVector &CheckedVarArgs, 7980 UncoveredArgHandler &UncoveredArg, 7981 llvm::APSInt Offset, 7982 bool IgnoreStringsWithoutSpecifiers = false) { 7983 if (S.isConstantEvaluated()) 7984 return SLCT_NotALiteral; 7985 tryAgain: 7986 assert(Offset.isSigned() && "invalid offset"); 7987 7988 if (E->isTypeDependent() || E->isValueDependent()) 7989 return SLCT_NotALiteral; 7990 7991 E = E->IgnoreParenCasts(); 7992 7993 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7994 // Technically -Wformat-nonliteral does not warn about this case. 7995 // The behavior of printf and friends in this case is implementation 7996 // dependent. Ideally if the format string cannot be null then 7997 // it should have a 'nonnull' attribute in the function prototype. 7998 return SLCT_UncheckedLiteral; 7999 8000 switch (E->getStmtClass()) { 8001 case Stmt::BinaryConditionalOperatorClass: 8002 case Stmt::ConditionalOperatorClass: { 8003 // The expression is a literal if both sub-expressions were, and it was 8004 // completely checked only if both sub-expressions were checked. 8005 const AbstractConditionalOperator *C = 8006 cast<AbstractConditionalOperator>(E); 8007 8008 // Determine whether it is necessary to check both sub-expressions, for 8009 // example, because the condition expression is a constant that can be 8010 // evaluated at compile time. 8011 bool CheckLeft = true, CheckRight = true; 8012 8013 bool Cond; 8014 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 8015 S.isConstantEvaluated())) { 8016 if (Cond) 8017 CheckRight = false; 8018 else 8019 CheckLeft = false; 8020 } 8021 8022 // We need to maintain the offsets for the right and the left hand side 8023 // separately to check if every possible indexed expression is a valid 8024 // string literal. They might have different offsets for different string 8025 // literals in the end. 8026 StringLiteralCheckType Left; 8027 if (!CheckLeft) 8028 Left = SLCT_UncheckedLiteral; 8029 else { 8030 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 8031 HasVAListArg, format_idx, firstDataArg, 8032 Type, CallType, InFunctionCall, 8033 CheckedVarArgs, UncoveredArg, Offset, 8034 IgnoreStringsWithoutSpecifiers); 8035 if (Left == SLCT_NotALiteral || !CheckRight) { 8036 return Left; 8037 } 8038 } 8039 8040 StringLiteralCheckType Right = checkFormatStringExpr( 8041 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 8042 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8043 IgnoreStringsWithoutSpecifiers); 8044 8045 return (CheckLeft && Left < Right) ? Left : Right; 8046 } 8047 8048 case Stmt::ImplicitCastExprClass: 8049 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 8050 goto tryAgain; 8051 8052 case Stmt::OpaqueValueExprClass: 8053 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 8054 E = src; 8055 goto tryAgain; 8056 } 8057 return SLCT_NotALiteral; 8058 8059 case Stmt::PredefinedExprClass: 8060 // While __func__, etc., are technically not string literals, they 8061 // cannot contain format specifiers and thus are not a security 8062 // liability. 8063 return SLCT_UncheckedLiteral; 8064 8065 case Stmt::DeclRefExprClass: { 8066 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8067 8068 // As an exception, do not flag errors for variables binding to 8069 // const string literals. 8070 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 8071 bool isConstant = false; 8072 QualType T = DR->getType(); 8073 8074 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 8075 isConstant = AT->getElementType().isConstant(S.Context); 8076 } else if (const PointerType *PT = T->getAs<PointerType>()) { 8077 isConstant = T.isConstant(S.Context) && 8078 PT->getPointeeType().isConstant(S.Context); 8079 } else if (T->isObjCObjectPointerType()) { 8080 // In ObjC, there is usually no "const ObjectPointer" type, 8081 // so don't check if the pointee type is constant. 8082 isConstant = T.isConstant(S.Context); 8083 } 8084 8085 if (isConstant) { 8086 if (const Expr *Init = VD->getAnyInitializer()) { 8087 // Look through initializers like const char c[] = { "foo" } 8088 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 8089 if (InitList->isStringLiteralInit()) 8090 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 8091 } 8092 return checkFormatStringExpr(S, Init, Args, 8093 HasVAListArg, format_idx, 8094 firstDataArg, Type, CallType, 8095 /*InFunctionCall*/ false, CheckedVarArgs, 8096 UncoveredArg, Offset); 8097 } 8098 } 8099 8100 // For vprintf* functions (i.e., HasVAListArg==true), we add a 8101 // special check to see if the format string is a function parameter 8102 // of the function calling the printf function. If the function 8103 // has an attribute indicating it is a printf-like function, then we 8104 // should suppress warnings concerning non-literals being used in a call 8105 // to a vprintf function. For example: 8106 // 8107 // void 8108 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 8109 // va_list ap; 8110 // va_start(ap, fmt); 8111 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 8112 // ... 8113 // } 8114 if (HasVAListArg) { 8115 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 8116 if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) { 8117 int PVIndex = PV->getFunctionScopeIndex() + 1; 8118 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) { 8119 // adjust for implicit parameter 8120 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) 8121 if (MD->isInstance()) 8122 ++PVIndex; 8123 // We also check if the formats are compatible. 8124 // We can't pass a 'scanf' string to a 'printf' function. 8125 if (PVIndex == PVFormat->getFormatIdx() && 8126 Type == S.GetFormatStringType(PVFormat)) 8127 return SLCT_UncheckedLiteral; 8128 } 8129 } 8130 } 8131 } 8132 } 8133 8134 return SLCT_NotALiteral; 8135 } 8136 8137 case Stmt::CallExprClass: 8138 case Stmt::CXXMemberCallExprClass: { 8139 const CallExpr *CE = cast<CallExpr>(E); 8140 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 8141 bool IsFirst = true; 8142 StringLiteralCheckType CommonResult; 8143 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 8144 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 8145 StringLiteralCheckType Result = checkFormatStringExpr( 8146 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 8147 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8148 IgnoreStringsWithoutSpecifiers); 8149 if (IsFirst) { 8150 CommonResult = Result; 8151 IsFirst = false; 8152 } 8153 } 8154 if (!IsFirst) 8155 return CommonResult; 8156 8157 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 8158 unsigned BuiltinID = FD->getBuiltinID(); 8159 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 8160 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 8161 const Expr *Arg = CE->getArg(0); 8162 return checkFormatStringExpr(S, Arg, Args, 8163 HasVAListArg, format_idx, 8164 firstDataArg, Type, CallType, 8165 InFunctionCall, CheckedVarArgs, 8166 UncoveredArg, Offset, 8167 IgnoreStringsWithoutSpecifiers); 8168 } 8169 } 8170 } 8171 8172 return SLCT_NotALiteral; 8173 } 8174 case Stmt::ObjCMessageExprClass: { 8175 const auto *ME = cast<ObjCMessageExpr>(E); 8176 if (const auto *MD = ME->getMethodDecl()) { 8177 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 8178 // As a special case heuristic, if we're using the method -[NSBundle 8179 // localizedStringForKey:value:table:], ignore any key strings that lack 8180 // format specifiers. The idea is that if the key doesn't have any 8181 // format specifiers then its probably just a key to map to the 8182 // localized strings. If it does have format specifiers though, then its 8183 // likely that the text of the key is the format string in the 8184 // programmer's language, and should be checked. 8185 const ObjCInterfaceDecl *IFace; 8186 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 8187 IFace->getIdentifier()->isStr("NSBundle") && 8188 MD->getSelector().isKeywordSelector( 8189 {"localizedStringForKey", "value", "table"})) { 8190 IgnoreStringsWithoutSpecifiers = true; 8191 } 8192 8193 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 8194 return checkFormatStringExpr( 8195 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 8196 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8197 IgnoreStringsWithoutSpecifiers); 8198 } 8199 } 8200 8201 return SLCT_NotALiteral; 8202 } 8203 case Stmt::ObjCStringLiteralClass: 8204 case Stmt::StringLiteralClass: { 8205 const StringLiteral *StrE = nullptr; 8206 8207 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 8208 StrE = ObjCFExpr->getString(); 8209 else 8210 StrE = cast<StringLiteral>(E); 8211 8212 if (StrE) { 8213 if (Offset.isNegative() || Offset > StrE->getLength()) { 8214 // TODO: It would be better to have an explicit warning for out of 8215 // bounds literals. 8216 return SLCT_NotALiteral; 8217 } 8218 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 8219 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 8220 firstDataArg, Type, InFunctionCall, CallType, 8221 CheckedVarArgs, UncoveredArg, 8222 IgnoreStringsWithoutSpecifiers); 8223 return SLCT_CheckedLiteral; 8224 } 8225 8226 return SLCT_NotALiteral; 8227 } 8228 case Stmt::BinaryOperatorClass: { 8229 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 8230 8231 // A string literal + an int offset is still a string literal. 8232 if (BinOp->isAdditiveOp()) { 8233 Expr::EvalResult LResult, RResult; 8234 8235 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 8236 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8237 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 8238 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8239 8240 if (LIsInt != RIsInt) { 8241 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 8242 8243 if (LIsInt) { 8244 if (BinOpKind == BO_Add) { 8245 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 8246 E = BinOp->getRHS(); 8247 goto tryAgain; 8248 } 8249 } else { 8250 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 8251 E = BinOp->getLHS(); 8252 goto tryAgain; 8253 } 8254 } 8255 } 8256 8257 return SLCT_NotALiteral; 8258 } 8259 case Stmt::UnaryOperatorClass: { 8260 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 8261 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 8262 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 8263 Expr::EvalResult IndexResult; 8264 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 8265 Expr::SE_NoSideEffects, 8266 S.isConstantEvaluated())) { 8267 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 8268 /*RHS is int*/ true); 8269 E = ASE->getBase(); 8270 goto tryAgain; 8271 } 8272 } 8273 8274 return SLCT_NotALiteral; 8275 } 8276 8277 default: 8278 return SLCT_NotALiteral; 8279 } 8280 } 8281 8282 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 8283 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 8284 .Case("scanf", FST_Scanf) 8285 .Cases("printf", "printf0", FST_Printf) 8286 .Cases("NSString", "CFString", FST_NSString) 8287 .Case("strftime", FST_Strftime) 8288 .Case("strfmon", FST_Strfmon) 8289 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 8290 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 8291 .Case("os_trace", FST_OSLog) 8292 .Case("os_log", FST_OSLog) 8293 .Default(FST_Unknown); 8294 } 8295 8296 /// CheckFormatArguments - Check calls to printf and scanf (and similar 8297 /// functions) for correct use of format strings. 8298 /// Returns true if a format string has been fully checked. 8299 bool Sema::CheckFormatArguments(const FormatAttr *Format, 8300 ArrayRef<const Expr *> Args, 8301 bool IsCXXMember, 8302 VariadicCallType CallType, 8303 SourceLocation Loc, SourceRange Range, 8304 llvm::SmallBitVector &CheckedVarArgs) { 8305 FormatStringInfo FSI; 8306 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 8307 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 8308 FSI.FirstDataArg, GetFormatStringType(Format), 8309 CallType, Loc, Range, CheckedVarArgs); 8310 return false; 8311 } 8312 8313 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 8314 bool HasVAListArg, unsigned format_idx, 8315 unsigned firstDataArg, FormatStringType Type, 8316 VariadicCallType CallType, 8317 SourceLocation Loc, SourceRange Range, 8318 llvm::SmallBitVector &CheckedVarArgs) { 8319 // CHECK: printf/scanf-like function is called with no format string. 8320 if (format_idx >= Args.size()) { 8321 Diag(Loc, diag::warn_missing_format_string) << Range; 8322 return false; 8323 } 8324 8325 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 8326 8327 // CHECK: format string is not a string literal. 8328 // 8329 // Dynamically generated format strings are difficult to 8330 // automatically vet at compile time. Requiring that format strings 8331 // are string literals: (1) permits the checking of format strings by 8332 // the compiler and thereby (2) can practically remove the source of 8333 // many format string exploits. 8334 8335 // Format string can be either ObjC string (e.g. @"%d") or 8336 // C string (e.g. "%d") 8337 // ObjC string uses the same format specifiers as C string, so we can use 8338 // the same format string checking logic for both ObjC and C strings. 8339 UncoveredArgHandler UncoveredArg; 8340 StringLiteralCheckType CT = 8341 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 8342 format_idx, firstDataArg, Type, CallType, 8343 /*IsFunctionCall*/ true, CheckedVarArgs, 8344 UncoveredArg, 8345 /*no string offset*/ llvm::APSInt(64, false) = 0); 8346 8347 // Generate a diagnostic where an uncovered argument is detected. 8348 if (UncoveredArg.hasUncoveredArg()) { 8349 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 8350 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 8351 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 8352 } 8353 8354 if (CT != SLCT_NotALiteral) 8355 // Literal format string found, check done! 8356 return CT == SLCT_CheckedLiteral; 8357 8358 // Strftime is particular as it always uses a single 'time' argument, 8359 // so it is safe to pass a non-literal string. 8360 if (Type == FST_Strftime) 8361 return false; 8362 8363 // Do not emit diag when the string param is a macro expansion and the 8364 // format is either NSString or CFString. This is a hack to prevent 8365 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 8366 // which are usually used in place of NS and CF string literals. 8367 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 8368 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 8369 return false; 8370 8371 // If there are no arguments specified, warn with -Wformat-security, otherwise 8372 // warn only with -Wformat-nonliteral. 8373 if (Args.size() == firstDataArg) { 8374 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 8375 << OrigFormatExpr->getSourceRange(); 8376 switch (Type) { 8377 default: 8378 break; 8379 case FST_Kprintf: 8380 case FST_FreeBSDKPrintf: 8381 case FST_Printf: 8382 Diag(FormatLoc, diag::note_format_security_fixit) 8383 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 8384 break; 8385 case FST_NSString: 8386 Diag(FormatLoc, diag::note_format_security_fixit) 8387 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 8388 break; 8389 } 8390 } else { 8391 Diag(FormatLoc, diag::warn_format_nonliteral) 8392 << OrigFormatExpr->getSourceRange(); 8393 } 8394 return false; 8395 } 8396 8397 namespace { 8398 8399 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 8400 protected: 8401 Sema &S; 8402 const FormatStringLiteral *FExpr; 8403 const Expr *OrigFormatExpr; 8404 const Sema::FormatStringType FSType; 8405 const unsigned FirstDataArg; 8406 const unsigned NumDataArgs; 8407 const char *Beg; // Start of format string. 8408 const bool HasVAListArg; 8409 ArrayRef<const Expr *> Args; 8410 unsigned FormatIdx; 8411 llvm::SmallBitVector CoveredArgs; 8412 bool usesPositionalArgs = false; 8413 bool atFirstArg = true; 8414 bool inFunctionCall; 8415 Sema::VariadicCallType CallType; 8416 llvm::SmallBitVector &CheckedVarArgs; 8417 UncoveredArgHandler &UncoveredArg; 8418 8419 public: 8420 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 8421 const Expr *origFormatExpr, 8422 const Sema::FormatStringType type, unsigned firstDataArg, 8423 unsigned numDataArgs, const char *beg, bool hasVAListArg, 8424 ArrayRef<const Expr *> Args, unsigned formatIdx, 8425 bool inFunctionCall, Sema::VariadicCallType callType, 8426 llvm::SmallBitVector &CheckedVarArgs, 8427 UncoveredArgHandler &UncoveredArg) 8428 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 8429 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 8430 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 8431 inFunctionCall(inFunctionCall), CallType(callType), 8432 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 8433 CoveredArgs.resize(numDataArgs); 8434 CoveredArgs.reset(); 8435 } 8436 8437 void DoneProcessing(); 8438 8439 void HandleIncompleteSpecifier(const char *startSpecifier, 8440 unsigned specifierLen) override; 8441 8442 void HandleInvalidLengthModifier( 8443 const analyze_format_string::FormatSpecifier &FS, 8444 const analyze_format_string::ConversionSpecifier &CS, 8445 const char *startSpecifier, unsigned specifierLen, 8446 unsigned DiagID); 8447 8448 void HandleNonStandardLengthModifier( 8449 const analyze_format_string::FormatSpecifier &FS, 8450 const char *startSpecifier, unsigned specifierLen); 8451 8452 void HandleNonStandardConversionSpecifier( 8453 const analyze_format_string::ConversionSpecifier &CS, 8454 const char *startSpecifier, unsigned specifierLen); 8455 8456 void HandlePosition(const char *startPos, unsigned posLen) override; 8457 8458 void HandleInvalidPosition(const char *startSpecifier, 8459 unsigned specifierLen, 8460 analyze_format_string::PositionContext p) override; 8461 8462 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 8463 8464 void HandleNullChar(const char *nullCharacter) override; 8465 8466 template <typename Range> 8467 static void 8468 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 8469 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 8470 bool IsStringLocation, Range StringRange, 8471 ArrayRef<FixItHint> Fixit = None); 8472 8473 protected: 8474 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 8475 const char *startSpec, 8476 unsigned specifierLen, 8477 const char *csStart, unsigned csLen); 8478 8479 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 8480 const char *startSpec, 8481 unsigned specifierLen); 8482 8483 SourceRange getFormatStringRange(); 8484 CharSourceRange getSpecifierRange(const char *startSpecifier, 8485 unsigned specifierLen); 8486 SourceLocation getLocationOfByte(const char *x); 8487 8488 const Expr *getDataArg(unsigned i) const; 8489 8490 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 8491 const analyze_format_string::ConversionSpecifier &CS, 8492 const char *startSpecifier, unsigned specifierLen, 8493 unsigned argIndex); 8494 8495 template <typename Range> 8496 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 8497 bool IsStringLocation, Range StringRange, 8498 ArrayRef<FixItHint> Fixit = None); 8499 }; 8500 8501 } // namespace 8502 8503 SourceRange CheckFormatHandler::getFormatStringRange() { 8504 return OrigFormatExpr->getSourceRange(); 8505 } 8506 8507 CharSourceRange CheckFormatHandler:: 8508 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 8509 SourceLocation Start = getLocationOfByte(startSpecifier); 8510 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 8511 8512 // Advance the end SourceLocation by one due to half-open ranges. 8513 End = End.getLocWithOffset(1); 8514 8515 return CharSourceRange::getCharRange(Start, End); 8516 } 8517 8518 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 8519 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 8520 S.getLangOpts(), S.Context.getTargetInfo()); 8521 } 8522 8523 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 8524 unsigned specifierLen){ 8525 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 8526 getLocationOfByte(startSpecifier), 8527 /*IsStringLocation*/true, 8528 getSpecifierRange(startSpecifier, specifierLen)); 8529 } 8530 8531 void CheckFormatHandler::HandleInvalidLengthModifier( 8532 const analyze_format_string::FormatSpecifier &FS, 8533 const analyze_format_string::ConversionSpecifier &CS, 8534 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 8535 using namespace analyze_format_string; 8536 8537 const LengthModifier &LM = FS.getLengthModifier(); 8538 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8539 8540 // See if we know how to fix this length modifier. 8541 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8542 if (FixedLM) { 8543 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8544 getLocationOfByte(LM.getStart()), 8545 /*IsStringLocation*/true, 8546 getSpecifierRange(startSpecifier, specifierLen)); 8547 8548 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8549 << FixedLM->toString() 8550 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8551 8552 } else { 8553 FixItHint Hint; 8554 if (DiagID == diag::warn_format_nonsensical_length) 8555 Hint = FixItHint::CreateRemoval(LMRange); 8556 8557 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8558 getLocationOfByte(LM.getStart()), 8559 /*IsStringLocation*/true, 8560 getSpecifierRange(startSpecifier, specifierLen), 8561 Hint); 8562 } 8563 } 8564 8565 void CheckFormatHandler::HandleNonStandardLengthModifier( 8566 const analyze_format_string::FormatSpecifier &FS, 8567 const char *startSpecifier, unsigned specifierLen) { 8568 using namespace analyze_format_string; 8569 8570 const LengthModifier &LM = FS.getLengthModifier(); 8571 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8572 8573 // See if we know how to fix this length modifier. 8574 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8575 if (FixedLM) { 8576 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8577 << LM.toString() << 0, 8578 getLocationOfByte(LM.getStart()), 8579 /*IsStringLocation*/true, 8580 getSpecifierRange(startSpecifier, specifierLen)); 8581 8582 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8583 << FixedLM->toString() 8584 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8585 8586 } else { 8587 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8588 << LM.toString() << 0, 8589 getLocationOfByte(LM.getStart()), 8590 /*IsStringLocation*/true, 8591 getSpecifierRange(startSpecifier, specifierLen)); 8592 } 8593 } 8594 8595 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 8596 const analyze_format_string::ConversionSpecifier &CS, 8597 const char *startSpecifier, unsigned specifierLen) { 8598 using namespace analyze_format_string; 8599 8600 // See if we know how to fix this conversion specifier. 8601 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 8602 if (FixedCS) { 8603 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8604 << CS.toString() << /*conversion specifier*/1, 8605 getLocationOfByte(CS.getStart()), 8606 /*IsStringLocation*/true, 8607 getSpecifierRange(startSpecifier, specifierLen)); 8608 8609 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 8610 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 8611 << FixedCS->toString() 8612 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 8613 } else { 8614 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8615 << CS.toString() << /*conversion specifier*/1, 8616 getLocationOfByte(CS.getStart()), 8617 /*IsStringLocation*/true, 8618 getSpecifierRange(startSpecifier, specifierLen)); 8619 } 8620 } 8621 8622 void CheckFormatHandler::HandlePosition(const char *startPos, 8623 unsigned posLen) { 8624 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 8625 getLocationOfByte(startPos), 8626 /*IsStringLocation*/true, 8627 getSpecifierRange(startPos, posLen)); 8628 } 8629 8630 void 8631 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 8632 analyze_format_string::PositionContext p) { 8633 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 8634 << (unsigned) p, 8635 getLocationOfByte(startPos), /*IsStringLocation*/true, 8636 getSpecifierRange(startPos, posLen)); 8637 } 8638 8639 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 8640 unsigned posLen) { 8641 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 8642 getLocationOfByte(startPos), 8643 /*IsStringLocation*/true, 8644 getSpecifierRange(startPos, posLen)); 8645 } 8646 8647 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 8648 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 8649 // The presence of a null character is likely an error. 8650 EmitFormatDiagnostic( 8651 S.PDiag(diag::warn_printf_format_string_contains_null_char), 8652 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 8653 getFormatStringRange()); 8654 } 8655 } 8656 8657 // Note that this may return NULL if there was an error parsing or building 8658 // one of the argument expressions. 8659 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 8660 return Args[FirstDataArg + i]; 8661 } 8662 8663 void CheckFormatHandler::DoneProcessing() { 8664 // Does the number of data arguments exceed the number of 8665 // format conversions in the format string? 8666 if (!HasVAListArg) { 8667 // Find any arguments that weren't covered. 8668 CoveredArgs.flip(); 8669 signed notCoveredArg = CoveredArgs.find_first(); 8670 if (notCoveredArg >= 0) { 8671 assert((unsigned)notCoveredArg < NumDataArgs); 8672 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 8673 } else { 8674 UncoveredArg.setAllCovered(); 8675 } 8676 } 8677 } 8678 8679 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 8680 const Expr *ArgExpr) { 8681 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 8682 "Invalid state"); 8683 8684 if (!ArgExpr) 8685 return; 8686 8687 SourceLocation Loc = ArgExpr->getBeginLoc(); 8688 8689 if (S.getSourceManager().isInSystemMacro(Loc)) 8690 return; 8691 8692 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8693 for (auto E : DiagnosticExprs) 8694 PDiag << E->getSourceRange(); 8695 8696 CheckFormatHandler::EmitFormatDiagnostic( 8697 S, IsFunctionCall, DiagnosticExprs[0], 8698 PDiag, Loc, /*IsStringLocation*/false, 8699 DiagnosticExprs[0]->getSourceRange()); 8700 } 8701 8702 bool 8703 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8704 SourceLocation Loc, 8705 const char *startSpec, 8706 unsigned specifierLen, 8707 const char *csStart, 8708 unsigned csLen) { 8709 bool keepGoing = true; 8710 if (argIndex < NumDataArgs) { 8711 // Consider the argument coverered, even though the specifier doesn't 8712 // make sense. 8713 CoveredArgs.set(argIndex); 8714 } 8715 else { 8716 // If argIndex exceeds the number of data arguments we 8717 // don't issue a warning because that is just a cascade of warnings (and 8718 // they may have intended '%%' anyway). We don't want to continue processing 8719 // the format string after this point, however, as we will like just get 8720 // gibberish when trying to match arguments. 8721 keepGoing = false; 8722 } 8723 8724 StringRef Specifier(csStart, csLen); 8725 8726 // If the specifier in non-printable, it could be the first byte of a UTF-8 8727 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8728 // hex value. 8729 std::string CodePointStr; 8730 if (!llvm::sys::locale::isPrint(*csStart)) { 8731 llvm::UTF32 CodePoint; 8732 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8733 const llvm::UTF8 *E = 8734 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8735 llvm::ConversionResult Result = 8736 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8737 8738 if (Result != llvm::conversionOK) { 8739 unsigned char FirstChar = *csStart; 8740 CodePoint = (llvm::UTF32)FirstChar; 8741 } 8742 8743 llvm::raw_string_ostream OS(CodePointStr); 8744 if (CodePoint < 256) 8745 OS << "\\x" << llvm::format("%02x", CodePoint); 8746 else if (CodePoint <= 0xFFFF) 8747 OS << "\\u" << llvm::format("%04x", CodePoint); 8748 else 8749 OS << "\\U" << llvm::format("%08x", CodePoint); 8750 OS.flush(); 8751 Specifier = CodePointStr; 8752 } 8753 8754 EmitFormatDiagnostic( 8755 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8756 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8757 8758 return keepGoing; 8759 } 8760 8761 void 8762 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8763 const char *startSpec, 8764 unsigned specifierLen) { 8765 EmitFormatDiagnostic( 8766 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8767 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8768 } 8769 8770 bool 8771 CheckFormatHandler::CheckNumArgs( 8772 const analyze_format_string::FormatSpecifier &FS, 8773 const analyze_format_string::ConversionSpecifier &CS, 8774 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8775 8776 if (argIndex >= NumDataArgs) { 8777 PartialDiagnostic PDiag = FS.usesPositionalArg() 8778 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8779 << (argIndex+1) << NumDataArgs) 8780 : S.PDiag(diag::warn_printf_insufficient_data_args); 8781 EmitFormatDiagnostic( 8782 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8783 getSpecifierRange(startSpecifier, specifierLen)); 8784 8785 // Since more arguments than conversion tokens are given, by extension 8786 // all arguments are covered, so mark this as so. 8787 UncoveredArg.setAllCovered(); 8788 return false; 8789 } 8790 return true; 8791 } 8792 8793 template<typename Range> 8794 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8795 SourceLocation Loc, 8796 bool IsStringLocation, 8797 Range StringRange, 8798 ArrayRef<FixItHint> FixIt) { 8799 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8800 Loc, IsStringLocation, StringRange, FixIt); 8801 } 8802 8803 /// If the format string is not within the function call, emit a note 8804 /// so that the function call and string are in diagnostic messages. 8805 /// 8806 /// \param InFunctionCall if true, the format string is within the function 8807 /// call and only one diagnostic message will be produced. Otherwise, an 8808 /// extra note will be emitted pointing to location of the format string. 8809 /// 8810 /// \param ArgumentExpr the expression that is passed as the format string 8811 /// argument in the function call. Used for getting locations when two 8812 /// diagnostics are emitted. 8813 /// 8814 /// \param PDiag the callee should already have provided any strings for the 8815 /// diagnostic message. This function only adds locations and fixits 8816 /// to diagnostics. 8817 /// 8818 /// \param Loc primary location for diagnostic. If two diagnostics are 8819 /// required, one will be at Loc and a new SourceLocation will be created for 8820 /// the other one. 8821 /// 8822 /// \param IsStringLocation if true, Loc points to the format string should be 8823 /// used for the note. Otherwise, Loc points to the argument list and will 8824 /// be used with PDiag. 8825 /// 8826 /// \param StringRange some or all of the string to highlight. This is 8827 /// templated so it can accept either a CharSourceRange or a SourceRange. 8828 /// 8829 /// \param FixIt optional fix it hint for the format string. 8830 template <typename Range> 8831 void CheckFormatHandler::EmitFormatDiagnostic( 8832 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8833 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8834 Range StringRange, ArrayRef<FixItHint> FixIt) { 8835 if (InFunctionCall) { 8836 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8837 D << StringRange; 8838 D << FixIt; 8839 } else { 8840 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8841 << ArgumentExpr->getSourceRange(); 8842 8843 const Sema::SemaDiagnosticBuilder &Note = 8844 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8845 diag::note_format_string_defined); 8846 8847 Note << StringRange; 8848 Note << FixIt; 8849 } 8850 } 8851 8852 //===--- CHECK: Printf format string checking ------------------------------===// 8853 8854 namespace { 8855 8856 class CheckPrintfHandler : public CheckFormatHandler { 8857 public: 8858 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8859 const Expr *origFormatExpr, 8860 const Sema::FormatStringType type, unsigned firstDataArg, 8861 unsigned numDataArgs, bool isObjC, const char *beg, 8862 bool hasVAListArg, ArrayRef<const Expr *> Args, 8863 unsigned formatIdx, bool inFunctionCall, 8864 Sema::VariadicCallType CallType, 8865 llvm::SmallBitVector &CheckedVarArgs, 8866 UncoveredArgHandler &UncoveredArg) 8867 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8868 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8869 inFunctionCall, CallType, CheckedVarArgs, 8870 UncoveredArg) {} 8871 8872 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8873 8874 /// Returns true if '%@' specifiers are allowed in the format string. 8875 bool allowsObjCArg() const { 8876 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8877 FSType == Sema::FST_OSTrace; 8878 } 8879 8880 bool HandleInvalidPrintfConversionSpecifier( 8881 const analyze_printf::PrintfSpecifier &FS, 8882 const char *startSpecifier, 8883 unsigned specifierLen) override; 8884 8885 void handleInvalidMaskType(StringRef MaskType) override; 8886 8887 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8888 const char *startSpecifier, 8889 unsigned specifierLen) override; 8890 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8891 const char *StartSpecifier, 8892 unsigned SpecifierLen, 8893 const Expr *E); 8894 8895 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8896 const char *startSpecifier, unsigned specifierLen); 8897 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8898 const analyze_printf::OptionalAmount &Amt, 8899 unsigned type, 8900 const char *startSpecifier, unsigned specifierLen); 8901 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8902 const analyze_printf::OptionalFlag &flag, 8903 const char *startSpecifier, unsigned specifierLen); 8904 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8905 const analyze_printf::OptionalFlag &ignoredFlag, 8906 const analyze_printf::OptionalFlag &flag, 8907 const char *startSpecifier, unsigned specifierLen); 8908 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8909 const Expr *E); 8910 8911 void HandleEmptyObjCModifierFlag(const char *startFlag, 8912 unsigned flagLen) override; 8913 8914 void HandleInvalidObjCModifierFlag(const char *startFlag, 8915 unsigned flagLen) override; 8916 8917 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8918 const char *flagsEnd, 8919 const char *conversionPosition) 8920 override; 8921 }; 8922 8923 } // namespace 8924 8925 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8926 const analyze_printf::PrintfSpecifier &FS, 8927 const char *startSpecifier, 8928 unsigned specifierLen) { 8929 const analyze_printf::PrintfConversionSpecifier &CS = 8930 FS.getConversionSpecifier(); 8931 8932 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8933 getLocationOfByte(CS.getStart()), 8934 startSpecifier, specifierLen, 8935 CS.getStart(), CS.getLength()); 8936 } 8937 8938 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8939 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8940 } 8941 8942 bool CheckPrintfHandler::HandleAmount( 8943 const analyze_format_string::OptionalAmount &Amt, 8944 unsigned k, const char *startSpecifier, 8945 unsigned specifierLen) { 8946 if (Amt.hasDataArgument()) { 8947 if (!HasVAListArg) { 8948 unsigned argIndex = Amt.getArgIndex(); 8949 if (argIndex >= NumDataArgs) { 8950 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8951 << k, 8952 getLocationOfByte(Amt.getStart()), 8953 /*IsStringLocation*/true, 8954 getSpecifierRange(startSpecifier, specifierLen)); 8955 // Don't do any more checking. We will just emit 8956 // spurious errors. 8957 return false; 8958 } 8959 8960 // Type check the data argument. It should be an 'int'. 8961 // Although not in conformance with C99, we also allow the argument to be 8962 // an 'unsigned int' as that is a reasonably safe case. GCC also 8963 // doesn't emit a warning for that case. 8964 CoveredArgs.set(argIndex); 8965 const Expr *Arg = getDataArg(argIndex); 8966 if (!Arg) 8967 return false; 8968 8969 QualType T = Arg->getType(); 8970 8971 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8972 assert(AT.isValid()); 8973 8974 if (!AT.matchesType(S.Context, T)) { 8975 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8976 << k << AT.getRepresentativeTypeName(S.Context) 8977 << T << Arg->getSourceRange(), 8978 getLocationOfByte(Amt.getStart()), 8979 /*IsStringLocation*/true, 8980 getSpecifierRange(startSpecifier, specifierLen)); 8981 // Don't do any more checking. We will just emit 8982 // spurious errors. 8983 return false; 8984 } 8985 } 8986 } 8987 return true; 8988 } 8989 8990 void CheckPrintfHandler::HandleInvalidAmount( 8991 const analyze_printf::PrintfSpecifier &FS, 8992 const analyze_printf::OptionalAmount &Amt, 8993 unsigned type, 8994 const char *startSpecifier, 8995 unsigned specifierLen) { 8996 const analyze_printf::PrintfConversionSpecifier &CS = 8997 FS.getConversionSpecifier(); 8998 8999 FixItHint fixit = 9000 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 9001 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 9002 Amt.getConstantLength())) 9003 : FixItHint(); 9004 9005 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 9006 << type << CS.toString(), 9007 getLocationOfByte(Amt.getStart()), 9008 /*IsStringLocation*/true, 9009 getSpecifierRange(startSpecifier, specifierLen), 9010 fixit); 9011 } 9012 9013 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 9014 const analyze_printf::OptionalFlag &flag, 9015 const char *startSpecifier, 9016 unsigned specifierLen) { 9017 // Warn about pointless flag with a fixit removal. 9018 const analyze_printf::PrintfConversionSpecifier &CS = 9019 FS.getConversionSpecifier(); 9020 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 9021 << flag.toString() << CS.toString(), 9022 getLocationOfByte(flag.getPosition()), 9023 /*IsStringLocation*/true, 9024 getSpecifierRange(startSpecifier, specifierLen), 9025 FixItHint::CreateRemoval( 9026 getSpecifierRange(flag.getPosition(), 1))); 9027 } 9028 9029 void CheckPrintfHandler::HandleIgnoredFlag( 9030 const analyze_printf::PrintfSpecifier &FS, 9031 const analyze_printf::OptionalFlag &ignoredFlag, 9032 const analyze_printf::OptionalFlag &flag, 9033 const char *startSpecifier, 9034 unsigned specifierLen) { 9035 // Warn about ignored flag with a fixit removal. 9036 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 9037 << ignoredFlag.toString() << flag.toString(), 9038 getLocationOfByte(ignoredFlag.getPosition()), 9039 /*IsStringLocation*/true, 9040 getSpecifierRange(startSpecifier, specifierLen), 9041 FixItHint::CreateRemoval( 9042 getSpecifierRange(ignoredFlag.getPosition(), 1))); 9043 } 9044 9045 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 9046 unsigned flagLen) { 9047 // Warn about an empty flag. 9048 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 9049 getLocationOfByte(startFlag), 9050 /*IsStringLocation*/true, 9051 getSpecifierRange(startFlag, flagLen)); 9052 } 9053 9054 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 9055 unsigned flagLen) { 9056 // Warn about an invalid flag. 9057 auto Range = getSpecifierRange(startFlag, flagLen); 9058 StringRef flag(startFlag, flagLen); 9059 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 9060 getLocationOfByte(startFlag), 9061 /*IsStringLocation*/true, 9062 Range, FixItHint::CreateRemoval(Range)); 9063 } 9064 9065 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 9066 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 9067 // Warn about using '[...]' without a '@' conversion. 9068 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 9069 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 9070 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 9071 getLocationOfByte(conversionPosition), 9072 /*IsStringLocation*/true, 9073 Range, FixItHint::CreateRemoval(Range)); 9074 } 9075 9076 // Determines if the specified is a C++ class or struct containing 9077 // a member with the specified name and kind (e.g. a CXXMethodDecl named 9078 // "c_str()"). 9079 template<typename MemberKind> 9080 static llvm::SmallPtrSet<MemberKind*, 1> 9081 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 9082 const RecordType *RT = Ty->getAs<RecordType>(); 9083 llvm::SmallPtrSet<MemberKind*, 1> Results; 9084 9085 if (!RT) 9086 return Results; 9087 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 9088 if (!RD || !RD->getDefinition()) 9089 return Results; 9090 9091 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 9092 Sema::LookupMemberName); 9093 R.suppressDiagnostics(); 9094 9095 // We just need to include all members of the right kind turned up by the 9096 // filter, at this point. 9097 if (S.LookupQualifiedName(R, RT->getDecl())) 9098 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 9099 NamedDecl *decl = (*I)->getUnderlyingDecl(); 9100 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 9101 Results.insert(FK); 9102 } 9103 return Results; 9104 } 9105 9106 /// Check if we could call '.c_str()' on an object. 9107 /// 9108 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 9109 /// allow the call, or if it would be ambiguous). 9110 bool Sema::hasCStrMethod(const Expr *E) { 9111 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 9112 9113 MethodSet Results = 9114 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 9115 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 9116 MI != ME; ++MI) 9117 if ((*MI)->getMinRequiredArguments() == 0) 9118 return true; 9119 return false; 9120 } 9121 9122 // Check if a (w)string was passed when a (w)char* was needed, and offer a 9123 // better diagnostic if so. AT is assumed to be valid. 9124 // Returns true when a c_str() conversion method is found. 9125 bool CheckPrintfHandler::checkForCStrMembers( 9126 const analyze_printf::ArgType &AT, const Expr *E) { 9127 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 9128 9129 MethodSet Results = 9130 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 9131 9132 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 9133 MI != ME; ++MI) { 9134 const CXXMethodDecl *Method = *MI; 9135 if (Method->getMinRequiredArguments() == 0 && 9136 AT.matchesType(S.Context, Method->getReturnType())) { 9137 // FIXME: Suggest parens if the expression needs them. 9138 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 9139 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 9140 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 9141 return true; 9142 } 9143 } 9144 9145 return false; 9146 } 9147 9148 bool 9149 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 9150 &FS, 9151 const char *startSpecifier, 9152 unsigned specifierLen) { 9153 using namespace analyze_format_string; 9154 using namespace analyze_printf; 9155 9156 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 9157 9158 if (FS.consumesDataArgument()) { 9159 if (atFirstArg) { 9160 atFirstArg = false; 9161 usesPositionalArgs = FS.usesPositionalArg(); 9162 } 9163 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9164 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9165 startSpecifier, specifierLen); 9166 return false; 9167 } 9168 } 9169 9170 // First check if the field width, precision, and conversion specifier 9171 // have matching data arguments. 9172 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 9173 startSpecifier, specifierLen)) { 9174 return false; 9175 } 9176 9177 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 9178 startSpecifier, specifierLen)) { 9179 return false; 9180 } 9181 9182 if (!CS.consumesDataArgument()) { 9183 // FIXME: Technically specifying a precision or field width here 9184 // makes no sense. Worth issuing a warning at some point. 9185 return true; 9186 } 9187 9188 // Consume the argument. 9189 unsigned argIndex = FS.getArgIndex(); 9190 if (argIndex < NumDataArgs) { 9191 // The check to see if the argIndex is valid will come later. 9192 // We set the bit here because we may exit early from this 9193 // function if we encounter some other error. 9194 CoveredArgs.set(argIndex); 9195 } 9196 9197 // FreeBSD kernel extensions. 9198 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 9199 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 9200 // We need at least two arguments. 9201 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 9202 return false; 9203 9204 // Claim the second argument. 9205 CoveredArgs.set(argIndex + 1); 9206 9207 // Type check the first argument (int for %b, pointer for %D) 9208 const Expr *Ex = getDataArg(argIndex); 9209 const analyze_printf::ArgType &AT = 9210 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 9211 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 9212 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 9213 EmitFormatDiagnostic( 9214 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9215 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 9216 << false << Ex->getSourceRange(), 9217 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9218 getSpecifierRange(startSpecifier, specifierLen)); 9219 9220 // Type check the second argument (char * for both %b and %D) 9221 Ex = getDataArg(argIndex + 1); 9222 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 9223 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 9224 EmitFormatDiagnostic( 9225 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9226 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 9227 << false << Ex->getSourceRange(), 9228 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9229 getSpecifierRange(startSpecifier, specifierLen)); 9230 9231 return true; 9232 } 9233 9234 // Check for using an Objective-C specific conversion specifier 9235 // in a non-ObjC literal. 9236 if (!allowsObjCArg() && CS.isObjCArg()) { 9237 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9238 specifierLen); 9239 } 9240 9241 // %P can only be used with os_log. 9242 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 9243 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9244 specifierLen); 9245 } 9246 9247 // %n is not allowed with os_log. 9248 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 9249 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 9250 getLocationOfByte(CS.getStart()), 9251 /*IsStringLocation*/ false, 9252 getSpecifierRange(startSpecifier, specifierLen)); 9253 9254 return true; 9255 } 9256 9257 // Only scalars are allowed for os_trace. 9258 if (FSType == Sema::FST_OSTrace && 9259 (CS.getKind() == ConversionSpecifier::PArg || 9260 CS.getKind() == ConversionSpecifier::sArg || 9261 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 9262 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9263 specifierLen); 9264 } 9265 9266 // Check for use of public/private annotation outside of os_log(). 9267 if (FSType != Sema::FST_OSLog) { 9268 if (FS.isPublic().isSet()) { 9269 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9270 << "public", 9271 getLocationOfByte(FS.isPublic().getPosition()), 9272 /*IsStringLocation*/ false, 9273 getSpecifierRange(startSpecifier, specifierLen)); 9274 } 9275 if (FS.isPrivate().isSet()) { 9276 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9277 << "private", 9278 getLocationOfByte(FS.isPrivate().getPosition()), 9279 /*IsStringLocation*/ false, 9280 getSpecifierRange(startSpecifier, specifierLen)); 9281 } 9282 } 9283 9284 // Check for invalid use of field width 9285 if (!FS.hasValidFieldWidth()) { 9286 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 9287 startSpecifier, specifierLen); 9288 } 9289 9290 // Check for invalid use of precision 9291 if (!FS.hasValidPrecision()) { 9292 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 9293 startSpecifier, specifierLen); 9294 } 9295 9296 // Precision is mandatory for %P specifier. 9297 if (CS.getKind() == ConversionSpecifier::PArg && 9298 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 9299 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 9300 getLocationOfByte(startSpecifier), 9301 /*IsStringLocation*/ false, 9302 getSpecifierRange(startSpecifier, specifierLen)); 9303 } 9304 9305 // Check each flag does not conflict with any other component. 9306 if (!FS.hasValidThousandsGroupingPrefix()) 9307 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 9308 if (!FS.hasValidLeadingZeros()) 9309 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 9310 if (!FS.hasValidPlusPrefix()) 9311 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 9312 if (!FS.hasValidSpacePrefix()) 9313 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 9314 if (!FS.hasValidAlternativeForm()) 9315 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 9316 if (!FS.hasValidLeftJustified()) 9317 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 9318 9319 // Check that flags are not ignored by another flag 9320 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 9321 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 9322 startSpecifier, specifierLen); 9323 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 9324 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 9325 startSpecifier, specifierLen); 9326 9327 // Check the length modifier is valid with the given conversion specifier. 9328 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9329 S.getLangOpts())) 9330 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9331 diag::warn_format_nonsensical_length); 9332 else if (!FS.hasStandardLengthModifier()) 9333 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9334 else if (!FS.hasStandardLengthConversionCombination()) 9335 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9336 diag::warn_format_non_standard_conversion_spec); 9337 9338 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9339 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9340 9341 // The remaining checks depend on the data arguments. 9342 if (HasVAListArg) 9343 return true; 9344 9345 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9346 return false; 9347 9348 const Expr *Arg = getDataArg(argIndex); 9349 if (!Arg) 9350 return true; 9351 9352 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 9353 } 9354 9355 static bool requiresParensToAddCast(const Expr *E) { 9356 // FIXME: We should have a general way to reason about operator 9357 // precedence and whether parens are actually needed here. 9358 // Take care of a few common cases where they aren't. 9359 const Expr *Inside = E->IgnoreImpCasts(); 9360 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 9361 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 9362 9363 switch (Inside->getStmtClass()) { 9364 case Stmt::ArraySubscriptExprClass: 9365 case Stmt::CallExprClass: 9366 case Stmt::CharacterLiteralClass: 9367 case Stmt::CXXBoolLiteralExprClass: 9368 case Stmt::DeclRefExprClass: 9369 case Stmt::FloatingLiteralClass: 9370 case Stmt::IntegerLiteralClass: 9371 case Stmt::MemberExprClass: 9372 case Stmt::ObjCArrayLiteralClass: 9373 case Stmt::ObjCBoolLiteralExprClass: 9374 case Stmt::ObjCBoxedExprClass: 9375 case Stmt::ObjCDictionaryLiteralClass: 9376 case Stmt::ObjCEncodeExprClass: 9377 case Stmt::ObjCIvarRefExprClass: 9378 case Stmt::ObjCMessageExprClass: 9379 case Stmt::ObjCPropertyRefExprClass: 9380 case Stmt::ObjCStringLiteralClass: 9381 case Stmt::ObjCSubscriptRefExprClass: 9382 case Stmt::ParenExprClass: 9383 case Stmt::StringLiteralClass: 9384 case Stmt::UnaryOperatorClass: 9385 return false; 9386 default: 9387 return true; 9388 } 9389 } 9390 9391 static std::pair<QualType, StringRef> 9392 shouldNotPrintDirectly(const ASTContext &Context, 9393 QualType IntendedTy, 9394 const Expr *E) { 9395 // Use a 'while' to peel off layers of typedefs. 9396 QualType TyTy = IntendedTy; 9397 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 9398 StringRef Name = UserTy->getDecl()->getName(); 9399 QualType CastTy = llvm::StringSwitch<QualType>(Name) 9400 .Case("CFIndex", Context.getNSIntegerType()) 9401 .Case("NSInteger", Context.getNSIntegerType()) 9402 .Case("NSUInteger", Context.getNSUIntegerType()) 9403 .Case("SInt32", Context.IntTy) 9404 .Case("UInt32", Context.UnsignedIntTy) 9405 .Default(QualType()); 9406 9407 if (!CastTy.isNull()) 9408 return std::make_pair(CastTy, Name); 9409 9410 TyTy = UserTy->desugar(); 9411 } 9412 9413 // Strip parens if necessary. 9414 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 9415 return shouldNotPrintDirectly(Context, 9416 PE->getSubExpr()->getType(), 9417 PE->getSubExpr()); 9418 9419 // If this is a conditional expression, then its result type is constructed 9420 // via usual arithmetic conversions and thus there might be no necessary 9421 // typedef sugar there. Recurse to operands to check for NSInteger & 9422 // Co. usage condition. 9423 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9424 QualType TrueTy, FalseTy; 9425 StringRef TrueName, FalseName; 9426 9427 std::tie(TrueTy, TrueName) = 9428 shouldNotPrintDirectly(Context, 9429 CO->getTrueExpr()->getType(), 9430 CO->getTrueExpr()); 9431 std::tie(FalseTy, FalseName) = 9432 shouldNotPrintDirectly(Context, 9433 CO->getFalseExpr()->getType(), 9434 CO->getFalseExpr()); 9435 9436 if (TrueTy == FalseTy) 9437 return std::make_pair(TrueTy, TrueName); 9438 else if (TrueTy.isNull()) 9439 return std::make_pair(FalseTy, FalseName); 9440 else if (FalseTy.isNull()) 9441 return std::make_pair(TrueTy, TrueName); 9442 } 9443 9444 return std::make_pair(QualType(), StringRef()); 9445 } 9446 9447 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 9448 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 9449 /// type do not count. 9450 static bool 9451 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 9452 QualType From = ICE->getSubExpr()->getType(); 9453 QualType To = ICE->getType(); 9454 // It's an integer promotion if the destination type is the promoted 9455 // source type. 9456 if (ICE->getCastKind() == CK_IntegralCast && 9457 From->isPromotableIntegerType() && 9458 S.Context.getPromotedIntegerType(From) == To) 9459 return true; 9460 // Look through vector types, since we do default argument promotion for 9461 // those in OpenCL. 9462 if (const auto *VecTy = From->getAs<ExtVectorType>()) 9463 From = VecTy->getElementType(); 9464 if (const auto *VecTy = To->getAs<ExtVectorType>()) 9465 To = VecTy->getElementType(); 9466 // It's a floating promotion if the source type is a lower rank. 9467 return ICE->getCastKind() == CK_FloatingCast && 9468 S.Context.getFloatingTypeOrder(From, To) < 0; 9469 } 9470 9471 bool 9472 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9473 const char *StartSpecifier, 9474 unsigned SpecifierLen, 9475 const Expr *E) { 9476 using namespace analyze_format_string; 9477 using namespace analyze_printf; 9478 9479 // Now type check the data expression that matches the 9480 // format specifier. 9481 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 9482 if (!AT.isValid()) 9483 return true; 9484 9485 QualType ExprTy = E->getType(); 9486 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 9487 ExprTy = TET->getUnderlyingExpr()->getType(); 9488 } 9489 9490 // Diagnose attempts to print a boolean value as a character. Unlike other 9491 // -Wformat diagnostics, this is fine from a type perspective, but it still 9492 // doesn't make sense. 9493 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 9494 E->isKnownToHaveBooleanValue()) { 9495 const CharSourceRange &CSR = 9496 getSpecifierRange(StartSpecifier, SpecifierLen); 9497 SmallString<4> FSString; 9498 llvm::raw_svector_ostream os(FSString); 9499 FS.toString(os); 9500 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 9501 << FSString, 9502 E->getExprLoc(), false, CSR); 9503 return true; 9504 } 9505 9506 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 9507 if (Match == analyze_printf::ArgType::Match) 9508 return true; 9509 9510 // Look through argument promotions for our error message's reported type. 9511 // This includes the integral and floating promotions, but excludes array 9512 // and function pointer decay (seeing that an argument intended to be a 9513 // string has type 'char [6]' is probably more confusing than 'char *') and 9514 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 9515 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9516 if (isArithmeticArgumentPromotion(S, ICE)) { 9517 E = ICE->getSubExpr(); 9518 ExprTy = E->getType(); 9519 9520 // Check if we didn't match because of an implicit cast from a 'char' 9521 // or 'short' to an 'int'. This is done because printf is a varargs 9522 // function. 9523 if (ICE->getType() == S.Context.IntTy || 9524 ICE->getType() == S.Context.UnsignedIntTy) { 9525 // All further checking is done on the subexpression 9526 const analyze_printf::ArgType::MatchKind ImplicitMatch = 9527 AT.matchesType(S.Context, ExprTy); 9528 if (ImplicitMatch == analyze_printf::ArgType::Match) 9529 return true; 9530 if (ImplicitMatch == ArgType::NoMatchPedantic || 9531 ImplicitMatch == ArgType::NoMatchTypeConfusion) 9532 Match = ImplicitMatch; 9533 } 9534 } 9535 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 9536 // Special case for 'a', which has type 'int' in C. 9537 // Note, however, that we do /not/ want to treat multibyte constants like 9538 // 'MooV' as characters! This form is deprecated but still exists. In 9539 // addition, don't treat expressions as of type 'char' if one byte length 9540 // modifier is provided. 9541 if (ExprTy == S.Context.IntTy && 9542 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 9543 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 9544 ExprTy = S.Context.CharTy; 9545 } 9546 9547 // Look through enums to their underlying type. 9548 bool IsEnum = false; 9549 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 9550 ExprTy = EnumTy->getDecl()->getIntegerType(); 9551 IsEnum = true; 9552 } 9553 9554 // %C in an Objective-C context prints a unichar, not a wchar_t. 9555 // If the argument is an integer of some kind, believe the %C and suggest 9556 // a cast instead of changing the conversion specifier. 9557 QualType IntendedTy = ExprTy; 9558 if (isObjCContext() && 9559 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 9560 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 9561 !ExprTy->isCharType()) { 9562 // 'unichar' is defined as a typedef of unsigned short, but we should 9563 // prefer using the typedef if it is visible. 9564 IntendedTy = S.Context.UnsignedShortTy; 9565 9566 // While we are here, check if the value is an IntegerLiteral that happens 9567 // to be within the valid range. 9568 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 9569 const llvm::APInt &V = IL->getValue(); 9570 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 9571 return true; 9572 } 9573 9574 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 9575 Sema::LookupOrdinaryName); 9576 if (S.LookupName(Result, S.getCurScope())) { 9577 NamedDecl *ND = Result.getFoundDecl(); 9578 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 9579 if (TD->getUnderlyingType() == IntendedTy) 9580 IntendedTy = S.Context.getTypedefType(TD); 9581 } 9582 } 9583 } 9584 9585 // Special-case some of Darwin's platform-independence types by suggesting 9586 // casts to primitive types that are known to be large enough. 9587 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 9588 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 9589 QualType CastTy; 9590 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 9591 if (!CastTy.isNull()) { 9592 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 9593 // (long in ASTContext). Only complain to pedants. 9594 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 9595 (AT.isSizeT() || AT.isPtrdiffT()) && 9596 AT.matchesType(S.Context, CastTy)) 9597 Match = ArgType::NoMatchPedantic; 9598 IntendedTy = CastTy; 9599 ShouldNotPrintDirectly = true; 9600 } 9601 } 9602 9603 // We may be able to offer a FixItHint if it is a supported type. 9604 PrintfSpecifier fixedFS = FS; 9605 bool Success = 9606 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 9607 9608 if (Success) { 9609 // Get the fix string from the fixed format specifier 9610 SmallString<16> buf; 9611 llvm::raw_svector_ostream os(buf); 9612 fixedFS.toString(os); 9613 9614 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 9615 9616 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 9617 unsigned Diag; 9618 switch (Match) { 9619 case ArgType::Match: llvm_unreachable("expected non-matching"); 9620 case ArgType::NoMatchPedantic: 9621 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9622 break; 9623 case ArgType::NoMatchTypeConfusion: 9624 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9625 break; 9626 case ArgType::NoMatch: 9627 Diag = diag::warn_format_conversion_argument_type_mismatch; 9628 break; 9629 } 9630 9631 // In this case, the specifier is wrong and should be changed to match 9632 // the argument. 9633 EmitFormatDiagnostic(S.PDiag(Diag) 9634 << AT.getRepresentativeTypeName(S.Context) 9635 << IntendedTy << IsEnum << E->getSourceRange(), 9636 E->getBeginLoc(), 9637 /*IsStringLocation*/ false, SpecRange, 9638 FixItHint::CreateReplacement(SpecRange, os.str())); 9639 } else { 9640 // The canonical type for formatting this value is different from the 9641 // actual type of the expression. (This occurs, for example, with Darwin's 9642 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 9643 // should be printed as 'long' for 64-bit compatibility.) 9644 // Rather than emitting a normal format/argument mismatch, we want to 9645 // add a cast to the recommended type (and correct the format string 9646 // if necessary). 9647 SmallString<16> CastBuf; 9648 llvm::raw_svector_ostream CastFix(CastBuf); 9649 CastFix << "("; 9650 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 9651 CastFix << ")"; 9652 9653 SmallVector<FixItHint,4> Hints; 9654 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 9655 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 9656 9657 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 9658 // If there's already a cast present, just replace it. 9659 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 9660 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 9661 9662 } else if (!requiresParensToAddCast(E)) { 9663 // If the expression has high enough precedence, 9664 // just write the C-style cast. 9665 Hints.push_back( 9666 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9667 } else { 9668 // Otherwise, add parens around the expression as well as the cast. 9669 CastFix << "("; 9670 Hints.push_back( 9671 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9672 9673 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 9674 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 9675 } 9676 9677 if (ShouldNotPrintDirectly) { 9678 // The expression has a type that should not be printed directly. 9679 // We extract the name from the typedef because we don't want to show 9680 // the underlying type in the diagnostic. 9681 StringRef Name; 9682 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 9683 Name = TypedefTy->getDecl()->getName(); 9684 else 9685 Name = CastTyName; 9686 unsigned Diag = Match == ArgType::NoMatchPedantic 9687 ? diag::warn_format_argument_needs_cast_pedantic 9688 : diag::warn_format_argument_needs_cast; 9689 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 9690 << E->getSourceRange(), 9691 E->getBeginLoc(), /*IsStringLocation=*/false, 9692 SpecRange, Hints); 9693 } else { 9694 // In this case, the expression could be printed using a different 9695 // specifier, but we've decided that the specifier is probably correct 9696 // and we should cast instead. Just use the normal warning message. 9697 EmitFormatDiagnostic( 9698 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9699 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9700 << E->getSourceRange(), 9701 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9702 } 9703 } 9704 } else { 9705 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9706 SpecifierLen); 9707 // Since the warning for passing non-POD types to variadic functions 9708 // was deferred until now, we emit a warning for non-POD 9709 // arguments here. 9710 switch (S.isValidVarArgType(ExprTy)) { 9711 case Sema::VAK_Valid: 9712 case Sema::VAK_ValidInCXX11: { 9713 unsigned Diag; 9714 switch (Match) { 9715 case ArgType::Match: llvm_unreachable("expected non-matching"); 9716 case ArgType::NoMatchPedantic: 9717 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9718 break; 9719 case ArgType::NoMatchTypeConfusion: 9720 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9721 break; 9722 case ArgType::NoMatch: 9723 Diag = diag::warn_format_conversion_argument_type_mismatch; 9724 break; 9725 } 9726 9727 EmitFormatDiagnostic( 9728 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9729 << IsEnum << CSR << E->getSourceRange(), 9730 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9731 break; 9732 } 9733 case Sema::VAK_Undefined: 9734 case Sema::VAK_MSVCUndefined: 9735 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9736 << S.getLangOpts().CPlusPlus11 << ExprTy 9737 << CallType 9738 << AT.getRepresentativeTypeName(S.Context) << CSR 9739 << E->getSourceRange(), 9740 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9741 checkForCStrMembers(AT, E); 9742 break; 9743 9744 case Sema::VAK_Invalid: 9745 if (ExprTy->isObjCObjectType()) 9746 EmitFormatDiagnostic( 9747 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9748 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9749 << AT.getRepresentativeTypeName(S.Context) << CSR 9750 << E->getSourceRange(), 9751 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9752 else 9753 // FIXME: If this is an initializer list, suggest removing the braces 9754 // or inserting a cast to the target type. 9755 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9756 << isa<InitListExpr>(E) << ExprTy << CallType 9757 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9758 break; 9759 } 9760 9761 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9762 "format string specifier index out of range"); 9763 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9764 } 9765 9766 return true; 9767 } 9768 9769 //===--- CHECK: Scanf format string checking ------------------------------===// 9770 9771 namespace { 9772 9773 class CheckScanfHandler : public CheckFormatHandler { 9774 public: 9775 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9776 const Expr *origFormatExpr, Sema::FormatStringType type, 9777 unsigned firstDataArg, unsigned numDataArgs, 9778 const char *beg, bool hasVAListArg, 9779 ArrayRef<const Expr *> Args, unsigned formatIdx, 9780 bool inFunctionCall, Sema::VariadicCallType CallType, 9781 llvm::SmallBitVector &CheckedVarArgs, 9782 UncoveredArgHandler &UncoveredArg) 9783 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9784 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9785 inFunctionCall, CallType, CheckedVarArgs, 9786 UncoveredArg) {} 9787 9788 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9789 const char *startSpecifier, 9790 unsigned specifierLen) override; 9791 9792 bool HandleInvalidScanfConversionSpecifier( 9793 const analyze_scanf::ScanfSpecifier &FS, 9794 const char *startSpecifier, 9795 unsigned specifierLen) override; 9796 9797 void HandleIncompleteScanList(const char *start, const char *end) override; 9798 }; 9799 9800 } // namespace 9801 9802 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9803 const char *end) { 9804 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9805 getLocationOfByte(end), /*IsStringLocation*/true, 9806 getSpecifierRange(start, end - start)); 9807 } 9808 9809 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9810 const analyze_scanf::ScanfSpecifier &FS, 9811 const char *startSpecifier, 9812 unsigned specifierLen) { 9813 const analyze_scanf::ScanfConversionSpecifier &CS = 9814 FS.getConversionSpecifier(); 9815 9816 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9817 getLocationOfByte(CS.getStart()), 9818 startSpecifier, specifierLen, 9819 CS.getStart(), CS.getLength()); 9820 } 9821 9822 bool CheckScanfHandler::HandleScanfSpecifier( 9823 const analyze_scanf::ScanfSpecifier &FS, 9824 const char *startSpecifier, 9825 unsigned specifierLen) { 9826 using namespace analyze_scanf; 9827 using namespace analyze_format_string; 9828 9829 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9830 9831 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9832 // be used to decide if we are using positional arguments consistently. 9833 if (FS.consumesDataArgument()) { 9834 if (atFirstArg) { 9835 atFirstArg = false; 9836 usesPositionalArgs = FS.usesPositionalArg(); 9837 } 9838 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9839 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9840 startSpecifier, specifierLen); 9841 return false; 9842 } 9843 } 9844 9845 // Check if the field with is non-zero. 9846 const OptionalAmount &Amt = FS.getFieldWidth(); 9847 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9848 if (Amt.getConstantAmount() == 0) { 9849 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9850 Amt.getConstantLength()); 9851 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9852 getLocationOfByte(Amt.getStart()), 9853 /*IsStringLocation*/true, R, 9854 FixItHint::CreateRemoval(R)); 9855 } 9856 } 9857 9858 if (!FS.consumesDataArgument()) { 9859 // FIXME: Technically specifying a precision or field width here 9860 // makes no sense. Worth issuing a warning at some point. 9861 return true; 9862 } 9863 9864 // Consume the argument. 9865 unsigned argIndex = FS.getArgIndex(); 9866 if (argIndex < NumDataArgs) { 9867 // The check to see if the argIndex is valid will come later. 9868 // We set the bit here because we may exit early from this 9869 // function if we encounter some other error. 9870 CoveredArgs.set(argIndex); 9871 } 9872 9873 // Check the length modifier is valid with the given conversion specifier. 9874 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9875 S.getLangOpts())) 9876 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9877 diag::warn_format_nonsensical_length); 9878 else if (!FS.hasStandardLengthModifier()) 9879 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9880 else if (!FS.hasStandardLengthConversionCombination()) 9881 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9882 diag::warn_format_non_standard_conversion_spec); 9883 9884 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9885 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9886 9887 // The remaining checks depend on the data arguments. 9888 if (HasVAListArg) 9889 return true; 9890 9891 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9892 return false; 9893 9894 // Check that the argument type matches the format specifier. 9895 const Expr *Ex = getDataArg(argIndex); 9896 if (!Ex) 9897 return true; 9898 9899 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9900 9901 if (!AT.isValid()) { 9902 return true; 9903 } 9904 9905 analyze_format_string::ArgType::MatchKind Match = 9906 AT.matchesType(S.Context, Ex->getType()); 9907 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9908 if (Match == analyze_format_string::ArgType::Match) 9909 return true; 9910 9911 ScanfSpecifier fixedFS = FS; 9912 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9913 S.getLangOpts(), S.Context); 9914 9915 unsigned Diag = 9916 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9917 : diag::warn_format_conversion_argument_type_mismatch; 9918 9919 if (Success) { 9920 // Get the fix string from the fixed format specifier. 9921 SmallString<128> buf; 9922 llvm::raw_svector_ostream os(buf); 9923 fixedFS.toString(os); 9924 9925 EmitFormatDiagnostic( 9926 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9927 << Ex->getType() << false << Ex->getSourceRange(), 9928 Ex->getBeginLoc(), 9929 /*IsStringLocation*/ false, 9930 getSpecifierRange(startSpecifier, specifierLen), 9931 FixItHint::CreateReplacement( 9932 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9933 } else { 9934 EmitFormatDiagnostic(S.PDiag(Diag) 9935 << AT.getRepresentativeTypeName(S.Context) 9936 << Ex->getType() << false << Ex->getSourceRange(), 9937 Ex->getBeginLoc(), 9938 /*IsStringLocation*/ false, 9939 getSpecifierRange(startSpecifier, specifierLen)); 9940 } 9941 9942 return true; 9943 } 9944 9945 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9946 const Expr *OrigFormatExpr, 9947 ArrayRef<const Expr *> Args, 9948 bool HasVAListArg, unsigned format_idx, 9949 unsigned firstDataArg, 9950 Sema::FormatStringType Type, 9951 bool inFunctionCall, 9952 Sema::VariadicCallType CallType, 9953 llvm::SmallBitVector &CheckedVarArgs, 9954 UncoveredArgHandler &UncoveredArg, 9955 bool IgnoreStringsWithoutSpecifiers) { 9956 // CHECK: is the format string a wide literal? 9957 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9958 CheckFormatHandler::EmitFormatDiagnostic( 9959 S, inFunctionCall, Args[format_idx], 9960 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9961 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9962 return; 9963 } 9964 9965 // Str - The format string. NOTE: this is NOT null-terminated! 9966 StringRef StrRef = FExpr->getString(); 9967 const char *Str = StrRef.data(); 9968 // Account for cases where the string literal is truncated in a declaration. 9969 const ConstantArrayType *T = 9970 S.Context.getAsConstantArrayType(FExpr->getType()); 9971 assert(T && "String literal not of constant array type!"); 9972 size_t TypeSize = T->getSize().getZExtValue(); 9973 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9974 const unsigned numDataArgs = Args.size() - firstDataArg; 9975 9976 if (IgnoreStringsWithoutSpecifiers && 9977 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9978 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9979 return; 9980 9981 // Emit a warning if the string literal is truncated and does not contain an 9982 // embedded null character. 9983 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) { 9984 CheckFormatHandler::EmitFormatDiagnostic( 9985 S, inFunctionCall, Args[format_idx], 9986 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9987 FExpr->getBeginLoc(), 9988 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9989 return; 9990 } 9991 9992 // CHECK: empty format string? 9993 if (StrLen == 0 && numDataArgs > 0) { 9994 CheckFormatHandler::EmitFormatDiagnostic( 9995 S, inFunctionCall, Args[format_idx], 9996 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9997 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9998 return; 9999 } 10000 10001 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 10002 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 10003 Type == Sema::FST_OSTrace) { 10004 CheckPrintfHandler H( 10005 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 10006 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 10007 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 10008 CheckedVarArgs, UncoveredArg); 10009 10010 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 10011 S.getLangOpts(), 10012 S.Context.getTargetInfo(), 10013 Type == Sema::FST_FreeBSDKPrintf)) 10014 H.DoneProcessing(); 10015 } else if (Type == Sema::FST_Scanf) { 10016 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 10017 numDataArgs, Str, HasVAListArg, Args, format_idx, 10018 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 10019 10020 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 10021 S.getLangOpts(), 10022 S.Context.getTargetInfo())) 10023 H.DoneProcessing(); 10024 } // TODO: handle other formats 10025 } 10026 10027 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 10028 // Str - The format string. NOTE: this is NOT null-terminated! 10029 StringRef StrRef = FExpr->getString(); 10030 const char *Str = StrRef.data(); 10031 // Account for cases where the string literal is truncated in a declaration. 10032 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 10033 assert(T && "String literal not of constant array type!"); 10034 size_t TypeSize = T->getSize().getZExtValue(); 10035 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 10036 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 10037 getLangOpts(), 10038 Context.getTargetInfo()); 10039 } 10040 10041 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 10042 10043 // Returns the related absolute value function that is larger, of 0 if one 10044 // does not exist. 10045 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 10046 switch (AbsFunction) { 10047 default: 10048 return 0; 10049 10050 case Builtin::BI__builtin_abs: 10051 return Builtin::BI__builtin_labs; 10052 case Builtin::BI__builtin_labs: 10053 return Builtin::BI__builtin_llabs; 10054 case Builtin::BI__builtin_llabs: 10055 return 0; 10056 10057 case Builtin::BI__builtin_fabsf: 10058 return Builtin::BI__builtin_fabs; 10059 case Builtin::BI__builtin_fabs: 10060 return Builtin::BI__builtin_fabsl; 10061 case Builtin::BI__builtin_fabsl: 10062 return 0; 10063 10064 case Builtin::BI__builtin_cabsf: 10065 return Builtin::BI__builtin_cabs; 10066 case Builtin::BI__builtin_cabs: 10067 return Builtin::BI__builtin_cabsl; 10068 case Builtin::BI__builtin_cabsl: 10069 return 0; 10070 10071 case Builtin::BIabs: 10072 return Builtin::BIlabs; 10073 case Builtin::BIlabs: 10074 return Builtin::BIllabs; 10075 case Builtin::BIllabs: 10076 return 0; 10077 10078 case Builtin::BIfabsf: 10079 return Builtin::BIfabs; 10080 case Builtin::BIfabs: 10081 return Builtin::BIfabsl; 10082 case Builtin::BIfabsl: 10083 return 0; 10084 10085 case Builtin::BIcabsf: 10086 return Builtin::BIcabs; 10087 case Builtin::BIcabs: 10088 return Builtin::BIcabsl; 10089 case Builtin::BIcabsl: 10090 return 0; 10091 } 10092 } 10093 10094 // Returns the argument type of the absolute value function. 10095 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 10096 unsigned AbsType) { 10097 if (AbsType == 0) 10098 return QualType(); 10099 10100 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 10101 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 10102 if (Error != ASTContext::GE_None) 10103 return QualType(); 10104 10105 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 10106 if (!FT) 10107 return QualType(); 10108 10109 if (FT->getNumParams() != 1) 10110 return QualType(); 10111 10112 return FT->getParamType(0); 10113 } 10114 10115 // Returns the best absolute value function, or zero, based on type and 10116 // current absolute value function. 10117 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 10118 unsigned AbsFunctionKind) { 10119 unsigned BestKind = 0; 10120 uint64_t ArgSize = Context.getTypeSize(ArgType); 10121 for (unsigned Kind = AbsFunctionKind; Kind != 0; 10122 Kind = getLargerAbsoluteValueFunction(Kind)) { 10123 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 10124 if (Context.getTypeSize(ParamType) >= ArgSize) { 10125 if (BestKind == 0) 10126 BestKind = Kind; 10127 else if (Context.hasSameType(ParamType, ArgType)) { 10128 BestKind = Kind; 10129 break; 10130 } 10131 } 10132 } 10133 return BestKind; 10134 } 10135 10136 enum AbsoluteValueKind { 10137 AVK_Integer, 10138 AVK_Floating, 10139 AVK_Complex 10140 }; 10141 10142 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 10143 if (T->isIntegralOrEnumerationType()) 10144 return AVK_Integer; 10145 if (T->isRealFloatingType()) 10146 return AVK_Floating; 10147 if (T->isAnyComplexType()) 10148 return AVK_Complex; 10149 10150 llvm_unreachable("Type not integer, floating, or complex"); 10151 } 10152 10153 // Changes the absolute value function to a different type. Preserves whether 10154 // the function is a builtin. 10155 static unsigned changeAbsFunction(unsigned AbsKind, 10156 AbsoluteValueKind ValueKind) { 10157 switch (ValueKind) { 10158 case AVK_Integer: 10159 switch (AbsKind) { 10160 default: 10161 return 0; 10162 case Builtin::BI__builtin_fabsf: 10163 case Builtin::BI__builtin_fabs: 10164 case Builtin::BI__builtin_fabsl: 10165 case Builtin::BI__builtin_cabsf: 10166 case Builtin::BI__builtin_cabs: 10167 case Builtin::BI__builtin_cabsl: 10168 return Builtin::BI__builtin_abs; 10169 case Builtin::BIfabsf: 10170 case Builtin::BIfabs: 10171 case Builtin::BIfabsl: 10172 case Builtin::BIcabsf: 10173 case Builtin::BIcabs: 10174 case Builtin::BIcabsl: 10175 return Builtin::BIabs; 10176 } 10177 case AVK_Floating: 10178 switch (AbsKind) { 10179 default: 10180 return 0; 10181 case Builtin::BI__builtin_abs: 10182 case Builtin::BI__builtin_labs: 10183 case Builtin::BI__builtin_llabs: 10184 case Builtin::BI__builtin_cabsf: 10185 case Builtin::BI__builtin_cabs: 10186 case Builtin::BI__builtin_cabsl: 10187 return Builtin::BI__builtin_fabsf; 10188 case Builtin::BIabs: 10189 case Builtin::BIlabs: 10190 case Builtin::BIllabs: 10191 case Builtin::BIcabsf: 10192 case Builtin::BIcabs: 10193 case Builtin::BIcabsl: 10194 return Builtin::BIfabsf; 10195 } 10196 case AVK_Complex: 10197 switch (AbsKind) { 10198 default: 10199 return 0; 10200 case Builtin::BI__builtin_abs: 10201 case Builtin::BI__builtin_labs: 10202 case Builtin::BI__builtin_llabs: 10203 case Builtin::BI__builtin_fabsf: 10204 case Builtin::BI__builtin_fabs: 10205 case Builtin::BI__builtin_fabsl: 10206 return Builtin::BI__builtin_cabsf; 10207 case Builtin::BIabs: 10208 case Builtin::BIlabs: 10209 case Builtin::BIllabs: 10210 case Builtin::BIfabsf: 10211 case Builtin::BIfabs: 10212 case Builtin::BIfabsl: 10213 return Builtin::BIcabsf; 10214 } 10215 } 10216 llvm_unreachable("Unable to convert function"); 10217 } 10218 10219 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 10220 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 10221 if (!FnInfo) 10222 return 0; 10223 10224 switch (FDecl->getBuiltinID()) { 10225 default: 10226 return 0; 10227 case Builtin::BI__builtin_abs: 10228 case Builtin::BI__builtin_fabs: 10229 case Builtin::BI__builtin_fabsf: 10230 case Builtin::BI__builtin_fabsl: 10231 case Builtin::BI__builtin_labs: 10232 case Builtin::BI__builtin_llabs: 10233 case Builtin::BI__builtin_cabs: 10234 case Builtin::BI__builtin_cabsf: 10235 case Builtin::BI__builtin_cabsl: 10236 case Builtin::BIabs: 10237 case Builtin::BIlabs: 10238 case Builtin::BIllabs: 10239 case Builtin::BIfabs: 10240 case Builtin::BIfabsf: 10241 case Builtin::BIfabsl: 10242 case Builtin::BIcabs: 10243 case Builtin::BIcabsf: 10244 case Builtin::BIcabsl: 10245 return FDecl->getBuiltinID(); 10246 } 10247 llvm_unreachable("Unknown Builtin type"); 10248 } 10249 10250 // If the replacement is valid, emit a note with replacement function. 10251 // Additionally, suggest including the proper header if not already included. 10252 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 10253 unsigned AbsKind, QualType ArgType) { 10254 bool EmitHeaderHint = true; 10255 const char *HeaderName = nullptr; 10256 const char *FunctionName = nullptr; 10257 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 10258 FunctionName = "std::abs"; 10259 if (ArgType->isIntegralOrEnumerationType()) { 10260 HeaderName = "cstdlib"; 10261 } else if (ArgType->isRealFloatingType()) { 10262 HeaderName = "cmath"; 10263 } else { 10264 llvm_unreachable("Invalid Type"); 10265 } 10266 10267 // Lookup all std::abs 10268 if (NamespaceDecl *Std = S.getStdNamespace()) { 10269 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 10270 R.suppressDiagnostics(); 10271 S.LookupQualifiedName(R, Std); 10272 10273 for (const auto *I : R) { 10274 const FunctionDecl *FDecl = nullptr; 10275 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 10276 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 10277 } else { 10278 FDecl = dyn_cast<FunctionDecl>(I); 10279 } 10280 if (!FDecl) 10281 continue; 10282 10283 // Found std::abs(), check that they are the right ones. 10284 if (FDecl->getNumParams() != 1) 10285 continue; 10286 10287 // Check that the parameter type can handle the argument. 10288 QualType ParamType = FDecl->getParamDecl(0)->getType(); 10289 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 10290 S.Context.getTypeSize(ArgType) <= 10291 S.Context.getTypeSize(ParamType)) { 10292 // Found a function, don't need the header hint. 10293 EmitHeaderHint = false; 10294 break; 10295 } 10296 } 10297 } 10298 } else { 10299 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 10300 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 10301 10302 if (HeaderName) { 10303 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 10304 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 10305 R.suppressDiagnostics(); 10306 S.LookupName(R, S.getCurScope()); 10307 10308 if (R.isSingleResult()) { 10309 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 10310 if (FD && FD->getBuiltinID() == AbsKind) { 10311 EmitHeaderHint = false; 10312 } else { 10313 return; 10314 } 10315 } else if (!R.empty()) { 10316 return; 10317 } 10318 } 10319 } 10320 10321 S.Diag(Loc, diag::note_replace_abs_function) 10322 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 10323 10324 if (!HeaderName) 10325 return; 10326 10327 if (!EmitHeaderHint) 10328 return; 10329 10330 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 10331 << FunctionName; 10332 } 10333 10334 template <std::size_t StrLen> 10335 static bool IsStdFunction(const FunctionDecl *FDecl, 10336 const char (&Str)[StrLen]) { 10337 if (!FDecl) 10338 return false; 10339 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 10340 return false; 10341 if (!FDecl->isInStdNamespace()) 10342 return false; 10343 10344 return true; 10345 } 10346 10347 // Warn when using the wrong abs() function. 10348 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 10349 const FunctionDecl *FDecl) { 10350 if (Call->getNumArgs() != 1) 10351 return; 10352 10353 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 10354 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 10355 if (AbsKind == 0 && !IsStdAbs) 10356 return; 10357 10358 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10359 QualType ParamType = Call->getArg(0)->getType(); 10360 10361 // Unsigned types cannot be negative. Suggest removing the absolute value 10362 // function call. 10363 if (ArgType->isUnsignedIntegerType()) { 10364 const char *FunctionName = 10365 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 10366 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 10367 Diag(Call->getExprLoc(), diag::note_remove_abs) 10368 << FunctionName 10369 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 10370 return; 10371 } 10372 10373 // Taking the absolute value of a pointer is very suspicious, they probably 10374 // wanted to index into an array, dereference a pointer, call a function, etc. 10375 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 10376 unsigned DiagType = 0; 10377 if (ArgType->isFunctionType()) 10378 DiagType = 1; 10379 else if (ArgType->isArrayType()) 10380 DiagType = 2; 10381 10382 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 10383 return; 10384 } 10385 10386 // std::abs has overloads which prevent most of the absolute value problems 10387 // from occurring. 10388 if (IsStdAbs) 10389 return; 10390 10391 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 10392 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 10393 10394 // The argument and parameter are the same kind. Check if they are the right 10395 // size. 10396 if (ArgValueKind == ParamValueKind) { 10397 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 10398 return; 10399 10400 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 10401 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 10402 << FDecl << ArgType << ParamType; 10403 10404 if (NewAbsKind == 0) 10405 return; 10406 10407 emitReplacement(*this, Call->getExprLoc(), 10408 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10409 return; 10410 } 10411 10412 // ArgValueKind != ParamValueKind 10413 // The wrong type of absolute value function was used. Attempt to find the 10414 // proper one. 10415 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 10416 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 10417 if (NewAbsKind == 0) 10418 return; 10419 10420 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 10421 << FDecl << ParamValueKind << ArgValueKind; 10422 10423 emitReplacement(*this, Call->getExprLoc(), 10424 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10425 } 10426 10427 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 10428 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 10429 const FunctionDecl *FDecl) { 10430 if (!Call || !FDecl) return; 10431 10432 // Ignore template specializations and macros. 10433 if (inTemplateInstantiation()) return; 10434 if (Call->getExprLoc().isMacroID()) return; 10435 10436 // Only care about the one template argument, two function parameter std::max 10437 if (Call->getNumArgs() != 2) return; 10438 if (!IsStdFunction(FDecl, "max")) return; 10439 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 10440 if (!ArgList) return; 10441 if (ArgList->size() != 1) return; 10442 10443 // Check that template type argument is unsigned integer. 10444 const auto& TA = ArgList->get(0); 10445 if (TA.getKind() != TemplateArgument::Type) return; 10446 QualType ArgType = TA.getAsType(); 10447 if (!ArgType->isUnsignedIntegerType()) return; 10448 10449 // See if either argument is a literal zero. 10450 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 10451 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 10452 if (!MTE) return false; 10453 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 10454 if (!Num) return false; 10455 if (Num->getValue() != 0) return false; 10456 return true; 10457 }; 10458 10459 const Expr *FirstArg = Call->getArg(0); 10460 const Expr *SecondArg = Call->getArg(1); 10461 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 10462 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 10463 10464 // Only warn when exactly one argument is zero. 10465 if (IsFirstArgZero == IsSecondArgZero) return; 10466 10467 SourceRange FirstRange = FirstArg->getSourceRange(); 10468 SourceRange SecondRange = SecondArg->getSourceRange(); 10469 10470 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 10471 10472 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 10473 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 10474 10475 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 10476 SourceRange RemovalRange; 10477 if (IsFirstArgZero) { 10478 RemovalRange = SourceRange(FirstRange.getBegin(), 10479 SecondRange.getBegin().getLocWithOffset(-1)); 10480 } else { 10481 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 10482 SecondRange.getEnd()); 10483 } 10484 10485 Diag(Call->getExprLoc(), diag::note_remove_max_call) 10486 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 10487 << FixItHint::CreateRemoval(RemovalRange); 10488 } 10489 10490 //===--- CHECK: Standard memory functions ---------------------------------===// 10491 10492 /// Takes the expression passed to the size_t parameter of functions 10493 /// such as memcmp, strncat, etc and warns if it's a comparison. 10494 /// 10495 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 10496 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 10497 IdentifierInfo *FnName, 10498 SourceLocation FnLoc, 10499 SourceLocation RParenLoc) { 10500 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 10501 if (!Size) 10502 return false; 10503 10504 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 10505 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 10506 return false; 10507 10508 SourceRange SizeRange = Size->getSourceRange(); 10509 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 10510 << SizeRange << FnName; 10511 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 10512 << FnName 10513 << FixItHint::CreateInsertion( 10514 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 10515 << FixItHint::CreateRemoval(RParenLoc); 10516 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 10517 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 10518 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 10519 ")"); 10520 10521 return true; 10522 } 10523 10524 /// Determine whether the given type is or contains a dynamic class type 10525 /// (e.g., whether it has a vtable). 10526 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 10527 bool &IsContained) { 10528 // Look through array types while ignoring qualifiers. 10529 const Type *Ty = T->getBaseElementTypeUnsafe(); 10530 IsContained = false; 10531 10532 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 10533 RD = RD ? RD->getDefinition() : nullptr; 10534 if (!RD || RD->isInvalidDecl()) 10535 return nullptr; 10536 10537 if (RD->isDynamicClass()) 10538 return RD; 10539 10540 // Check all the fields. If any bases were dynamic, the class is dynamic. 10541 // It's impossible for a class to transitively contain itself by value, so 10542 // infinite recursion is impossible. 10543 for (auto *FD : RD->fields()) { 10544 bool SubContained; 10545 if (const CXXRecordDecl *ContainedRD = 10546 getContainedDynamicClass(FD->getType(), SubContained)) { 10547 IsContained = true; 10548 return ContainedRD; 10549 } 10550 } 10551 10552 return nullptr; 10553 } 10554 10555 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 10556 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 10557 if (Unary->getKind() == UETT_SizeOf) 10558 return Unary; 10559 return nullptr; 10560 } 10561 10562 /// If E is a sizeof expression, returns its argument expression, 10563 /// otherwise returns NULL. 10564 static const Expr *getSizeOfExprArg(const Expr *E) { 10565 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10566 if (!SizeOf->isArgumentType()) 10567 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 10568 return nullptr; 10569 } 10570 10571 /// If E is a sizeof expression, returns its argument type. 10572 static QualType getSizeOfArgType(const Expr *E) { 10573 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10574 return SizeOf->getTypeOfArgument(); 10575 return QualType(); 10576 } 10577 10578 namespace { 10579 10580 struct SearchNonTrivialToInitializeField 10581 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 10582 using Super = 10583 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 10584 10585 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 10586 10587 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 10588 SourceLocation SL) { 10589 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10590 asDerived().visitArray(PDIK, AT, SL); 10591 return; 10592 } 10593 10594 Super::visitWithKind(PDIK, FT, SL); 10595 } 10596 10597 void visitARCStrong(QualType FT, SourceLocation SL) { 10598 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10599 } 10600 void visitARCWeak(QualType FT, SourceLocation SL) { 10601 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10602 } 10603 void visitStruct(QualType FT, SourceLocation SL) { 10604 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10605 visit(FD->getType(), FD->getLocation()); 10606 } 10607 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 10608 const ArrayType *AT, SourceLocation SL) { 10609 visit(getContext().getBaseElementType(AT), SL); 10610 } 10611 void visitTrivial(QualType FT, SourceLocation SL) {} 10612 10613 static void diag(QualType RT, const Expr *E, Sema &S) { 10614 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 10615 } 10616 10617 ASTContext &getContext() { return S.getASTContext(); } 10618 10619 const Expr *E; 10620 Sema &S; 10621 }; 10622 10623 struct SearchNonTrivialToCopyField 10624 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 10625 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 10626 10627 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 10628 10629 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 10630 SourceLocation SL) { 10631 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10632 asDerived().visitArray(PCK, AT, SL); 10633 return; 10634 } 10635 10636 Super::visitWithKind(PCK, FT, SL); 10637 } 10638 10639 void visitARCStrong(QualType FT, SourceLocation SL) { 10640 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10641 } 10642 void visitARCWeak(QualType FT, SourceLocation SL) { 10643 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10644 } 10645 void visitStruct(QualType FT, SourceLocation SL) { 10646 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10647 visit(FD->getType(), FD->getLocation()); 10648 } 10649 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 10650 SourceLocation SL) { 10651 visit(getContext().getBaseElementType(AT), SL); 10652 } 10653 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 10654 SourceLocation SL) {} 10655 void visitTrivial(QualType FT, SourceLocation SL) {} 10656 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 10657 10658 static void diag(QualType RT, const Expr *E, Sema &S) { 10659 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 10660 } 10661 10662 ASTContext &getContext() { return S.getASTContext(); } 10663 10664 const Expr *E; 10665 Sema &S; 10666 }; 10667 10668 } 10669 10670 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 10671 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 10672 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 10673 10674 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 10675 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 10676 return false; 10677 10678 return doesExprLikelyComputeSize(BO->getLHS()) || 10679 doesExprLikelyComputeSize(BO->getRHS()); 10680 } 10681 10682 return getAsSizeOfExpr(SizeofExpr) != nullptr; 10683 } 10684 10685 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 10686 /// 10687 /// \code 10688 /// #define MACRO 0 10689 /// foo(MACRO); 10690 /// foo(0); 10691 /// \endcode 10692 /// 10693 /// This should return true for the first call to foo, but not for the second 10694 /// (regardless of whether foo is a macro or function). 10695 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10696 SourceLocation CallLoc, 10697 SourceLocation ArgLoc) { 10698 if (!CallLoc.isMacroID()) 10699 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10700 10701 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10702 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10703 } 10704 10705 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10706 /// last two arguments transposed. 10707 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10708 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10709 return; 10710 10711 const Expr *SizeArg = 10712 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10713 10714 auto isLiteralZero = [](const Expr *E) { 10715 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10716 }; 10717 10718 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10719 SourceLocation CallLoc = Call->getRParenLoc(); 10720 SourceManager &SM = S.getSourceManager(); 10721 if (isLiteralZero(SizeArg) && 10722 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10723 10724 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10725 10726 // Some platforms #define bzero to __builtin_memset. See if this is the 10727 // case, and if so, emit a better diagnostic. 10728 if (BId == Builtin::BIbzero || 10729 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10730 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10731 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10732 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10733 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10734 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10735 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10736 } 10737 return; 10738 } 10739 10740 // If the second argument to a memset is a sizeof expression and the third 10741 // isn't, this is also likely an error. This should catch 10742 // 'memset(buf, sizeof(buf), 0xff)'. 10743 if (BId == Builtin::BImemset && 10744 doesExprLikelyComputeSize(Call->getArg(1)) && 10745 !doesExprLikelyComputeSize(Call->getArg(2))) { 10746 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10747 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10748 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10749 return; 10750 } 10751 } 10752 10753 /// Check for dangerous or invalid arguments to memset(). 10754 /// 10755 /// This issues warnings on known problematic, dangerous or unspecified 10756 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10757 /// function calls. 10758 /// 10759 /// \param Call The call expression to diagnose. 10760 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10761 unsigned BId, 10762 IdentifierInfo *FnName) { 10763 assert(BId != 0); 10764 10765 // It is possible to have a non-standard definition of memset. Validate 10766 // we have enough arguments, and if not, abort further checking. 10767 unsigned ExpectedNumArgs = 10768 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10769 if (Call->getNumArgs() < ExpectedNumArgs) 10770 return; 10771 10772 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10773 BId == Builtin::BIstrndup ? 1 : 2); 10774 unsigned LenArg = 10775 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10776 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10777 10778 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10779 Call->getBeginLoc(), Call->getRParenLoc())) 10780 return; 10781 10782 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10783 CheckMemaccessSize(*this, BId, Call); 10784 10785 // We have special checking when the length is a sizeof expression. 10786 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10787 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10788 llvm::FoldingSetNodeID SizeOfArgID; 10789 10790 // Although widely used, 'bzero' is not a standard function. Be more strict 10791 // with the argument types before allowing diagnostics and only allow the 10792 // form bzero(ptr, sizeof(...)). 10793 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10794 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10795 return; 10796 10797 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10798 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10799 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10800 10801 QualType DestTy = Dest->getType(); 10802 QualType PointeeTy; 10803 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10804 PointeeTy = DestPtrTy->getPointeeType(); 10805 10806 // Never warn about void type pointers. This can be used to suppress 10807 // false positives. 10808 if (PointeeTy->isVoidType()) 10809 continue; 10810 10811 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10812 // actually comparing the expressions for equality. Because computing the 10813 // expression IDs can be expensive, we only do this if the diagnostic is 10814 // enabled. 10815 if (SizeOfArg && 10816 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10817 SizeOfArg->getExprLoc())) { 10818 // We only compute IDs for expressions if the warning is enabled, and 10819 // cache the sizeof arg's ID. 10820 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10821 SizeOfArg->Profile(SizeOfArgID, Context, true); 10822 llvm::FoldingSetNodeID DestID; 10823 Dest->Profile(DestID, Context, true); 10824 if (DestID == SizeOfArgID) { 10825 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10826 // over sizeof(src) as well. 10827 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10828 StringRef ReadableName = FnName->getName(); 10829 10830 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10831 if (UnaryOp->getOpcode() == UO_AddrOf) 10832 ActionIdx = 1; // If its an address-of operator, just remove it. 10833 if (!PointeeTy->isIncompleteType() && 10834 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10835 ActionIdx = 2; // If the pointee's size is sizeof(char), 10836 // suggest an explicit length. 10837 10838 // If the function is defined as a builtin macro, do not show macro 10839 // expansion. 10840 SourceLocation SL = SizeOfArg->getExprLoc(); 10841 SourceRange DSR = Dest->getSourceRange(); 10842 SourceRange SSR = SizeOfArg->getSourceRange(); 10843 SourceManager &SM = getSourceManager(); 10844 10845 if (SM.isMacroArgExpansion(SL)) { 10846 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10847 SL = SM.getSpellingLoc(SL); 10848 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10849 SM.getSpellingLoc(DSR.getEnd())); 10850 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10851 SM.getSpellingLoc(SSR.getEnd())); 10852 } 10853 10854 DiagRuntimeBehavior(SL, SizeOfArg, 10855 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10856 << ReadableName 10857 << PointeeTy 10858 << DestTy 10859 << DSR 10860 << SSR); 10861 DiagRuntimeBehavior(SL, SizeOfArg, 10862 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10863 << ActionIdx 10864 << SSR); 10865 10866 break; 10867 } 10868 } 10869 10870 // Also check for cases where the sizeof argument is the exact same 10871 // type as the memory argument, and where it points to a user-defined 10872 // record type. 10873 if (SizeOfArgTy != QualType()) { 10874 if (PointeeTy->isRecordType() && 10875 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10876 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10877 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10878 << FnName << SizeOfArgTy << ArgIdx 10879 << PointeeTy << Dest->getSourceRange() 10880 << LenExpr->getSourceRange()); 10881 break; 10882 } 10883 } 10884 } else if (DestTy->isArrayType()) { 10885 PointeeTy = DestTy; 10886 } 10887 10888 if (PointeeTy == QualType()) 10889 continue; 10890 10891 // Always complain about dynamic classes. 10892 bool IsContained; 10893 if (const CXXRecordDecl *ContainedRD = 10894 getContainedDynamicClass(PointeeTy, IsContained)) { 10895 10896 unsigned OperationType = 0; 10897 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10898 // "overwritten" if we're warning about the destination for any call 10899 // but memcmp; otherwise a verb appropriate to the call. 10900 if (ArgIdx != 0 || IsCmp) { 10901 if (BId == Builtin::BImemcpy) 10902 OperationType = 1; 10903 else if(BId == Builtin::BImemmove) 10904 OperationType = 2; 10905 else if (IsCmp) 10906 OperationType = 3; 10907 } 10908 10909 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10910 PDiag(diag::warn_dyn_class_memaccess) 10911 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10912 << IsContained << ContainedRD << OperationType 10913 << Call->getCallee()->getSourceRange()); 10914 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10915 BId != Builtin::BImemset) 10916 DiagRuntimeBehavior( 10917 Dest->getExprLoc(), Dest, 10918 PDiag(diag::warn_arc_object_memaccess) 10919 << ArgIdx << FnName << PointeeTy 10920 << Call->getCallee()->getSourceRange()); 10921 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10922 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10923 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10924 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10925 PDiag(diag::warn_cstruct_memaccess) 10926 << ArgIdx << FnName << PointeeTy << 0); 10927 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10928 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10929 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10930 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10931 PDiag(diag::warn_cstruct_memaccess) 10932 << ArgIdx << FnName << PointeeTy << 1); 10933 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10934 } else { 10935 continue; 10936 } 10937 } else 10938 continue; 10939 10940 DiagRuntimeBehavior( 10941 Dest->getExprLoc(), Dest, 10942 PDiag(diag::note_bad_memaccess_silence) 10943 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10944 break; 10945 } 10946 } 10947 10948 // A little helper routine: ignore addition and subtraction of integer literals. 10949 // This intentionally does not ignore all integer constant expressions because 10950 // we don't want to remove sizeof(). 10951 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10952 Ex = Ex->IgnoreParenCasts(); 10953 10954 while (true) { 10955 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10956 if (!BO || !BO->isAdditiveOp()) 10957 break; 10958 10959 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10960 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10961 10962 if (isa<IntegerLiteral>(RHS)) 10963 Ex = LHS; 10964 else if (isa<IntegerLiteral>(LHS)) 10965 Ex = RHS; 10966 else 10967 break; 10968 } 10969 10970 return Ex; 10971 } 10972 10973 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10974 ASTContext &Context) { 10975 // Only handle constant-sized or VLAs, but not flexible members. 10976 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10977 // Only issue the FIXIT for arrays of size > 1. 10978 if (CAT->getSize().getSExtValue() <= 1) 10979 return false; 10980 } else if (!Ty->isVariableArrayType()) { 10981 return false; 10982 } 10983 return true; 10984 } 10985 10986 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10987 // be the size of the source, instead of the destination. 10988 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10989 IdentifierInfo *FnName) { 10990 10991 // Don't crash if the user has the wrong number of arguments 10992 unsigned NumArgs = Call->getNumArgs(); 10993 if ((NumArgs != 3) && (NumArgs != 4)) 10994 return; 10995 10996 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10997 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10998 const Expr *CompareWithSrc = nullptr; 10999 11000 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 11001 Call->getBeginLoc(), Call->getRParenLoc())) 11002 return; 11003 11004 // Look for 'strlcpy(dst, x, sizeof(x))' 11005 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 11006 CompareWithSrc = Ex; 11007 else { 11008 // Look for 'strlcpy(dst, x, strlen(x))' 11009 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 11010 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 11011 SizeCall->getNumArgs() == 1) 11012 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 11013 } 11014 } 11015 11016 if (!CompareWithSrc) 11017 return; 11018 11019 // Determine if the argument to sizeof/strlen is equal to the source 11020 // argument. In principle there's all kinds of things you could do 11021 // here, for instance creating an == expression and evaluating it with 11022 // EvaluateAsBooleanCondition, but this uses a more direct technique: 11023 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 11024 if (!SrcArgDRE) 11025 return; 11026 11027 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 11028 if (!CompareWithSrcDRE || 11029 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 11030 return; 11031 11032 const Expr *OriginalSizeArg = Call->getArg(2); 11033 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 11034 << OriginalSizeArg->getSourceRange() << FnName; 11035 11036 // Output a FIXIT hint if the destination is an array (rather than a 11037 // pointer to an array). This could be enhanced to handle some 11038 // pointers if we know the actual size, like if DstArg is 'array+2' 11039 // we could say 'sizeof(array)-2'. 11040 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 11041 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 11042 return; 11043 11044 SmallString<128> sizeString; 11045 llvm::raw_svector_ostream OS(sizeString); 11046 OS << "sizeof("; 11047 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11048 OS << ")"; 11049 11050 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 11051 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 11052 OS.str()); 11053 } 11054 11055 /// Check if two expressions refer to the same declaration. 11056 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 11057 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 11058 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 11059 return D1->getDecl() == D2->getDecl(); 11060 return false; 11061 } 11062 11063 static const Expr *getStrlenExprArg(const Expr *E) { 11064 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11065 const FunctionDecl *FD = CE->getDirectCallee(); 11066 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 11067 return nullptr; 11068 return CE->getArg(0)->IgnoreParenCasts(); 11069 } 11070 return nullptr; 11071 } 11072 11073 // Warn on anti-patterns as the 'size' argument to strncat. 11074 // The correct size argument should look like following: 11075 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 11076 void Sema::CheckStrncatArguments(const CallExpr *CE, 11077 IdentifierInfo *FnName) { 11078 // Don't crash if the user has the wrong number of arguments. 11079 if (CE->getNumArgs() < 3) 11080 return; 11081 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 11082 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 11083 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 11084 11085 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 11086 CE->getRParenLoc())) 11087 return; 11088 11089 // Identify common expressions, which are wrongly used as the size argument 11090 // to strncat and may lead to buffer overflows. 11091 unsigned PatternType = 0; 11092 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 11093 // - sizeof(dst) 11094 if (referToTheSameDecl(SizeOfArg, DstArg)) 11095 PatternType = 1; 11096 // - sizeof(src) 11097 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 11098 PatternType = 2; 11099 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 11100 if (BE->getOpcode() == BO_Sub) { 11101 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 11102 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 11103 // - sizeof(dst) - strlen(dst) 11104 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 11105 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 11106 PatternType = 1; 11107 // - sizeof(src) - (anything) 11108 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 11109 PatternType = 2; 11110 } 11111 } 11112 11113 if (PatternType == 0) 11114 return; 11115 11116 // Generate the diagnostic. 11117 SourceLocation SL = LenArg->getBeginLoc(); 11118 SourceRange SR = LenArg->getSourceRange(); 11119 SourceManager &SM = getSourceManager(); 11120 11121 // If the function is defined as a builtin macro, do not show macro expansion. 11122 if (SM.isMacroArgExpansion(SL)) { 11123 SL = SM.getSpellingLoc(SL); 11124 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 11125 SM.getSpellingLoc(SR.getEnd())); 11126 } 11127 11128 // Check if the destination is an array (rather than a pointer to an array). 11129 QualType DstTy = DstArg->getType(); 11130 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 11131 Context); 11132 if (!isKnownSizeArray) { 11133 if (PatternType == 1) 11134 Diag(SL, diag::warn_strncat_wrong_size) << SR; 11135 else 11136 Diag(SL, diag::warn_strncat_src_size) << SR; 11137 return; 11138 } 11139 11140 if (PatternType == 1) 11141 Diag(SL, diag::warn_strncat_large_size) << SR; 11142 else 11143 Diag(SL, diag::warn_strncat_src_size) << SR; 11144 11145 SmallString<128> sizeString; 11146 llvm::raw_svector_ostream OS(sizeString); 11147 OS << "sizeof("; 11148 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11149 OS << ") - "; 11150 OS << "strlen("; 11151 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11152 OS << ") - 1"; 11153 11154 Diag(SL, diag::note_strncat_wrong_size) 11155 << FixItHint::CreateReplacement(SR, OS.str()); 11156 } 11157 11158 namespace { 11159 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 11160 const UnaryOperator *UnaryExpr, const Decl *D) { 11161 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 11162 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 11163 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 11164 return; 11165 } 11166 } 11167 11168 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 11169 const UnaryOperator *UnaryExpr) { 11170 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 11171 const Decl *D = Lvalue->getDecl(); 11172 if (isa<DeclaratorDecl>(D)) 11173 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType()) 11174 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 11175 } 11176 11177 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 11178 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 11179 Lvalue->getMemberDecl()); 11180 } 11181 11182 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 11183 const UnaryOperator *UnaryExpr) { 11184 const auto *Lambda = dyn_cast<LambdaExpr>( 11185 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 11186 if (!Lambda) 11187 return; 11188 11189 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 11190 << CalleeName << 2 /*object: lambda expression*/; 11191 } 11192 11193 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 11194 const DeclRefExpr *Lvalue) { 11195 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 11196 if (Var == nullptr) 11197 return; 11198 11199 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 11200 << CalleeName << 0 /*object: */ << Var; 11201 } 11202 11203 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 11204 const CastExpr *Cast) { 11205 SmallString<128> SizeString; 11206 llvm::raw_svector_ostream OS(SizeString); 11207 11208 clang::CastKind Kind = Cast->getCastKind(); 11209 if (Kind == clang::CK_BitCast && 11210 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 11211 return; 11212 if (Kind == clang::CK_IntegralToPointer && 11213 !isa<IntegerLiteral>( 11214 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 11215 return; 11216 11217 switch (Cast->getCastKind()) { 11218 case clang::CK_BitCast: 11219 case clang::CK_IntegralToPointer: 11220 case clang::CK_FunctionToPointerDecay: 11221 OS << '\''; 11222 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 11223 OS << '\''; 11224 break; 11225 default: 11226 return; 11227 } 11228 11229 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 11230 << CalleeName << 0 /*object: */ << OS.str(); 11231 } 11232 } // namespace 11233 11234 /// Alerts the user that they are attempting to free a non-malloc'd object. 11235 void Sema::CheckFreeArguments(const CallExpr *E) { 11236 const std::string CalleeName = 11237 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 11238 11239 { // Prefer something that doesn't involve a cast to make things simpler. 11240 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 11241 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 11242 switch (UnaryExpr->getOpcode()) { 11243 case UnaryOperator::Opcode::UO_AddrOf: 11244 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 11245 case UnaryOperator::Opcode::UO_Plus: 11246 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 11247 default: 11248 break; 11249 } 11250 11251 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 11252 if (Lvalue->getType()->isArrayType()) 11253 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 11254 11255 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 11256 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 11257 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 11258 return; 11259 } 11260 11261 if (isa<BlockExpr>(Arg)) { 11262 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 11263 << CalleeName << 1 /*object: block*/; 11264 return; 11265 } 11266 } 11267 // Maybe the cast was important, check after the other cases. 11268 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 11269 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 11270 } 11271 11272 void 11273 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 11274 SourceLocation ReturnLoc, 11275 bool isObjCMethod, 11276 const AttrVec *Attrs, 11277 const FunctionDecl *FD) { 11278 // Check if the return value is null but should not be. 11279 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 11280 (!isObjCMethod && isNonNullType(Context, lhsType))) && 11281 CheckNonNullExpr(*this, RetValExp)) 11282 Diag(ReturnLoc, diag::warn_null_ret) 11283 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 11284 11285 // C++11 [basic.stc.dynamic.allocation]p4: 11286 // If an allocation function declared with a non-throwing 11287 // exception-specification fails to allocate storage, it shall return 11288 // a null pointer. Any other allocation function that fails to allocate 11289 // storage shall indicate failure only by throwing an exception [...] 11290 if (FD) { 11291 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 11292 if (Op == OO_New || Op == OO_Array_New) { 11293 const FunctionProtoType *Proto 11294 = FD->getType()->castAs<FunctionProtoType>(); 11295 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 11296 CheckNonNullExpr(*this, RetValExp)) 11297 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 11298 << FD << getLangOpts().CPlusPlus11; 11299 } 11300 } 11301 11302 // PPC MMA non-pointer types are not allowed as return type. Checking the type 11303 // here prevent the user from using a PPC MMA type as trailing return type. 11304 if (Context.getTargetInfo().getTriple().isPPC64()) 11305 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 11306 } 11307 11308 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 11309 11310 /// Check for comparisons of floating point operands using != and ==. 11311 /// Issue a warning if these are no self-comparisons, as they are not likely 11312 /// to do what the programmer intended. 11313 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 11314 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 11315 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 11316 11317 // Special case: check for x == x (which is OK). 11318 // Do not emit warnings for such cases. 11319 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 11320 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 11321 if (DRL->getDecl() == DRR->getDecl()) 11322 return; 11323 11324 // Special case: check for comparisons against literals that can be exactly 11325 // represented by APFloat. In such cases, do not emit a warning. This 11326 // is a heuristic: often comparison against such literals are used to 11327 // detect if a value in a variable has not changed. This clearly can 11328 // lead to false negatives. 11329 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 11330 if (FLL->isExact()) 11331 return; 11332 } else 11333 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 11334 if (FLR->isExact()) 11335 return; 11336 11337 // Check for comparisons with builtin types. 11338 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 11339 if (CL->getBuiltinCallee()) 11340 return; 11341 11342 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 11343 if (CR->getBuiltinCallee()) 11344 return; 11345 11346 // Emit the diagnostic. 11347 Diag(Loc, diag::warn_floatingpoint_eq) 11348 << LHS->getSourceRange() << RHS->getSourceRange(); 11349 } 11350 11351 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 11352 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 11353 11354 namespace { 11355 11356 /// Structure recording the 'active' range of an integer-valued 11357 /// expression. 11358 struct IntRange { 11359 /// The number of bits active in the int. Note that this includes exactly one 11360 /// sign bit if !NonNegative. 11361 unsigned Width; 11362 11363 /// True if the int is known not to have negative values. If so, all leading 11364 /// bits before Width are known zero, otherwise they are known to be the 11365 /// same as the MSB within Width. 11366 bool NonNegative; 11367 11368 IntRange(unsigned Width, bool NonNegative) 11369 : Width(Width), NonNegative(NonNegative) {} 11370 11371 /// Number of bits excluding the sign bit. 11372 unsigned valueBits() const { 11373 return NonNegative ? Width : Width - 1; 11374 } 11375 11376 /// Returns the range of the bool type. 11377 static IntRange forBoolType() { 11378 return IntRange(1, true); 11379 } 11380 11381 /// Returns the range of an opaque value of the given integral type. 11382 static IntRange forValueOfType(ASTContext &C, QualType T) { 11383 return forValueOfCanonicalType(C, 11384 T->getCanonicalTypeInternal().getTypePtr()); 11385 } 11386 11387 /// Returns the range of an opaque value of a canonical integral type. 11388 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 11389 assert(T->isCanonicalUnqualified()); 11390 11391 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11392 T = VT->getElementType().getTypePtr(); 11393 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11394 T = CT->getElementType().getTypePtr(); 11395 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11396 T = AT->getValueType().getTypePtr(); 11397 11398 if (!C.getLangOpts().CPlusPlus) { 11399 // For enum types in C code, use the underlying datatype. 11400 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11401 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 11402 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 11403 // For enum types in C++, use the known bit width of the enumerators. 11404 EnumDecl *Enum = ET->getDecl(); 11405 // In C++11, enums can have a fixed underlying type. Use this type to 11406 // compute the range. 11407 if (Enum->isFixed()) { 11408 return IntRange(C.getIntWidth(QualType(T, 0)), 11409 !ET->isSignedIntegerOrEnumerationType()); 11410 } 11411 11412 unsigned NumPositive = Enum->getNumPositiveBits(); 11413 unsigned NumNegative = Enum->getNumNegativeBits(); 11414 11415 if (NumNegative == 0) 11416 return IntRange(NumPositive, true/*NonNegative*/); 11417 else 11418 return IntRange(std::max(NumPositive + 1, NumNegative), 11419 false/*NonNegative*/); 11420 } 11421 11422 if (const auto *EIT = dyn_cast<BitIntType>(T)) 11423 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11424 11425 const BuiltinType *BT = cast<BuiltinType>(T); 11426 assert(BT->isInteger()); 11427 11428 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11429 } 11430 11431 /// Returns the "target" range of a canonical integral type, i.e. 11432 /// the range of values expressible in the type. 11433 /// 11434 /// This matches forValueOfCanonicalType except that enums have the 11435 /// full range of their type, not the range of their enumerators. 11436 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 11437 assert(T->isCanonicalUnqualified()); 11438 11439 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11440 T = VT->getElementType().getTypePtr(); 11441 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11442 T = CT->getElementType().getTypePtr(); 11443 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11444 T = AT->getValueType().getTypePtr(); 11445 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11446 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 11447 11448 if (const auto *EIT = dyn_cast<BitIntType>(T)) 11449 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11450 11451 const BuiltinType *BT = cast<BuiltinType>(T); 11452 assert(BT->isInteger()); 11453 11454 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11455 } 11456 11457 /// Returns the supremum of two ranges: i.e. their conservative merge. 11458 static IntRange join(IntRange L, IntRange R) { 11459 bool Unsigned = L.NonNegative && R.NonNegative; 11460 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 11461 L.NonNegative && R.NonNegative); 11462 } 11463 11464 /// Return the range of a bitwise-AND of the two ranges. 11465 static IntRange bit_and(IntRange L, IntRange R) { 11466 unsigned Bits = std::max(L.Width, R.Width); 11467 bool NonNegative = false; 11468 if (L.NonNegative) { 11469 Bits = std::min(Bits, L.Width); 11470 NonNegative = true; 11471 } 11472 if (R.NonNegative) { 11473 Bits = std::min(Bits, R.Width); 11474 NonNegative = true; 11475 } 11476 return IntRange(Bits, NonNegative); 11477 } 11478 11479 /// Return the range of a sum of the two ranges. 11480 static IntRange sum(IntRange L, IntRange R) { 11481 bool Unsigned = L.NonNegative && R.NonNegative; 11482 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 11483 Unsigned); 11484 } 11485 11486 /// Return the range of a difference of the two ranges. 11487 static IntRange difference(IntRange L, IntRange R) { 11488 // We need a 1-bit-wider range if: 11489 // 1) LHS can be negative: least value can be reduced. 11490 // 2) RHS can be negative: greatest value can be increased. 11491 bool CanWiden = !L.NonNegative || !R.NonNegative; 11492 bool Unsigned = L.NonNegative && R.Width == 0; 11493 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 11494 !Unsigned, 11495 Unsigned); 11496 } 11497 11498 /// Return the range of a product of the two ranges. 11499 static IntRange product(IntRange L, IntRange R) { 11500 // If both LHS and RHS can be negative, we can form 11501 // -2^L * -2^R = 2^(L + R) 11502 // which requires L + R + 1 value bits to represent. 11503 bool CanWiden = !L.NonNegative && !R.NonNegative; 11504 bool Unsigned = L.NonNegative && R.NonNegative; 11505 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 11506 Unsigned); 11507 } 11508 11509 /// Return the range of a remainder operation between the two ranges. 11510 static IntRange rem(IntRange L, IntRange R) { 11511 // The result of a remainder can't be larger than the result of 11512 // either side. The sign of the result is the sign of the LHS. 11513 bool Unsigned = L.NonNegative; 11514 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 11515 Unsigned); 11516 } 11517 }; 11518 11519 } // namespace 11520 11521 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 11522 unsigned MaxWidth) { 11523 if (value.isSigned() && value.isNegative()) 11524 return IntRange(value.getMinSignedBits(), false); 11525 11526 if (value.getBitWidth() > MaxWidth) 11527 value = value.trunc(MaxWidth); 11528 11529 // isNonNegative() just checks the sign bit without considering 11530 // signedness. 11531 return IntRange(value.getActiveBits(), true); 11532 } 11533 11534 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 11535 unsigned MaxWidth) { 11536 if (result.isInt()) 11537 return GetValueRange(C, result.getInt(), MaxWidth); 11538 11539 if (result.isVector()) { 11540 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 11541 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 11542 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 11543 R = IntRange::join(R, El); 11544 } 11545 return R; 11546 } 11547 11548 if (result.isComplexInt()) { 11549 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 11550 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 11551 return IntRange::join(R, I); 11552 } 11553 11554 // This can happen with lossless casts to intptr_t of "based" lvalues. 11555 // Assume it might use arbitrary bits. 11556 // FIXME: The only reason we need to pass the type in here is to get 11557 // the sign right on this one case. It would be nice if APValue 11558 // preserved this. 11559 assert(result.isLValue() || result.isAddrLabelDiff()); 11560 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 11561 } 11562 11563 static QualType GetExprType(const Expr *E) { 11564 QualType Ty = E->getType(); 11565 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 11566 Ty = AtomicRHS->getValueType(); 11567 return Ty; 11568 } 11569 11570 /// Pseudo-evaluate the given integer expression, estimating the 11571 /// range of values it might take. 11572 /// 11573 /// \param MaxWidth The width to which the value will be truncated. 11574 /// \param Approximate If \c true, return a likely range for the result: in 11575 /// particular, assume that arithmetic on narrower types doesn't leave 11576 /// those types. If \c false, return a range including all possible 11577 /// result values. 11578 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 11579 bool InConstantContext, bool Approximate) { 11580 E = E->IgnoreParens(); 11581 11582 // Try a full evaluation first. 11583 Expr::EvalResult result; 11584 if (E->EvaluateAsRValue(result, C, InConstantContext)) 11585 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 11586 11587 // I think we only want to look through implicit casts here; if the 11588 // user has an explicit widening cast, we should treat the value as 11589 // being of the new, wider type. 11590 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 11591 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 11592 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 11593 Approximate); 11594 11595 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 11596 11597 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 11598 CE->getCastKind() == CK_BooleanToSignedIntegral; 11599 11600 // Assume that non-integer casts can span the full range of the type. 11601 if (!isIntegerCast) 11602 return OutputTypeRange; 11603 11604 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 11605 std::min(MaxWidth, OutputTypeRange.Width), 11606 InConstantContext, Approximate); 11607 11608 // Bail out if the subexpr's range is as wide as the cast type. 11609 if (SubRange.Width >= OutputTypeRange.Width) 11610 return OutputTypeRange; 11611 11612 // Otherwise, we take the smaller width, and we're non-negative if 11613 // either the output type or the subexpr is. 11614 return IntRange(SubRange.Width, 11615 SubRange.NonNegative || OutputTypeRange.NonNegative); 11616 } 11617 11618 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11619 // If we can fold the condition, just take that operand. 11620 bool CondResult; 11621 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 11622 return GetExprRange(C, 11623 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 11624 MaxWidth, InConstantContext, Approximate); 11625 11626 // Otherwise, conservatively merge. 11627 // GetExprRange requires an integer expression, but a throw expression 11628 // results in a void type. 11629 Expr *E = CO->getTrueExpr(); 11630 IntRange L = E->getType()->isVoidType() 11631 ? IntRange{0, true} 11632 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11633 E = CO->getFalseExpr(); 11634 IntRange R = E->getType()->isVoidType() 11635 ? IntRange{0, true} 11636 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11637 return IntRange::join(L, R); 11638 } 11639 11640 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11641 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 11642 11643 switch (BO->getOpcode()) { 11644 case BO_Cmp: 11645 llvm_unreachable("builtin <=> should have class type"); 11646 11647 // Boolean-valued operations are single-bit and positive. 11648 case BO_LAnd: 11649 case BO_LOr: 11650 case BO_LT: 11651 case BO_GT: 11652 case BO_LE: 11653 case BO_GE: 11654 case BO_EQ: 11655 case BO_NE: 11656 return IntRange::forBoolType(); 11657 11658 // The type of the assignments is the type of the LHS, so the RHS 11659 // is not necessarily the same type. 11660 case BO_MulAssign: 11661 case BO_DivAssign: 11662 case BO_RemAssign: 11663 case BO_AddAssign: 11664 case BO_SubAssign: 11665 case BO_XorAssign: 11666 case BO_OrAssign: 11667 // TODO: bitfields? 11668 return IntRange::forValueOfType(C, GetExprType(E)); 11669 11670 // Simple assignments just pass through the RHS, which will have 11671 // been coerced to the LHS type. 11672 case BO_Assign: 11673 // TODO: bitfields? 11674 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11675 Approximate); 11676 11677 // Operations with opaque sources are black-listed. 11678 case BO_PtrMemD: 11679 case BO_PtrMemI: 11680 return IntRange::forValueOfType(C, GetExprType(E)); 11681 11682 // Bitwise-and uses the *infinum* of the two source ranges. 11683 case BO_And: 11684 case BO_AndAssign: 11685 Combine = IntRange::bit_and; 11686 break; 11687 11688 // Left shift gets black-listed based on a judgement call. 11689 case BO_Shl: 11690 // ...except that we want to treat '1 << (blah)' as logically 11691 // positive. It's an important idiom. 11692 if (IntegerLiteral *I 11693 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11694 if (I->getValue() == 1) { 11695 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11696 return IntRange(R.Width, /*NonNegative*/ true); 11697 } 11698 } 11699 LLVM_FALLTHROUGH; 11700 11701 case BO_ShlAssign: 11702 return IntRange::forValueOfType(C, GetExprType(E)); 11703 11704 // Right shift by a constant can narrow its left argument. 11705 case BO_Shr: 11706 case BO_ShrAssign: { 11707 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11708 Approximate); 11709 11710 // If the shift amount is a positive constant, drop the width by 11711 // that much. 11712 if (Optional<llvm::APSInt> shift = 11713 BO->getRHS()->getIntegerConstantExpr(C)) { 11714 if (shift->isNonNegative()) { 11715 unsigned zext = shift->getZExtValue(); 11716 if (zext >= L.Width) 11717 L.Width = (L.NonNegative ? 0 : 1); 11718 else 11719 L.Width -= zext; 11720 } 11721 } 11722 11723 return L; 11724 } 11725 11726 // Comma acts as its right operand. 11727 case BO_Comma: 11728 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11729 Approximate); 11730 11731 case BO_Add: 11732 if (!Approximate) 11733 Combine = IntRange::sum; 11734 break; 11735 11736 case BO_Sub: 11737 if (BO->getLHS()->getType()->isPointerType()) 11738 return IntRange::forValueOfType(C, GetExprType(E)); 11739 if (!Approximate) 11740 Combine = IntRange::difference; 11741 break; 11742 11743 case BO_Mul: 11744 if (!Approximate) 11745 Combine = IntRange::product; 11746 break; 11747 11748 // The width of a division result is mostly determined by the size 11749 // of the LHS. 11750 case BO_Div: { 11751 // Don't 'pre-truncate' the operands. 11752 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11753 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11754 Approximate); 11755 11756 // If the divisor is constant, use that. 11757 if (Optional<llvm::APSInt> divisor = 11758 BO->getRHS()->getIntegerConstantExpr(C)) { 11759 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11760 if (log2 >= L.Width) 11761 L.Width = (L.NonNegative ? 0 : 1); 11762 else 11763 L.Width = std::min(L.Width - log2, MaxWidth); 11764 return L; 11765 } 11766 11767 // Otherwise, just use the LHS's width. 11768 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11769 // could be -1. 11770 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11771 Approximate); 11772 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11773 } 11774 11775 case BO_Rem: 11776 Combine = IntRange::rem; 11777 break; 11778 11779 // The default behavior is okay for these. 11780 case BO_Xor: 11781 case BO_Or: 11782 break; 11783 } 11784 11785 // Combine the two ranges, but limit the result to the type in which we 11786 // performed the computation. 11787 QualType T = GetExprType(E); 11788 unsigned opWidth = C.getIntWidth(T); 11789 IntRange L = 11790 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11791 IntRange R = 11792 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11793 IntRange C = Combine(L, R); 11794 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11795 C.Width = std::min(C.Width, MaxWidth); 11796 return C; 11797 } 11798 11799 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11800 switch (UO->getOpcode()) { 11801 // Boolean-valued operations are white-listed. 11802 case UO_LNot: 11803 return IntRange::forBoolType(); 11804 11805 // Operations with opaque sources are black-listed. 11806 case UO_Deref: 11807 case UO_AddrOf: // should be impossible 11808 return IntRange::forValueOfType(C, GetExprType(E)); 11809 11810 default: 11811 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11812 Approximate); 11813 } 11814 } 11815 11816 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11817 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11818 Approximate); 11819 11820 if (const auto *BitField = E->getSourceBitField()) 11821 return IntRange(BitField->getBitWidthValue(C), 11822 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11823 11824 return IntRange::forValueOfType(C, GetExprType(E)); 11825 } 11826 11827 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11828 bool InConstantContext, bool Approximate) { 11829 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11830 Approximate); 11831 } 11832 11833 /// Checks whether the given value, which currently has the given 11834 /// source semantics, has the same value when coerced through the 11835 /// target semantics. 11836 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11837 const llvm::fltSemantics &Src, 11838 const llvm::fltSemantics &Tgt) { 11839 llvm::APFloat truncated = value; 11840 11841 bool ignored; 11842 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11843 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11844 11845 return truncated.bitwiseIsEqual(value); 11846 } 11847 11848 /// Checks whether the given value, which currently has the given 11849 /// source semantics, has the same value when coerced through the 11850 /// target semantics. 11851 /// 11852 /// The value might be a vector of floats (or a complex number). 11853 static bool IsSameFloatAfterCast(const APValue &value, 11854 const llvm::fltSemantics &Src, 11855 const llvm::fltSemantics &Tgt) { 11856 if (value.isFloat()) 11857 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11858 11859 if (value.isVector()) { 11860 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11861 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11862 return false; 11863 return true; 11864 } 11865 11866 assert(value.isComplexFloat()); 11867 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11868 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11869 } 11870 11871 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11872 bool IsListInit = false); 11873 11874 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11875 // Suppress cases where we are comparing against an enum constant. 11876 if (const DeclRefExpr *DR = 11877 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11878 if (isa<EnumConstantDecl>(DR->getDecl())) 11879 return true; 11880 11881 // Suppress cases where the value is expanded from a macro, unless that macro 11882 // is how a language represents a boolean literal. This is the case in both C 11883 // and Objective-C. 11884 SourceLocation BeginLoc = E->getBeginLoc(); 11885 if (BeginLoc.isMacroID()) { 11886 StringRef MacroName = Lexer::getImmediateMacroName( 11887 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11888 return MacroName != "YES" && MacroName != "NO" && 11889 MacroName != "true" && MacroName != "false"; 11890 } 11891 11892 return false; 11893 } 11894 11895 static bool isKnownToHaveUnsignedValue(Expr *E) { 11896 return E->getType()->isIntegerType() && 11897 (!E->getType()->isSignedIntegerType() || 11898 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11899 } 11900 11901 namespace { 11902 /// The promoted range of values of a type. In general this has the 11903 /// following structure: 11904 /// 11905 /// |-----------| . . . |-----------| 11906 /// ^ ^ ^ ^ 11907 /// Min HoleMin HoleMax Max 11908 /// 11909 /// ... where there is only a hole if a signed type is promoted to unsigned 11910 /// (in which case Min and Max are the smallest and largest representable 11911 /// values). 11912 struct PromotedRange { 11913 // Min, or HoleMax if there is a hole. 11914 llvm::APSInt PromotedMin; 11915 // Max, or HoleMin if there is a hole. 11916 llvm::APSInt PromotedMax; 11917 11918 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11919 if (R.Width == 0) 11920 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11921 else if (R.Width >= BitWidth && !Unsigned) { 11922 // Promotion made the type *narrower*. This happens when promoting 11923 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11924 // Treat all values of 'signed int' as being in range for now. 11925 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11926 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11927 } else { 11928 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11929 .extOrTrunc(BitWidth); 11930 PromotedMin.setIsUnsigned(Unsigned); 11931 11932 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11933 .extOrTrunc(BitWidth); 11934 PromotedMax.setIsUnsigned(Unsigned); 11935 } 11936 } 11937 11938 // Determine whether this range is contiguous (has no hole). 11939 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11940 11941 // Where a constant value is within the range. 11942 enum ComparisonResult { 11943 LT = 0x1, 11944 LE = 0x2, 11945 GT = 0x4, 11946 GE = 0x8, 11947 EQ = 0x10, 11948 NE = 0x20, 11949 InRangeFlag = 0x40, 11950 11951 Less = LE | LT | NE, 11952 Min = LE | InRangeFlag, 11953 InRange = InRangeFlag, 11954 Max = GE | InRangeFlag, 11955 Greater = GE | GT | NE, 11956 11957 OnlyValue = LE | GE | EQ | InRangeFlag, 11958 InHole = NE 11959 }; 11960 11961 ComparisonResult compare(const llvm::APSInt &Value) const { 11962 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11963 Value.isUnsigned() == PromotedMin.isUnsigned()); 11964 if (!isContiguous()) { 11965 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11966 if (Value.isMinValue()) return Min; 11967 if (Value.isMaxValue()) return Max; 11968 if (Value >= PromotedMin) return InRange; 11969 if (Value <= PromotedMax) return InRange; 11970 return InHole; 11971 } 11972 11973 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11974 case -1: return Less; 11975 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11976 case 1: 11977 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11978 case -1: return InRange; 11979 case 0: return Max; 11980 case 1: return Greater; 11981 } 11982 } 11983 11984 llvm_unreachable("impossible compare result"); 11985 } 11986 11987 static llvm::Optional<StringRef> 11988 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11989 if (Op == BO_Cmp) { 11990 ComparisonResult LTFlag = LT, GTFlag = GT; 11991 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11992 11993 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11994 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11995 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11996 return llvm::None; 11997 } 11998 11999 ComparisonResult TrueFlag, FalseFlag; 12000 if (Op == BO_EQ) { 12001 TrueFlag = EQ; 12002 FalseFlag = NE; 12003 } else if (Op == BO_NE) { 12004 TrueFlag = NE; 12005 FalseFlag = EQ; 12006 } else { 12007 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 12008 TrueFlag = LT; 12009 FalseFlag = GE; 12010 } else { 12011 TrueFlag = GT; 12012 FalseFlag = LE; 12013 } 12014 if (Op == BO_GE || Op == BO_LE) 12015 std::swap(TrueFlag, FalseFlag); 12016 } 12017 if (R & TrueFlag) 12018 return StringRef("true"); 12019 if (R & FalseFlag) 12020 return StringRef("false"); 12021 return llvm::None; 12022 } 12023 }; 12024 } 12025 12026 static bool HasEnumType(Expr *E) { 12027 // Strip off implicit integral promotions. 12028 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12029 if (ICE->getCastKind() != CK_IntegralCast && 12030 ICE->getCastKind() != CK_NoOp) 12031 break; 12032 E = ICE->getSubExpr(); 12033 } 12034 12035 return E->getType()->isEnumeralType(); 12036 } 12037 12038 static int classifyConstantValue(Expr *Constant) { 12039 // The values of this enumeration are used in the diagnostics 12040 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 12041 enum ConstantValueKind { 12042 Miscellaneous = 0, 12043 LiteralTrue, 12044 LiteralFalse 12045 }; 12046 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 12047 return BL->getValue() ? ConstantValueKind::LiteralTrue 12048 : ConstantValueKind::LiteralFalse; 12049 return ConstantValueKind::Miscellaneous; 12050 } 12051 12052 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 12053 Expr *Constant, Expr *Other, 12054 const llvm::APSInt &Value, 12055 bool RhsConstant) { 12056 if (S.inTemplateInstantiation()) 12057 return false; 12058 12059 Expr *OriginalOther = Other; 12060 12061 Constant = Constant->IgnoreParenImpCasts(); 12062 Other = Other->IgnoreParenImpCasts(); 12063 12064 // Suppress warnings on tautological comparisons between values of the same 12065 // enumeration type. There are only two ways we could warn on this: 12066 // - If the constant is outside the range of representable values of 12067 // the enumeration. In such a case, we should warn about the cast 12068 // to enumeration type, not about the comparison. 12069 // - If the constant is the maximum / minimum in-range value. For an 12070 // enumeratin type, such comparisons can be meaningful and useful. 12071 if (Constant->getType()->isEnumeralType() && 12072 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 12073 return false; 12074 12075 IntRange OtherValueRange = GetExprRange( 12076 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 12077 12078 QualType OtherT = Other->getType(); 12079 if (const auto *AT = OtherT->getAs<AtomicType>()) 12080 OtherT = AT->getValueType(); 12081 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 12082 12083 // Special case for ObjC BOOL on targets where its a typedef for a signed char 12084 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 12085 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 12086 S.NSAPIObj->isObjCBOOLType(OtherT) && 12087 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 12088 12089 // Whether we're treating Other as being a bool because of the form of 12090 // expression despite it having another type (typically 'int' in C). 12091 bool OtherIsBooleanDespiteType = 12092 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 12093 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 12094 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 12095 12096 // Check if all values in the range of possible values of this expression 12097 // lead to the same comparison outcome. 12098 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 12099 Value.isUnsigned()); 12100 auto Cmp = OtherPromotedValueRange.compare(Value); 12101 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 12102 if (!Result) 12103 return false; 12104 12105 // Also consider the range determined by the type alone. This allows us to 12106 // classify the warning under the proper diagnostic group. 12107 bool TautologicalTypeCompare = false; 12108 { 12109 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 12110 Value.isUnsigned()); 12111 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 12112 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 12113 RhsConstant)) { 12114 TautologicalTypeCompare = true; 12115 Cmp = TypeCmp; 12116 Result = TypeResult; 12117 } 12118 } 12119 12120 // Don't warn if the non-constant operand actually always evaluates to the 12121 // same value. 12122 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 12123 return false; 12124 12125 // Suppress the diagnostic for an in-range comparison if the constant comes 12126 // from a macro or enumerator. We don't want to diagnose 12127 // 12128 // some_long_value <= INT_MAX 12129 // 12130 // when sizeof(int) == sizeof(long). 12131 bool InRange = Cmp & PromotedRange::InRangeFlag; 12132 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 12133 return false; 12134 12135 // A comparison of an unsigned bit-field against 0 is really a type problem, 12136 // even though at the type level the bit-field might promote to 'signed int'. 12137 if (Other->refersToBitField() && InRange && Value == 0 && 12138 Other->getType()->isUnsignedIntegerOrEnumerationType()) 12139 TautologicalTypeCompare = true; 12140 12141 // If this is a comparison to an enum constant, include that 12142 // constant in the diagnostic. 12143 const EnumConstantDecl *ED = nullptr; 12144 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 12145 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 12146 12147 // Should be enough for uint128 (39 decimal digits) 12148 SmallString<64> PrettySourceValue; 12149 llvm::raw_svector_ostream OS(PrettySourceValue); 12150 if (ED) { 12151 OS << '\'' << *ED << "' (" << Value << ")"; 12152 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 12153 Constant->IgnoreParenImpCasts())) { 12154 OS << (BL->getValue() ? "YES" : "NO"); 12155 } else { 12156 OS << Value; 12157 } 12158 12159 if (!TautologicalTypeCompare) { 12160 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 12161 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 12162 << E->getOpcodeStr() << OS.str() << *Result 12163 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 12164 return true; 12165 } 12166 12167 if (IsObjCSignedCharBool) { 12168 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12169 S.PDiag(diag::warn_tautological_compare_objc_bool) 12170 << OS.str() << *Result); 12171 return true; 12172 } 12173 12174 // FIXME: We use a somewhat different formatting for the in-range cases and 12175 // cases involving boolean values for historical reasons. We should pick a 12176 // consistent way of presenting these diagnostics. 12177 if (!InRange || Other->isKnownToHaveBooleanValue()) { 12178 12179 S.DiagRuntimeBehavior( 12180 E->getOperatorLoc(), E, 12181 S.PDiag(!InRange ? diag::warn_out_of_range_compare 12182 : diag::warn_tautological_bool_compare) 12183 << OS.str() << classifyConstantValue(Constant) << OtherT 12184 << OtherIsBooleanDespiteType << *Result 12185 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 12186 } else { 12187 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 12188 unsigned Diag = 12189 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 12190 ? (HasEnumType(OriginalOther) 12191 ? diag::warn_unsigned_enum_always_true_comparison 12192 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 12193 : diag::warn_unsigned_always_true_comparison) 12194 : diag::warn_tautological_constant_compare; 12195 12196 S.Diag(E->getOperatorLoc(), Diag) 12197 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 12198 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 12199 } 12200 12201 return true; 12202 } 12203 12204 /// Analyze the operands of the given comparison. Implements the 12205 /// fallback case from AnalyzeComparison. 12206 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 12207 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12208 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12209 } 12210 12211 /// Implements -Wsign-compare. 12212 /// 12213 /// \param E the binary operator to check for warnings 12214 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 12215 // The type the comparison is being performed in. 12216 QualType T = E->getLHS()->getType(); 12217 12218 // Only analyze comparison operators where both sides have been converted to 12219 // the same type. 12220 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 12221 return AnalyzeImpConvsInComparison(S, E); 12222 12223 // Don't analyze value-dependent comparisons directly. 12224 if (E->isValueDependent()) 12225 return AnalyzeImpConvsInComparison(S, E); 12226 12227 Expr *LHS = E->getLHS(); 12228 Expr *RHS = E->getRHS(); 12229 12230 if (T->isIntegralType(S.Context)) { 12231 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 12232 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 12233 12234 // We don't care about expressions whose result is a constant. 12235 if (RHSValue && LHSValue) 12236 return AnalyzeImpConvsInComparison(S, E); 12237 12238 // We only care about expressions where just one side is literal 12239 if ((bool)RHSValue ^ (bool)LHSValue) { 12240 // Is the constant on the RHS or LHS? 12241 const bool RhsConstant = (bool)RHSValue; 12242 Expr *Const = RhsConstant ? RHS : LHS; 12243 Expr *Other = RhsConstant ? LHS : RHS; 12244 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 12245 12246 // Check whether an integer constant comparison results in a value 12247 // of 'true' or 'false'. 12248 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 12249 return AnalyzeImpConvsInComparison(S, E); 12250 } 12251 } 12252 12253 if (!T->hasUnsignedIntegerRepresentation()) { 12254 // We don't do anything special if this isn't an unsigned integral 12255 // comparison: we're only interested in integral comparisons, and 12256 // signed comparisons only happen in cases we don't care to warn about. 12257 return AnalyzeImpConvsInComparison(S, E); 12258 } 12259 12260 LHS = LHS->IgnoreParenImpCasts(); 12261 RHS = RHS->IgnoreParenImpCasts(); 12262 12263 if (!S.getLangOpts().CPlusPlus) { 12264 // Avoid warning about comparison of integers with different signs when 12265 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 12266 // the type of `E`. 12267 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 12268 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12269 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 12270 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12271 } 12272 12273 // Check to see if one of the (unmodified) operands is of different 12274 // signedness. 12275 Expr *signedOperand, *unsignedOperand; 12276 if (LHS->getType()->hasSignedIntegerRepresentation()) { 12277 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 12278 "unsigned comparison between two signed integer expressions?"); 12279 signedOperand = LHS; 12280 unsignedOperand = RHS; 12281 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 12282 signedOperand = RHS; 12283 unsignedOperand = LHS; 12284 } else { 12285 return AnalyzeImpConvsInComparison(S, E); 12286 } 12287 12288 // Otherwise, calculate the effective range of the signed operand. 12289 IntRange signedRange = GetExprRange( 12290 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 12291 12292 // Go ahead and analyze implicit conversions in the operands. Note 12293 // that we skip the implicit conversions on both sides. 12294 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 12295 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 12296 12297 // If the signed range is non-negative, -Wsign-compare won't fire. 12298 if (signedRange.NonNegative) 12299 return; 12300 12301 // For (in)equality comparisons, if the unsigned operand is a 12302 // constant which cannot collide with a overflowed signed operand, 12303 // then reinterpreting the signed operand as unsigned will not 12304 // change the result of the comparison. 12305 if (E->isEqualityOp()) { 12306 unsigned comparisonWidth = S.Context.getIntWidth(T); 12307 IntRange unsignedRange = 12308 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 12309 /*Approximate*/ true); 12310 12311 // We should never be unable to prove that the unsigned operand is 12312 // non-negative. 12313 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 12314 12315 if (unsignedRange.Width < comparisonWidth) 12316 return; 12317 } 12318 12319 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12320 S.PDiag(diag::warn_mixed_sign_comparison) 12321 << LHS->getType() << RHS->getType() 12322 << LHS->getSourceRange() << RHS->getSourceRange()); 12323 } 12324 12325 /// Analyzes an attempt to assign the given value to a bitfield. 12326 /// 12327 /// Returns true if there was something fishy about the attempt. 12328 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 12329 SourceLocation InitLoc) { 12330 assert(Bitfield->isBitField()); 12331 if (Bitfield->isInvalidDecl()) 12332 return false; 12333 12334 // White-list bool bitfields. 12335 QualType BitfieldType = Bitfield->getType(); 12336 if (BitfieldType->isBooleanType()) 12337 return false; 12338 12339 if (BitfieldType->isEnumeralType()) { 12340 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 12341 // If the underlying enum type was not explicitly specified as an unsigned 12342 // type and the enum contain only positive values, MSVC++ will cause an 12343 // inconsistency by storing this as a signed type. 12344 if (S.getLangOpts().CPlusPlus11 && 12345 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 12346 BitfieldEnumDecl->getNumPositiveBits() > 0 && 12347 BitfieldEnumDecl->getNumNegativeBits() == 0) { 12348 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 12349 << BitfieldEnumDecl; 12350 } 12351 } 12352 12353 if (Bitfield->getType()->isBooleanType()) 12354 return false; 12355 12356 // Ignore value- or type-dependent expressions. 12357 if (Bitfield->getBitWidth()->isValueDependent() || 12358 Bitfield->getBitWidth()->isTypeDependent() || 12359 Init->isValueDependent() || 12360 Init->isTypeDependent()) 12361 return false; 12362 12363 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 12364 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 12365 12366 Expr::EvalResult Result; 12367 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 12368 Expr::SE_AllowSideEffects)) { 12369 // The RHS is not constant. If the RHS has an enum type, make sure the 12370 // bitfield is wide enough to hold all the values of the enum without 12371 // truncation. 12372 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 12373 EnumDecl *ED = EnumTy->getDecl(); 12374 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 12375 12376 // Enum types are implicitly signed on Windows, so check if there are any 12377 // negative enumerators to see if the enum was intended to be signed or 12378 // not. 12379 bool SignedEnum = ED->getNumNegativeBits() > 0; 12380 12381 // Check for surprising sign changes when assigning enum values to a 12382 // bitfield of different signedness. If the bitfield is signed and we 12383 // have exactly the right number of bits to store this unsigned enum, 12384 // suggest changing the enum to an unsigned type. This typically happens 12385 // on Windows where unfixed enums always use an underlying type of 'int'. 12386 unsigned DiagID = 0; 12387 if (SignedEnum && !SignedBitfield) { 12388 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 12389 } else if (SignedBitfield && !SignedEnum && 12390 ED->getNumPositiveBits() == FieldWidth) { 12391 DiagID = diag::warn_signed_bitfield_enum_conversion; 12392 } 12393 12394 if (DiagID) { 12395 S.Diag(InitLoc, DiagID) << Bitfield << ED; 12396 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 12397 SourceRange TypeRange = 12398 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 12399 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 12400 << SignedEnum << TypeRange; 12401 } 12402 12403 // Compute the required bitwidth. If the enum has negative values, we need 12404 // one more bit than the normal number of positive bits to represent the 12405 // sign bit. 12406 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 12407 ED->getNumNegativeBits()) 12408 : ED->getNumPositiveBits(); 12409 12410 // Check the bitwidth. 12411 if (BitsNeeded > FieldWidth) { 12412 Expr *WidthExpr = Bitfield->getBitWidth(); 12413 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 12414 << Bitfield << ED; 12415 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 12416 << BitsNeeded << ED << WidthExpr->getSourceRange(); 12417 } 12418 } 12419 12420 return false; 12421 } 12422 12423 llvm::APSInt Value = Result.Val.getInt(); 12424 12425 unsigned OriginalWidth = Value.getBitWidth(); 12426 12427 if (!Value.isSigned() || Value.isNegative()) 12428 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 12429 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 12430 OriginalWidth = Value.getMinSignedBits(); 12431 12432 if (OriginalWidth <= FieldWidth) 12433 return false; 12434 12435 // Compute the value which the bitfield will contain. 12436 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 12437 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 12438 12439 // Check whether the stored value is equal to the original value. 12440 TruncatedValue = TruncatedValue.extend(OriginalWidth); 12441 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 12442 return false; 12443 12444 // Special-case bitfields of width 1: booleans are naturally 0/1, and 12445 // therefore don't strictly fit into a signed bitfield of width 1. 12446 if (FieldWidth == 1 && Value == 1) 12447 return false; 12448 12449 std::string PrettyValue = toString(Value, 10); 12450 std::string PrettyTrunc = toString(TruncatedValue, 10); 12451 12452 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 12453 << PrettyValue << PrettyTrunc << OriginalInit->getType() 12454 << Init->getSourceRange(); 12455 12456 return true; 12457 } 12458 12459 /// Analyze the given simple or compound assignment for warning-worthy 12460 /// operations. 12461 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 12462 // Just recurse on the LHS. 12463 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12464 12465 // We want to recurse on the RHS as normal unless we're assigning to 12466 // a bitfield. 12467 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 12468 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 12469 E->getOperatorLoc())) { 12470 // Recurse, ignoring any implicit conversions on the RHS. 12471 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 12472 E->getOperatorLoc()); 12473 } 12474 } 12475 12476 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12477 12478 // Diagnose implicitly sequentially-consistent atomic assignment. 12479 if (E->getLHS()->getType()->isAtomicType()) 12480 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12481 } 12482 12483 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12484 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 12485 SourceLocation CContext, unsigned diag, 12486 bool pruneControlFlow = false) { 12487 if (pruneControlFlow) { 12488 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12489 S.PDiag(diag) 12490 << SourceType << T << E->getSourceRange() 12491 << SourceRange(CContext)); 12492 return; 12493 } 12494 S.Diag(E->getExprLoc(), diag) 12495 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 12496 } 12497 12498 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12499 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 12500 SourceLocation CContext, 12501 unsigned diag, bool pruneControlFlow = false) { 12502 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 12503 } 12504 12505 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 12506 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 12507 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 12508 } 12509 12510 static void adornObjCBoolConversionDiagWithTernaryFixit( 12511 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 12512 Expr *Ignored = SourceExpr->IgnoreImplicit(); 12513 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 12514 Ignored = OVE->getSourceExpr(); 12515 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 12516 isa<BinaryOperator>(Ignored) || 12517 isa<CXXOperatorCallExpr>(Ignored); 12518 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 12519 if (NeedsParens) 12520 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 12521 << FixItHint::CreateInsertion(EndLoc, ")"); 12522 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 12523 } 12524 12525 /// Diagnose an implicit cast from a floating point value to an integer value. 12526 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 12527 SourceLocation CContext) { 12528 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 12529 const bool PruneWarnings = S.inTemplateInstantiation(); 12530 12531 Expr *InnerE = E->IgnoreParenImpCasts(); 12532 // We also want to warn on, e.g., "int i = -1.234" 12533 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 12534 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 12535 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 12536 12537 const bool IsLiteral = 12538 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 12539 12540 llvm::APFloat Value(0.0); 12541 bool IsConstant = 12542 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 12543 if (!IsConstant) { 12544 if (isObjCSignedCharBool(S, T)) { 12545 return adornObjCBoolConversionDiagWithTernaryFixit( 12546 S, E, 12547 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 12548 << E->getType()); 12549 } 12550 12551 return DiagnoseImpCast(S, E, T, CContext, 12552 diag::warn_impcast_float_integer, PruneWarnings); 12553 } 12554 12555 bool isExact = false; 12556 12557 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 12558 T->hasUnsignedIntegerRepresentation()); 12559 llvm::APFloat::opStatus Result = Value.convertToInteger( 12560 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 12561 12562 // FIXME: Force the precision of the source value down so we don't print 12563 // digits which are usually useless (we don't really care here if we 12564 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 12565 // would automatically print the shortest representation, but it's a bit 12566 // tricky to implement. 12567 SmallString<16> PrettySourceValue; 12568 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 12569 precision = (precision * 59 + 195) / 196; 12570 Value.toString(PrettySourceValue, precision); 12571 12572 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 12573 return adornObjCBoolConversionDiagWithTernaryFixit( 12574 S, E, 12575 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 12576 << PrettySourceValue); 12577 } 12578 12579 if (Result == llvm::APFloat::opOK && isExact) { 12580 if (IsLiteral) return; 12581 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 12582 PruneWarnings); 12583 } 12584 12585 // Conversion of a floating-point value to a non-bool integer where the 12586 // integral part cannot be represented by the integer type is undefined. 12587 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 12588 return DiagnoseImpCast( 12589 S, E, T, CContext, 12590 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 12591 : diag::warn_impcast_float_to_integer_out_of_range, 12592 PruneWarnings); 12593 12594 unsigned DiagID = 0; 12595 if (IsLiteral) { 12596 // Warn on floating point literal to integer. 12597 DiagID = diag::warn_impcast_literal_float_to_integer; 12598 } else if (IntegerValue == 0) { 12599 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 12600 return DiagnoseImpCast(S, E, T, CContext, 12601 diag::warn_impcast_float_integer, PruneWarnings); 12602 } 12603 // Warn on non-zero to zero conversion. 12604 DiagID = diag::warn_impcast_float_to_integer_zero; 12605 } else { 12606 if (IntegerValue.isUnsigned()) { 12607 if (!IntegerValue.isMaxValue()) { 12608 return DiagnoseImpCast(S, E, T, CContext, 12609 diag::warn_impcast_float_integer, PruneWarnings); 12610 } 12611 } else { // IntegerValue.isSigned() 12612 if (!IntegerValue.isMaxSignedValue() && 12613 !IntegerValue.isMinSignedValue()) { 12614 return DiagnoseImpCast(S, E, T, CContext, 12615 diag::warn_impcast_float_integer, PruneWarnings); 12616 } 12617 } 12618 // Warn on evaluatable floating point expression to integer conversion. 12619 DiagID = diag::warn_impcast_float_to_integer; 12620 } 12621 12622 SmallString<16> PrettyTargetValue; 12623 if (IsBool) 12624 PrettyTargetValue = Value.isZero() ? "false" : "true"; 12625 else 12626 IntegerValue.toString(PrettyTargetValue); 12627 12628 if (PruneWarnings) { 12629 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12630 S.PDiag(DiagID) 12631 << E->getType() << T.getUnqualifiedType() 12632 << PrettySourceValue << PrettyTargetValue 12633 << E->getSourceRange() << SourceRange(CContext)); 12634 } else { 12635 S.Diag(E->getExprLoc(), DiagID) 12636 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 12637 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 12638 } 12639 } 12640 12641 /// Analyze the given compound assignment for the possible losing of 12642 /// floating-point precision. 12643 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 12644 assert(isa<CompoundAssignOperator>(E) && 12645 "Must be compound assignment operation"); 12646 // Recurse on the LHS and RHS in here 12647 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12648 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12649 12650 if (E->getLHS()->getType()->isAtomicType()) 12651 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 12652 12653 // Now check the outermost expression 12654 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 12655 const auto *RBT = cast<CompoundAssignOperator>(E) 12656 ->getComputationResultType() 12657 ->getAs<BuiltinType>(); 12658 12659 // The below checks assume source is floating point. 12660 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 12661 12662 // If source is floating point but target is an integer. 12663 if (ResultBT->isInteger()) 12664 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 12665 E->getExprLoc(), diag::warn_impcast_float_integer); 12666 12667 if (!ResultBT->isFloatingPoint()) 12668 return; 12669 12670 // If both source and target are floating points, warn about losing precision. 12671 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12672 QualType(ResultBT, 0), QualType(RBT, 0)); 12673 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 12674 // warn about dropping FP rank. 12675 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 12676 diag::warn_impcast_float_result_precision); 12677 } 12678 12679 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 12680 IntRange Range) { 12681 if (!Range.Width) return "0"; 12682 12683 llvm::APSInt ValueInRange = Value; 12684 ValueInRange.setIsSigned(!Range.NonNegative); 12685 ValueInRange = ValueInRange.trunc(Range.Width); 12686 return toString(ValueInRange, 10); 12687 } 12688 12689 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 12690 if (!isa<ImplicitCastExpr>(Ex)) 12691 return false; 12692 12693 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12694 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12695 const Type *Source = 12696 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12697 if (Target->isDependentType()) 12698 return false; 12699 12700 const BuiltinType *FloatCandidateBT = 12701 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12702 const Type *BoolCandidateType = ToBool ? Target : Source; 12703 12704 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12705 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12706 } 12707 12708 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12709 SourceLocation CC) { 12710 unsigned NumArgs = TheCall->getNumArgs(); 12711 for (unsigned i = 0; i < NumArgs; ++i) { 12712 Expr *CurrA = TheCall->getArg(i); 12713 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12714 continue; 12715 12716 bool IsSwapped = ((i > 0) && 12717 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12718 IsSwapped |= ((i < (NumArgs - 1)) && 12719 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12720 if (IsSwapped) { 12721 // Warn on this floating-point to bool conversion. 12722 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12723 CurrA->getType(), CC, 12724 diag::warn_impcast_floating_point_to_bool); 12725 } 12726 } 12727 } 12728 12729 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12730 SourceLocation CC) { 12731 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12732 E->getExprLoc())) 12733 return; 12734 12735 // Don't warn on functions which have return type nullptr_t. 12736 if (isa<CallExpr>(E)) 12737 return; 12738 12739 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12740 const Expr::NullPointerConstantKind NullKind = 12741 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12742 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12743 return; 12744 12745 // Return if target type is a safe conversion. 12746 if (T->isAnyPointerType() || T->isBlockPointerType() || 12747 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12748 return; 12749 12750 SourceLocation Loc = E->getSourceRange().getBegin(); 12751 12752 // Venture through the macro stacks to get to the source of macro arguments. 12753 // The new location is a better location than the complete location that was 12754 // passed in. 12755 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12756 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12757 12758 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12759 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12760 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12761 Loc, S.SourceMgr, S.getLangOpts()); 12762 if (MacroName == "NULL") 12763 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12764 } 12765 12766 // Only warn if the null and context location are in the same macro expansion. 12767 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12768 return; 12769 12770 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12771 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12772 << FixItHint::CreateReplacement(Loc, 12773 S.getFixItZeroLiteralForType(T, Loc)); 12774 } 12775 12776 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12777 ObjCArrayLiteral *ArrayLiteral); 12778 12779 static void 12780 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12781 ObjCDictionaryLiteral *DictionaryLiteral); 12782 12783 /// Check a single element within a collection literal against the 12784 /// target element type. 12785 static void checkObjCCollectionLiteralElement(Sema &S, 12786 QualType TargetElementType, 12787 Expr *Element, 12788 unsigned ElementKind) { 12789 // Skip a bitcast to 'id' or qualified 'id'. 12790 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12791 if (ICE->getCastKind() == CK_BitCast && 12792 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12793 Element = ICE->getSubExpr(); 12794 } 12795 12796 QualType ElementType = Element->getType(); 12797 ExprResult ElementResult(Element); 12798 if (ElementType->getAs<ObjCObjectPointerType>() && 12799 S.CheckSingleAssignmentConstraints(TargetElementType, 12800 ElementResult, 12801 false, false) 12802 != Sema::Compatible) { 12803 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12804 << ElementType << ElementKind << TargetElementType 12805 << Element->getSourceRange(); 12806 } 12807 12808 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12809 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12810 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12811 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12812 } 12813 12814 /// Check an Objective-C array literal being converted to the given 12815 /// target type. 12816 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12817 ObjCArrayLiteral *ArrayLiteral) { 12818 if (!S.NSArrayDecl) 12819 return; 12820 12821 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12822 if (!TargetObjCPtr) 12823 return; 12824 12825 if (TargetObjCPtr->isUnspecialized() || 12826 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12827 != S.NSArrayDecl->getCanonicalDecl()) 12828 return; 12829 12830 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12831 if (TypeArgs.size() != 1) 12832 return; 12833 12834 QualType TargetElementType = TypeArgs[0]; 12835 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12836 checkObjCCollectionLiteralElement(S, TargetElementType, 12837 ArrayLiteral->getElement(I), 12838 0); 12839 } 12840 } 12841 12842 /// Check an Objective-C dictionary literal being converted to the given 12843 /// target type. 12844 static void 12845 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12846 ObjCDictionaryLiteral *DictionaryLiteral) { 12847 if (!S.NSDictionaryDecl) 12848 return; 12849 12850 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12851 if (!TargetObjCPtr) 12852 return; 12853 12854 if (TargetObjCPtr->isUnspecialized() || 12855 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12856 != S.NSDictionaryDecl->getCanonicalDecl()) 12857 return; 12858 12859 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12860 if (TypeArgs.size() != 2) 12861 return; 12862 12863 QualType TargetKeyType = TypeArgs[0]; 12864 QualType TargetObjectType = TypeArgs[1]; 12865 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12866 auto Element = DictionaryLiteral->getKeyValueElement(I); 12867 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12868 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12869 } 12870 } 12871 12872 // Helper function to filter out cases for constant width constant conversion. 12873 // Don't warn on char array initialization or for non-decimal values. 12874 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12875 SourceLocation CC) { 12876 // If initializing from a constant, and the constant starts with '0', 12877 // then it is a binary, octal, or hexadecimal. Allow these constants 12878 // to fill all the bits, even if there is a sign change. 12879 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12880 const char FirstLiteralCharacter = 12881 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12882 if (FirstLiteralCharacter == '0') 12883 return false; 12884 } 12885 12886 // If the CC location points to a '{', and the type is char, then assume 12887 // assume it is an array initialization. 12888 if (CC.isValid() && T->isCharType()) { 12889 const char FirstContextCharacter = 12890 S.getSourceManager().getCharacterData(CC)[0]; 12891 if (FirstContextCharacter == '{') 12892 return false; 12893 } 12894 12895 return true; 12896 } 12897 12898 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12899 const auto *IL = dyn_cast<IntegerLiteral>(E); 12900 if (!IL) { 12901 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12902 if (UO->getOpcode() == UO_Minus) 12903 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12904 } 12905 } 12906 12907 return IL; 12908 } 12909 12910 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12911 E = E->IgnoreParenImpCasts(); 12912 SourceLocation ExprLoc = E->getExprLoc(); 12913 12914 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12915 BinaryOperator::Opcode Opc = BO->getOpcode(); 12916 Expr::EvalResult Result; 12917 // Do not diagnose unsigned shifts. 12918 if (Opc == BO_Shl) { 12919 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12920 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12921 if (LHS && LHS->getValue() == 0) 12922 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12923 else if (!E->isValueDependent() && LHS && RHS && 12924 RHS->getValue().isNonNegative() && 12925 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12926 S.Diag(ExprLoc, diag::warn_left_shift_always) 12927 << (Result.Val.getInt() != 0); 12928 else if (E->getType()->isSignedIntegerType()) 12929 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12930 } 12931 } 12932 12933 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12934 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12935 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12936 if (!LHS || !RHS) 12937 return; 12938 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12939 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12940 // Do not diagnose common idioms. 12941 return; 12942 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12943 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12944 } 12945 } 12946 12947 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12948 SourceLocation CC, 12949 bool *ICContext = nullptr, 12950 bool IsListInit = false) { 12951 if (E->isTypeDependent() || E->isValueDependent()) return; 12952 12953 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12954 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12955 if (Source == Target) return; 12956 if (Target->isDependentType()) return; 12957 12958 // If the conversion context location is invalid don't complain. We also 12959 // don't want to emit a warning if the issue occurs from the expansion of 12960 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12961 // delay this check as long as possible. Once we detect we are in that 12962 // scenario, we just return. 12963 if (CC.isInvalid()) 12964 return; 12965 12966 if (Source->isAtomicType()) 12967 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12968 12969 // Diagnose implicit casts to bool. 12970 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12971 if (isa<StringLiteral>(E)) 12972 // Warn on string literal to bool. Checks for string literals in logical 12973 // and expressions, for instance, assert(0 && "error here"), are 12974 // prevented by a check in AnalyzeImplicitConversions(). 12975 return DiagnoseImpCast(S, E, T, CC, 12976 diag::warn_impcast_string_literal_to_bool); 12977 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12978 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12979 // This covers the literal expressions that evaluate to Objective-C 12980 // objects. 12981 return DiagnoseImpCast(S, E, T, CC, 12982 diag::warn_impcast_objective_c_literal_to_bool); 12983 } 12984 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12985 // Warn on pointer to bool conversion that is always true. 12986 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12987 SourceRange(CC)); 12988 } 12989 } 12990 12991 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12992 // is a typedef for signed char (macOS), then that constant value has to be 1 12993 // or 0. 12994 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12995 Expr::EvalResult Result; 12996 if (E->EvaluateAsInt(Result, S.getASTContext(), 12997 Expr::SE_AllowSideEffects)) { 12998 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12999 adornObjCBoolConversionDiagWithTernaryFixit( 13000 S, E, 13001 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 13002 << toString(Result.Val.getInt(), 10)); 13003 } 13004 return; 13005 } 13006 } 13007 13008 // Check implicit casts from Objective-C collection literals to specialized 13009 // collection types, e.g., NSArray<NSString *> *. 13010 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 13011 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 13012 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 13013 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 13014 13015 // Strip vector types. 13016 if (isa<VectorType>(Source)) { 13017 if (Target->isVLSTBuiltinType() && 13018 (S.Context.areCompatibleSveTypes(QualType(Target, 0), 13019 QualType(Source, 0)) || 13020 S.Context.areLaxCompatibleSveTypes(QualType(Target, 0), 13021 QualType(Source, 0)))) 13022 return; 13023 13024 if (!isa<VectorType>(Target)) { 13025 if (S.SourceMgr.isInSystemMacro(CC)) 13026 return; 13027 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 13028 } 13029 13030 // If the vector cast is cast between two vectors of the same size, it is 13031 // a bitcast, not a conversion. 13032 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 13033 return; 13034 13035 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 13036 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 13037 } 13038 if (auto VecTy = dyn_cast<VectorType>(Target)) 13039 Target = VecTy->getElementType().getTypePtr(); 13040 13041 // Strip complex types. 13042 if (isa<ComplexType>(Source)) { 13043 if (!isa<ComplexType>(Target)) { 13044 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 13045 return; 13046 13047 return DiagnoseImpCast(S, E, T, CC, 13048 S.getLangOpts().CPlusPlus 13049 ? diag::err_impcast_complex_scalar 13050 : diag::warn_impcast_complex_scalar); 13051 } 13052 13053 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 13054 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 13055 } 13056 13057 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 13058 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 13059 13060 // If the source is floating point... 13061 if (SourceBT && SourceBT->isFloatingPoint()) { 13062 // ...and the target is floating point... 13063 if (TargetBT && TargetBT->isFloatingPoint()) { 13064 // ...then warn if we're dropping FP rank. 13065 13066 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 13067 QualType(SourceBT, 0), QualType(TargetBT, 0)); 13068 if (Order > 0) { 13069 // Don't warn about float constants that are precisely 13070 // representable in the target type. 13071 Expr::EvalResult result; 13072 if (E->EvaluateAsRValue(result, S.Context)) { 13073 // Value might be a float, a float vector, or a float complex. 13074 if (IsSameFloatAfterCast(result.Val, 13075 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 13076 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 13077 return; 13078 } 13079 13080 if (S.SourceMgr.isInSystemMacro(CC)) 13081 return; 13082 13083 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 13084 } 13085 // ... or possibly if we're increasing rank, too 13086 else if (Order < 0) { 13087 if (S.SourceMgr.isInSystemMacro(CC)) 13088 return; 13089 13090 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 13091 } 13092 return; 13093 } 13094 13095 // If the target is integral, always warn. 13096 if (TargetBT && TargetBT->isInteger()) { 13097 if (S.SourceMgr.isInSystemMacro(CC)) 13098 return; 13099 13100 DiagnoseFloatingImpCast(S, E, T, CC); 13101 } 13102 13103 // Detect the case where a call result is converted from floating-point to 13104 // to bool, and the final argument to the call is converted from bool, to 13105 // discover this typo: 13106 // 13107 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 13108 // 13109 // FIXME: This is an incredibly special case; is there some more general 13110 // way to detect this class of misplaced-parentheses bug? 13111 if (Target->isBooleanType() && isa<CallExpr>(E)) { 13112 // Check last argument of function call to see if it is an 13113 // implicit cast from a type matching the type the result 13114 // is being cast to. 13115 CallExpr *CEx = cast<CallExpr>(E); 13116 if (unsigned NumArgs = CEx->getNumArgs()) { 13117 Expr *LastA = CEx->getArg(NumArgs - 1); 13118 Expr *InnerE = LastA->IgnoreParenImpCasts(); 13119 if (isa<ImplicitCastExpr>(LastA) && 13120 InnerE->getType()->isBooleanType()) { 13121 // Warn on this floating-point to bool conversion 13122 DiagnoseImpCast(S, E, T, CC, 13123 diag::warn_impcast_floating_point_to_bool); 13124 } 13125 } 13126 } 13127 return; 13128 } 13129 13130 // Valid casts involving fixed point types should be accounted for here. 13131 if (Source->isFixedPointType()) { 13132 if (Target->isUnsaturatedFixedPointType()) { 13133 Expr::EvalResult Result; 13134 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 13135 S.isConstantEvaluated())) { 13136 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 13137 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 13138 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 13139 if (Value > MaxVal || Value < MinVal) { 13140 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13141 S.PDiag(diag::warn_impcast_fixed_point_range) 13142 << Value.toString() << T 13143 << E->getSourceRange() 13144 << clang::SourceRange(CC)); 13145 return; 13146 } 13147 } 13148 } else if (Target->isIntegerType()) { 13149 Expr::EvalResult Result; 13150 if (!S.isConstantEvaluated() && 13151 E->EvaluateAsFixedPoint(Result, S.Context, 13152 Expr::SE_AllowSideEffects)) { 13153 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 13154 13155 bool Overflowed; 13156 llvm::APSInt IntResult = FXResult.convertToInt( 13157 S.Context.getIntWidth(T), 13158 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 13159 13160 if (Overflowed) { 13161 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13162 S.PDiag(diag::warn_impcast_fixed_point_range) 13163 << FXResult.toString() << T 13164 << E->getSourceRange() 13165 << clang::SourceRange(CC)); 13166 return; 13167 } 13168 } 13169 } 13170 } else if (Target->isUnsaturatedFixedPointType()) { 13171 if (Source->isIntegerType()) { 13172 Expr::EvalResult Result; 13173 if (!S.isConstantEvaluated() && 13174 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 13175 llvm::APSInt Value = Result.Val.getInt(); 13176 13177 bool Overflowed; 13178 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 13179 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 13180 13181 if (Overflowed) { 13182 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13183 S.PDiag(diag::warn_impcast_fixed_point_range) 13184 << toString(Value, /*Radix=*/10) << T 13185 << E->getSourceRange() 13186 << clang::SourceRange(CC)); 13187 return; 13188 } 13189 } 13190 } 13191 } 13192 13193 // If we are casting an integer type to a floating point type without 13194 // initialization-list syntax, we might lose accuracy if the floating 13195 // point type has a narrower significand than the integer type. 13196 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 13197 TargetBT->isFloatingType() && !IsListInit) { 13198 // Determine the number of precision bits in the source integer type. 13199 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 13200 /*Approximate*/ true); 13201 unsigned int SourcePrecision = SourceRange.Width; 13202 13203 // Determine the number of precision bits in the 13204 // target floating point type. 13205 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 13206 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13207 13208 if (SourcePrecision > 0 && TargetPrecision > 0 && 13209 SourcePrecision > TargetPrecision) { 13210 13211 if (Optional<llvm::APSInt> SourceInt = 13212 E->getIntegerConstantExpr(S.Context)) { 13213 // If the source integer is a constant, convert it to the target 13214 // floating point type. Issue a warning if the value changes 13215 // during the whole conversion. 13216 llvm::APFloat TargetFloatValue( 13217 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13218 llvm::APFloat::opStatus ConversionStatus = 13219 TargetFloatValue.convertFromAPInt( 13220 *SourceInt, SourceBT->isSignedInteger(), 13221 llvm::APFloat::rmNearestTiesToEven); 13222 13223 if (ConversionStatus != llvm::APFloat::opOK) { 13224 SmallString<32> PrettySourceValue; 13225 SourceInt->toString(PrettySourceValue, 10); 13226 SmallString<32> PrettyTargetValue; 13227 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 13228 13229 S.DiagRuntimeBehavior( 13230 E->getExprLoc(), E, 13231 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 13232 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13233 << E->getSourceRange() << clang::SourceRange(CC)); 13234 } 13235 } else { 13236 // Otherwise, the implicit conversion may lose precision. 13237 DiagnoseImpCast(S, E, T, CC, 13238 diag::warn_impcast_integer_float_precision); 13239 } 13240 } 13241 } 13242 13243 DiagnoseNullConversion(S, E, T, CC); 13244 13245 S.DiscardMisalignedMemberAddress(Target, E); 13246 13247 if (Target->isBooleanType()) 13248 DiagnoseIntInBoolContext(S, E); 13249 13250 if (!Source->isIntegerType() || !Target->isIntegerType()) 13251 return; 13252 13253 // TODO: remove this early return once the false positives for constant->bool 13254 // in templates, macros, etc, are reduced or removed. 13255 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 13256 return; 13257 13258 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 13259 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 13260 return adornObjCBoolConversionDiagWithTernaryFixit( 13261 S, E, 13262 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 13263 << E->getType()); 13264 } 13265 13266 IntRange SourceTypeRange = 13267 IntRange::forTargetOfCanonicalType(S.Context, Source); 13268 IntRange LikelySourceRange = 13269 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 13270 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 13271 13272 if (LikelySourceRange.Width > TargetRange.Width) { 13273 // If the source is a constant, use a default-on diagnostic. 13274 // TODO: this should happen for bitfield stores, too. 13275 Expr::EvalResult Result; 13276 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 13277 S.isConstantEvaluated())) { 13278 llvm::APSInt Value(32); 13279 Value = Result.Val.getInt(); 13280 13281 if (S.SourceMgr.isInSystemMacro(CC)) 13282 return; 13283 13284 std::string PrettySourceValue = toString(Value, 10); 13285 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13286 13287 S.DiagRuntimeBehavior( 13288 E->getExprLoc(), E, 13289 S.PDiag(diag::warn_impcast_integer_precision_constant) 13290 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13291 << E->getSourceRange() << SourceRange(CC)); 13292 return; 13293 } 13294 13295 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 13296 if (S.SourceMgr.isInSystemMacro(CC)) 13297 return; 13298 13299 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 13300 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 13301 /* pruneControlFlow */ true); 13302 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 13303 } 13304 13305 if (TargetRange.Width > SourceTypeRange.Width) { 13306 if (auto *UO = dyn_cast<UnaryOperator>(E)) 13307 if (UO->getOpcode() == UO_Minus) 13308 if (Source->isUnsignedIntegerType()) { 13309 if (Target->isUnsignedIntegerType()) 13310 return DiagnoseImpCast(S, E, T, CC, 13311 diag::warn_impcast_high_order_zero_bits); 13312 if (Target->isSignedIntegerType()) 13313 return DiagnoseImpCast(S, E, T, CC, 13314 diag::warn_impcast_nonnegative_result); 13315 } 13316 } 13317 13318 if (TargetRange.Width == LikelySourceRange.Width && 13319 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 13320 Source->isSignedIntegerType()) { 13321 // Warn when doing a signed to signed conversion, warn if the positive 13322 // source value is exactly the width of the target type, which will 13323 // cause a negative value to be stored. 13324 13325 Expr::EvalResult Result; 13326 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 13327 !S.SourceMgr.isInSystemMacro(CC)) { 13328 llvm::APSInt Value = Result.Val.getInt(); 13329 if (isSameWidthConstantConversion(S, E, T, CC)) { 13330 std::string PrettySourceValue = toString(Value, 10); 13331 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13332 13333 S.DiagRuntimeBehavior( 13334 E->getExprLoc(), E, 13335 S.PDiag(diag::warn_impcast_integer_precision_constant) 13336 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13337 << E->getSourceRange() << SourceRange(CC)); 13338 return; 13339 } 13340 } 13341 13342 // Fall through for non-constants to give a sign conversion warning. 13343 } 13344 13345 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 13346 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 13347 LikelySourceRange.Width == TargetRange.Width)) { 13348 if (S.SourceMgr.isInSystemMacro(CC)) 13349 return; 13350 13351 unsigned DiagID = diag::warn_impcast_integer_sign; 13352 13353 // Traditionally, gcc has warned about this under -Wsign-compare. 13354 // We also want to warn about it in -Wconversion. 13355 // So if -Wconversion is off, use a completely identical diagnostic 13356 // in the sign-compare group. 13357 // The conditional-checking code will 13358 if (ICContext) { 13359 DiagID = diag::warn_impcast_integer_sign_conditional; 13360 *ICContext = true; 13361 } 13362 13363 return DiagnoseImpCast(S, E, T, CC, DiagID); 13364 } 13365 13366 // Diagnose conversions between different enumeration types. 13367 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 13368 // type, to give us better diagnostics. 13369 QualType SourceType = E->getType(); 13370 if (!S.getLangOpts().CPlusPlus) { 13371 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13372 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 13373 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 13374 SourceType = S.Context.getTypeDeclType(Enum); 13375 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 13376 } 13377 } 13378 13379 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 13380 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 13381 if (SourceEnum->getDecl()->hasNameForLinkage() && 13382 TargetEnum->getDecl()->hasNameForLinkage() && 13383 SourceEnum != TargetEnum) { 13384 if (S.SourceMgr.isInSystemMacro(CC)) 13385 return; 13386 13387 return DiagnoseImpCast(S, E, SourceType, T, CC, 13388 diag::warn_impcast_different_enum_types); 13389 } 13390 } 13391 13392 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13393 SourceLocation CC, QualType T); 13394 13395 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 13396 SourceLocation CC, bool &ICContext) { 13397 E = E->IgnoreParenImpCasts(); 13398 13399 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 13400 return CheckConditionalOperator(S, CO, CC, T); 13401 13402 AnalyzeImplicitConversions(S, E, CC); 13403 if (E->getType() != T) 13404 return CheckImplicitConversion(S, E, T, CC, &ICContext); 13405 } 13406 13407 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13408 SourceLocation CC, QualType T) { 13409 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 13410 13411 Expr *TrueExpr = E->getTrueExpr(); 13412 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 13413 TrueExpr = BCO->getCommon(); 13414 13415 bool Suspicious = false; 13416 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 13417 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 13418 13419 if (T->isBooleanType()) 13420 DiagnoseIntInBoolContext(S, E); 13421 13422 // If -Wconversion would have warned about either of the candidates 13423 // for a signedness conversion to the context type... 13424 if (!Suspicious) return; 13425 13426 // ...but it's currently ignored... 13427 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 13428 return; 13429 13430 // ...then check whether it would have warned about either of the 13431 // candidates for a signedness conversion to the condition type. 13432 if (E->getType() == T) return; 13433 13434 Suspicious = false; 13435 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 13436 E->getType(), CC, &Suspicious); 13437 if (!Suspicious) 13438 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 13439 E->getType(), CC, &Suspicious); 13440 } 13441 13442 /// Check conversion of given expression to boolean. 13443 /// Input argument E is a logical expression. 13444 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 13445 if (S.getLangOpts().Bool) 13446 return; 13447 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 13448 return; 13449 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 13450 } 13451 13452 namespace { 13453 struct AnalyzeImplicitConversionsWorkItem { 13454 Expr *E; 13455 SourceLocation CC; 13456 bool IsListInit; 13457 }; 13458 } 13459 13460 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 13461 /// that should be visited are added to WorkList. 13462 static void AnalyzeImplicitConversions( 13463 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 13464 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 13465 Expr *OrigE = Item.E; 13466 SourceLocation CC = Item.CC; 13467 13468 QualType T = OrigE->getType(); 13469 Expr *E = OrigE->IgnoreParenImpCasts(); 13470 13471 // Propagate whether we are in a C++ list initialization expression. 13472 // If so, we do not issue warnings for implicit int-float conversion 13473 // precision loss, because C++11 narrowing already handles it. 13474 bool IsListInit = Item.IsListInit || 13475 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 13476 13477 if (E->isTypeDependent() || E->isValueDependent()) 13478 return; 13479 13480 Expr *SourceExpr = E; 13481 // Examine, but don't traverse into the source expression of an 13482 // OpaqueValueExpr, since it may have multiple parents and we don't want to 13483 // emit duplicate diagnostics. Its fine to examine the form or attempt to 13484 // evaluate it in the context of checking the specific conversion to T though. 13485 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 13486 if (auto *Src = OVE->getSourceExpr()) 13487 SourceExpr = Src; 13488 13489 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 13490 if (UO->getOpcode() == UO_Not && 13491 UO->getSubExpr()->isKnownToHaveBooleanValue()) 13492 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 13493 << OrigE->getSourceRange() << T->isBooleanType() 13494 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 13495 13496 if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) 13497 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) && 13498 BO->getLHS()->isKnownToHaveBooleanValue() && 13499 BO->getRHS()->isKnownToHaveBooleanValue() && 13500 BO->getLHS()->HasSideEffects(S.Context) && 13501 BO->getRHS()->HasSideEffects(S.Context)) { 13502 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical) 13503 << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange() 13504 << FixItHint::CreateReplacement( 13505 BO->getOperatorLoc(), 13506 (BO->getOpcode() == BO_And ? "&&" : "||")); 13507 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int); 13508 } 13509 13510 // For conditional operators, we analyze the arguments as if they 13511 // were being fed directly into the output. 13512 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 13513 CheckConditionalOperator(S, CO, CC, T); 13514 return; 13515 } 13516 13517 // Check implicit argument conversions for function calls. 13518 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 13519 CheckImplicitArgumentConversions(S, Call, CC); 13520 13521 // Go ahead and check any implicit conversions we might have skipped. 13522 // The non-canonical typecheck is just an optimization; 13523 // CheckImplicitConversion will filter out dead implicit conversions. 13524 if (SourceExpr->getType() != T) 13525 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 13526 13527 // Now continue drilling into this expression. 13528 13529 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 13530 // The bound subexpressions in a PseudoObjectExpr are not reachable 13531 // as transitive children. 13532 // FIXME: Use a more uniform representation for this. 13533 for (auto *SE : POE->semantics()) 13534 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 13535 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 13536 } 13537 13538 // Skip past explicit casts. 13539 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 13540 E = CE->getSubExpr()->IgnoreParenImpCasts(); 13541 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 13542 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 13543 WorkList.push_back({E, CC, IsListInit}); 13544 return; 13545 } 13546 13547 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13548 // Do a somewhat different check with comparison operators. 13549 if (BO->isComparisonOp()) 13550 return AnalyzeComparison(S, BO); 13551 13552 // And with simple assignments. 13553 if (BO->getOpcode() == BO_Assign) 13554 return AnalyzeAssignment(S, BO); 13555 // And with compound assignments. 13556 if (BO->isAssignmentOp()) 13557 return AnalyzeCompoundAssignment(S, BO); 13558 } 13559 13560 // These break the otherwise-useful invariant below. Fortunately, 13561 // we don't really need to recurse into them, because any internal 13562 // expressions should have been analyzed already when they were 13563 // built into statements. 13564 if (isa<StmtExpr>(E)) return; 13565 13566 // Don't descend into unevaluated contexts. 13567 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 13568 13569 // Now just recurse over the expression's children. 13570 CC = E->getExprLoc(); 13571 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 13572 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 13573 for (Stmt *SubStmt : E->children()) { 13574 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 13575 if (!ChildExpr) 13576 continue; 13577 13578 if (IsLogicalAndOperator && 13579 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 13580 // Ignore checking string literals that are in logical and operators. 13581 // This is a common pattern for asserts. 13582 continue; 13583 WorkList.push_back({ChildExpr, CC, IsListInit}); 13584 } 13585 13586 if (BO && BO->isLogicalOp()) { 13587 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 13588 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13589 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13590 13591 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 13592 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13593 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13594 } 13595 13596 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 13597 if (U->getOpcode() == UO_LNot) { 13598 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 13599 } else if (U->getOpcode() != UO_AddrOf) { 13600 if (U->getSubExpr()->getType()->isAtomicType()) 13601 S.Diag(U->getSubExpr()->getBeginLoc(), 13602 diag::warn_atomic_implicit_seq_cst); 13603 } 13604 } 13605 } 13606 13607 /// AnalyzeImplicitConversions - Find and report any interesting 13608 /// implicit conversions in the given expression. There are a couple 13609 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 13610 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 13611 bool IsListInit/*= false*/) { 13612 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 13613 WorkList.push_back({OrigE, CC, IsListInit}); 13614 while (!WorkList.empty()) 13615 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 13616 } 13617 13618 /// Diagnose integer type and any valid implicit conversion to it. 13619 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 13620 // Taking into account implicit conversions, 13621 // allow any integer. 13622 if (!E->getType()->isIntegerType()) { 13623 S.Diag(E->getBeginLoc(), 13624 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 13625 return true; 13626 } 13627 // Potentially emit standard warnings for implicit conversions if enabled 13628 // using -Wconversion. 13629 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 13630 return false; 13631 } 13632 13633 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 13634 // Returns true when emitting a warning about taking the address of a reference. 13635 static bool CheckForReference(Sema &SemaRef, const Expr *E, 13636 const PartialDiagnostic &PD) { 13637 E = E->IgnoreParenImpCasts(); 13638 13639 const FunctionDecl *FD = nullptr; 13640 13641 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13642 if (!DRE->getDecl()->getType()->isReferenceType()) 13643 return false; 13644 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13645 if (!M->getMemberDecl()->getType()->isReferenceType()) 13646 return false; 13647 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 13648 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 13649 return false; 13650 FD = Call->getDirectCallee(); 13651 } else { 13652 return false; 13653 } 13654 13655 SemaRef.Diag(E->getExprLoc(), PD); 13656 13657 // If possible, point to location of function. 13658 if (FD) { 13659 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 13660 } 13661 13662 return true; 13663 } 13664 13665 // Returns true if the SourceLocation is expanded from any macro body. 13666 // Returns false if the SourceLocation is invalid, is from not in a macro 13667 // expansion, or is from expanded from a top-level macro argument. 13668 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 13669 if (Loc.isInvalid()) 13670 return false; 13671 13672 while (Loc.isMacroID()) { 13673 if (SM.isMacroBodyExpansion(Loc)) 13674 return true; 13675 Loc = SM.getImmediateMacroCallerLoc(Loc); 13676 } 13677 13678 return false; 13679 } 13680 13681 /// Diagnose pointers that are always non-null. 13682 /// \param E the expression containing the pointer 13683 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 13684 /// compared to a null pointer 13685 /// \param IsEqual True when the comparison is equal to a null pointer 13686 /// \param Range Extra SourceRange to highlight in the diagnostic 13687 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 13688 Expr::NullPointerConstantKind NullKind, 13689 bool IsEqual, SourceRange Range) { 13690 if (!E) 13691 return; 13692 13693 // Don't warn inside macros. 13694 if (E->getExprLoc().isMacroID()) { 13695 const SourceManager &SM = getSourceManager(); 13696 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 13697 IsInAnyMacroBody(SM, Range.getBegin())) 13698 return; 13699 } 13700 E = E->IgnoreImpCasts(); 13701 13702 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 13703 13704 if (isa<CXXThisExpr>(E)) { 13705 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13706 : diag::warn_this_bool_conversion; 13707 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13708 return; 13709 } 13710 13711 bool IsAddressOf = false; 13712 13713 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13714 if (UO->getOpcode() != UO_AddrOf) 13715 return; 13716 IsAddressOf = true; 13717 E = UO->getSubExpr(); 13718 } 13719 13720 if (IsAddressOf) { 13721 unsigned DiagID = IsCompare 13722 ? diag::warn_address_of_reference_null_compare 13723 : diag::warn_address_of_reference_bool_conversion; 13724 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13725 << IsEqual; 13726 if (CheckForReference(*this, E, PD)) { 13727 return; 13728 } 13729 } 13730 13731 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13732 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13733 std::string Str; 13734 llvm::raw_string_ostream S(Str); 13735 E->printPretty(S, nullptr, getPrintingPolicy()); 13736 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13737 : diag::warn_cast_nonnull_to_bool; 13738 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13739 << E->getSourceRange() << Range << IsEqual; 13740 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13741 }; 13742 13743 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13744 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13745 if (auto *Callee = Call->getDirectCallee()) { 13746 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13747 ComplainAboutNonnullParamOrCall(A); 13748 return; 13749 } 13750 } 13751 } 13752 13753 // Expect to find a single Decl. Skip anything more complicated. 13754 ValueDecl *D = nullptr; 13755 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13756 D = R->getDecl(); 13757 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13758 D = M->getMemberDecl(); 13759 } 13760 13761 // Weak Decls can be null. 13762 if (!D || D->isWeak()) 13763 return; 13764 13765 // Check for parameter decl with nonnull attribute 13766 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13767 if (getCurFunction() && 13768 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13769 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13770 ComplainAboutNonnullParamOrCall(A); 13771 return; 13772 } 13773 13774 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13775 // Skip function template not specialized yet. 13776 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13777 return; 13778 auto ParamIter = llvm::find(FD->parameters(), PV); 13779 assert(ParamIter != FD->param_end()); 13780 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13781 13782 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13783 if (!NonNull->args_size()) { 13784 ComplainAboutNonnullParamOrCall(NonNull); 13785 return; 13786 } 13787 13788 for (const ParamIdx &ArgNo : NonNull->args()) { 13789 if (ArgNo.getASTIndex() == ParamNo) { 13790 ComplainAboutNonnullParamOrCall(NonNull); 13791 return; 13792 } 13793 } 13794 } 13795 } 13796 } 13797 } 13798 13799 QualType T = D->getType(); 13800 const bool IsArray = T->isArrayType(); 13801 const bool IsFunction = T->isFunctionType(); 13802 13803 // Address of function is used to silence the function warning. 13804 if (IsAddressOf && IsFunction) { 13805 return; 13806 } 13807 13808 // Found nothing. 13809 if (!IsAddressOf && !IsFunction && !IsArray) 13810 return; 13811 13812 // Pretty print the expression for the diagnostic. 13813 std::string Str; 13814 llvm::raw_string_ostream S(Str); 13815 E->printPretty(S, nullptr, getPrintingPolicy()); 13816 13817 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13818 : diag::warn_impcast_pointer_to_bool; 13819 enum { 13820 AddressOf, 13821 FunctionPointer, 13822 ArrayPointer 13823 } DiagType; 13824 if (IsAddressOf) 13825 DiagType = AddressOf; 13826 else if (IsFunction) 13827 DiagType = FunctionPointer; 13828 else if (IsArray) 13829 DiagType = ArrayPointer; 13830 else 13831 llvm_unreachable("Could not determine diagnostic."); 13832 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13833 << Range << IsEqual; 13834 13835 if (!IsFunction) 13836 return; 13837 13838 // Suggest '&' to silence the function warning. 13839 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13840 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13841 13842 // Check to see if '()' fixit should be emitted. 13843 QualType ReturnType; 13844 UnresolvedSet<4> NonTemplateOverloads; 13845 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13846 if (ReturnType.isNull()) 13847 return; 13848 13849 if (IsCompare) { 13850 // There are two cases here. If there is null constant, the only suggest 13851 // for a pointer return type. If the null is 0, then suggest if the return 13852 // type is a pointer or an integer type. 13853 if (!ReturnType->isPointerType()) { 13854 if (NullKind == Expr::NPCK_ZeroExpression || 13855 NullKind == Expr::NPCK_ZeroLiteral) { 13856 if (!ReturnType->isIntegerType()) 13857 return; 13858 } else { 13859 return; 13860 } 13861 } 13862 } else { // !IsCompare 13863 // For function to bool, only suggest if the function pointer has bool 13864 // return type. 13865 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13866 return; 13867 } 13868 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13869 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13870 } 13871 13872 /// Diagnoses "dangerous" implicit conversions within the given 13873 /// expression (which is a full expression). Implements -Wconversion 13874 /// and -Wsign-compare. 13875 /// 13876 /// \param CC the "context" location of the implicit conversion, i.e. 13877 /// the most location of the syntactic entity requiring the implicit 13878 /// conversion 13879 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13880 // Don't diagnose in unevaluated contexts. 13881 if (isUnevaluatedContext()) 13882 return; 13883 13884 // Don't diagnose for value- or type-dependent expressions. 13885 if (E->isTypeDependent() || E->isValueDependent()) 13886 return; 13887 13888 // Check for array bounds violations in cases where the check isn't triggered 13889 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13890 // ArraySubscriptExpr is on the RHS of a variable initialization. 13891 CheckArrayAccess(E); 13892 13893 // This is not the right CC for (e.g.) a variable initialization. 13894 AnalyzeImplicitConversions(*this, E, CC); 13895 } 13896 13897 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13898 /// Input argument E is a logical expression. 13899 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13900 ::CheckBoolLikeConversion(*this, E, CC); 13901 } 13902 13903 /// Diagnose when expression is an integer constant expression and its evaluation 13904 /// results in integer overflow 13905 void Sema::CheckForIntOverflow (Expr *E) { 13906 // Use a work list to deal with nested struct initializers. 13907 SmallVector<Expr *, 2> Exprs(1, E); 13908 13909 do { 13910 Expr *OriginalE = Exprs.pop_back_val(); 13911 Expr *E = OriginalE->IgnoreParenCasts(); 13912 13913 if (isa<BinaryOperator>(E)) { 13914 E->EvaluateForOverflow(Context); 13915 continue; 13916 } 13917 13918 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13919 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13920 else if (isa<ObjCBoxedExpr>(OriginalE)) 13921 E->EvaluateForOverflow(Context); 13922 else if (auto Call = dyn_cast<CallExpr>(E)) 13923 Exprs.append(Call->arg_begin(), Call->arg_end()); 13924 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13925 Exprs.append(Message->arg_begin(), Message->arg_end()); 13926 } while (!Exprs.empty()); 13927 } 13928 13929 namespace { 13930 13931 /// Visitor for expressions which looks for unsequenced operations on the 13932 /// same object. 13933 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13934 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13935 13936 /// A tree of sequenced regions within an expression. Two regions are 13937 /// unsequenced if one is an ancestor or a descendent of the other. When we 13938 /// finish processing an expression with sequencing, such as a comma 13939 /// expression, we fold its tree nodes into its parent, since they are 13940 /// unsequenced with respect to nodes we will visit later. 13941 class SequenceTree { 13942 struct Value { 13943 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13944 unsigned Parent : 31; 13945 unsigned Merged : 1; 13946 }; 13947 SmallVector<Value, 8> Values; 13948 13949 public: 13950 /// A region within an expression which may be sequenced with respect 13951 /// to some other region. 13952 class Seq { 13953 friend class SequenceTree; 13954 13955 unsigned Index; 13956 13957 explicit Seq(unsigned N) : Index(N) {} 13958 13959 public: 13960 Seq() : Index(0) {} 13961 }; 13962 13963 SequenceTree() { Values.push_back(Value(0)); } 13964 Seq root() const { return Seq(0); } 13965 13966 /// Create a new sequence of operations, which is an unsequenced 13967 /// subset of \p Parent. This sequence of operations is sequenced with 13968 /// respect to other children of \p Parent. 13969 Seq allocate(Seq Parent) { 13970 Values.push_back(Value(Parent.Index)); 13971 return Seq(Values.size() - 1); 13972 } 13973 13974 /// Merge a sequence of operations into its parent. 13975 void merge(Seq S) { 13976 Values[S.Index].Merged = true; 13977 } 13978 13979 /// Determine whether two operations are unsequenced. This operation 13980 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13981 /// should have been merged into its parent as appropriate. 13982 bool isUnsequenced(Seq Cur, Seq Old) { 13983 unsigned C = representative(Cur.Index); 13984 unsigned Target = representative(Old.Index); 13985 while (C >= Target) { 13986 if (C == Target) 13987 return true; 13988 C = Values[C].Parent; 13989 } 13990 return false; 13991 } 13992 13993 private: 13994 /// Pick a representative for a sequence. 13995 unsigned representative(unsigned K) { 13996 if (Values[K].Merged) 13997 // Perform path compression as we go. 13998 return Values[K].Parent = representative(Values[K].Parent); 13999 return K; 14000 } 14001 }; 14002 14003 /// An object for which we can track unsequenced uses. 14004 using Object = const NamedDecl *; 14005 14006 /// Different flavors of object usage which we track. We only track the 14007 /// least-sequenced usage of each kind. 14008 enum UsageKind { 14009 /// A read of an object. Multiple unsequenced reads are OK. 14010 UK_Use, 14011 14012 /// A modification of an object which is sequenced before the value 14013 /// computation of the expression, such as ++n in C++. 14014 UK_ModAsValue, 14015 14016 /// A modification of an object which is not sequenced before the value 14017 /// computation of the expression, such as n++. 14018 UK_ModAsSideEffect, 14019 14020 UK_Count = UK_ModAsSideEffect + 1 14021 }; 14022 14023 /// Bundle together a sequencing region and the expression corresponding 14024 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 14025 struct Usage { 14026 const Expr *UsageExpr; 14027 SequenceTree::Seq Seq; 14028 14029 Usage() : UsageExpr(nullptr) {} 14030 }; 14031 14032 struct UsageInfo { 14033 Usage Uses[UK_Count]; 14034 14035 /// Have we issued a diagnostic for this object already? 14036 bool Diagnosed; 14037 14038 UsageInfo() : Diagnosed(false) {} 14039 }; 14040 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 14041 14042 Sema &SemaRef; 14043 14044 /// Sequenced regions within the expression. 14045 SequenceTree Tree; 14046 14047 /// Declaration modifications and references which we have seen. 14048 UsageInfoMap UsageMap; 14049 14050 /// The region we are currently within. 14051 SequenceTree::Seq Region; 14052 14053 /// Filled in with declarations which were modified as a side-effect 14054 /// (that is, post-increment operations). 14055 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 14056 14057 /// Expressions to check later. We defer checking these to reduce 14058 /// stack usage. 14059 SmallVectorImpl<const Expr *> &WorkList; 14060 14061 /// RAII object wrapping the visitation of a sequenced subexpression of an 14062 /// expression. At the end of this process, the side-effects of the evaluation 14063 /// become sequenced with respect to the value computation of the result, so 14064 /// we downgrade any UK_ModAsSideEffect within the evaluation to 14065 /// UK_ModAsValue. 14066 struct SequencedSubexpression { 14067 SequencedSubexpression(SequenceChecker &Self) 14068 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 14069 Self.ModAsSideEffect = &ModAsSideEffect; 14070 } 14071 14072 ~SequencedSubexpression() { 14073 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 14074 // Add a new usage with usage kind UK_ModAsValue, and then restore 14075 // the previous usage with UK_ModAsSideEffect (thus clearing it if 14076 // the previous one was empty). 14077 UsageInfo &UI = Self.UsageMap[M.first]; 14078 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 14079 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 14080 SideEffectUsage = M.second; 14081 } 14082 Self.ModAsSideEffect = OldModAsSideEffect; 14083 } 14084 14085 SequenceChecker &Self; 14086 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 14087 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 14088 }; 14089 14090 /// RAII object wrapping the visitation of a subexpression which we might 14091 /// choose to evaluate as a constant. If any subexpression is evaluated and 14092 /// found to be non-constant, this allows us to suppress the evaluation of 14093 /// the outer expression. 14094 class EvaluationTracker { 14095 public: 14096 EvaluationTracker(SequenceChecker &Self) 14097 : Self(Self), Prev(Self.EvalTracker) { 14098 Self.EvalTracker = this; 14099 } 14100 14101 ~EvaluationTracker() { 14102 Self.EvalTracker = Prev; 14103 if (Prev) 14104 Prev->EvalOK &= EvalOK; 14105 } 14106 14107 bool evaluate(const Expr *E, bool &Result) { 14108 if (!EvalOK || E->isValueDependent()) 14109 return false; 14110 EvalOK = E->EvaluateAsBooleanCondition( 14111 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 14112 return EvalOK; 14113 } 14114 14115 private: 14116 SequenceChecker &Self; 14117 EvaluationTracker *Prev; 14118 bool EvalOK = true; 14119 } *EvalTracker = nullptr; 14120 14121 /// Find the object which is produced by the specified expression, 14122 /// if any. 14123 Object getObject(const Expr *E, bool Mod) const { 14124 E = E->IgnoreParenCasts(); 14125 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 14126 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 14127 return getObject(UO->getSubExpr(), Mod); 14128 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 14129 if (BO->getOpcode() == BO_Comma) 14130 return getObject(BO->getRHS(), Mod); 14131 if (Mod && BO->isAssignmentOp()) 14132 return getObject(BO->getLHS(), Mod); 14133 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14134 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 14135 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 14136 return ME->getMemberDecl(); 14137 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 14138 // FIXME: If this is a reference, map through to its value. 14139 return DRE->getDecl(); 14140 return nullptr; 14141 } 14142 14143 /// Note that an object \p O was modified or used by an expression 14144 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 14145 /// the object \p O as obtained via the \p UsageMap. 14146 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 14147 // Get the old usage for the given object and usage kind. 14148 Usage &U = UI.Uses[UK]; 14149 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 14150 // If we have a modification as side effect and are in a sequenced 14151 // subexpression, save the old Usage so that we can restore it later 14152 // in SequencedSubexpression::~SequencedSubexpression. 14153 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 14154 ModAsSideEffect->push_back(std::make_pair(O, U)); 14155 // Then record the new usage with the current sequencing region. 14156 U.UsageExpr = UsageExpr; 14157 U.Seq = Region; 14158 } 14159 } 14160 14161 /// Check whether a modification or use of an object \p O in an expression 14162 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 14163 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 14164 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 14165 /// usage and false we are checking for a mod-use unsequenced usage. 14166 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 14167 UsageKind OtherKind, bool IsModMod) { 14168 if (UI.Diagnosed) 14169 return; 14170 14171 const Usage &U = UI.Uses[OtherKind]; 14172 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 14173 return; 14174 14175 const Expr *Mod = U.UsageExpr; 14176 const Expr *ModOrUse = UsageExpr; 14177 if (OtherKind == UK_Use) 14178 std::swap(Mod, ModOrUse); 14179 14180 SemaRef.DiagRuntimeBehavior( 14181 Mod->getExprLoc(), {Mod, ModOrUse}, 14182 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 14183 : diag::warn_unsequenced_mod_use) 14184 << O << SourceRange(ModOrUse->getExprLoc())); 14185 UI.Diagnosed = true; 14186 } 14187 14188 // A note on note{Pre, Post}{Use, Mod}: 14189 // 14190 // (It helps to follow the algorithm with an expression such as 14191 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 14192 // operations before C++17 and both are well-defined in C++17). 14193 // 14194 // When visiting a node which uses/modify an object we first call notePreUse 14195 // or notePreMod before visiting its sub-expression(s). At this point the 14196 // children of the current node have not yet been visited and so the eventual 14197 // uses/modifications resulting from the children of the current node have not 14198 // been recorded yet. 14199 // 14200 // We then visit the children of the current node. After that notePostUse or 14201 // notePostMod is called. These will 1) detect an unsequenced modification 14202 // as side effect (as in "k++ + k") and 2) add a new usage with the 14203 // appropriate usage kind. 14204 // 14205 // We also have to be careful that some operation sequences modification as 14206 // side effect as well (for example: || or ,). To account for this we wrap 14207 // the visitation of such a sub-expression (for example: the LHS of || or ,) 14208 // with SequencedSubexpression. SequencedSubexpression is an RAII object 14209 // which record usages which are modifications as side effect, and then 14210 // downgrade them (or more accurately restore the previous usage which was a 14211 // modification as side effect) when exiting the scope of the sequenced 14212 // subexpression. 14213 14214 void notePreUse(Object O, const Expr *UseExpr) { 14215 UsageInfo &UI = UsageMap[O]; 14216 // Uses conflict with other modifications. 14217 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 14218 } 14219 14220 void notePostUse(Object O, const Expr *UseExpr) { 14221 UsageInfo &UI = UsageMap[O]; 14222 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 14223 /*IsModMod=*/false); 14224 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 14225 } 14226 14227 void notePreMod(Object O, const Expr *ModExpr) { 14228 UsageInfo &UI = UsageMap[O]; 14229 // Modifications conflict with other modifications and with uses. 14230 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 14231 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 14232 } 14233 14234 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 14235 UsageInfo &UI = UsageMap[O]; 14236 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 14237 /*IsModMod=*/true); 14238 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 14239 } 14240 14241 public: 14242 SequenceChecker(Sema &S, const Expr *E, 14243 SmallVectorImpl<const Expr *> &WorkList) 14244 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 14245 Visit(E); 14246 // Silence a -Wunused-private-field since WorkList is now unused. 14247 // TODO: Evaluate if it can be used, and if not remove it. 14248 (void)this->WorkList; 14249 } 14250 14251 void VisitStmt(const Stmt *S) { 14252 // Skip all statements which aren't expressions for now. 14253 } 14254 14255 void VisitExpr(const Expr *E) { 14256 // By default, just recurse to evaluated subexpressions. 14257 Base::VisitStmt(E); 14258 } 14259 14260 void VisitCastExpr(const CastExpr *E) { 14261 Object O = Object(); 14262 if (E->getCastKind() == CK_LValueToRValue) 14263 O = getObject(E->getSubExpr(), false); 14264 14265 if (O) 14266 notePreUse(O, E); 14267 VisitExpr(E); 14268 if (O) 14269 notePostUse(O, E); 14270 } 14271 14272 void VisitSequencedExpressions(const Expr *SequencedBefore, 14273 const Expr *SequencedAfter) { 14274 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 14275 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 14276 SequenceTree::Seq OldRegion = Region; 14277 14278 { 14279 SequencedSubexpression SeqBefore(*this); 14280 Region = BeforeRegion; 14281 Visit(SequencedBefore); 14282 } 14283 14284 Region = AfterRegion; 14285 Visit(SequencedAfter); 14286 14287 Region = OldRegion; 14288 14289 Tree.merge(BeforeRegion); 14290 Tree.merge(AfterRegion); 14291 } 14292 14293 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 14294 // C++17 [expr.sub]p1: 14295 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 14296 // expression E1 is sequenced before the expression E2. 14297 if (SemaRef.getLangOpts().CPlusPlus17) 14298 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 14299 else { 14300 Visit(ASE->getLHS()); 14301 Visit(ASE->getRHS()); 14302 } 14303 } 14304 14305 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14306 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14307 void VisitBinPtrMem(const BinaryOperator *BO) { 14308 // C++17 [expr.mptr.oper]p4: 14309 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 14310 // the expression E1 is sequenced before the expression E2. 14311 if (SemaRef.getLangOpts().CPlusPlus17) 14312 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14313 else { 14314 Visit(BO->getLHS()); 14315 Visit(BO->getRHS()); 14316 } 14317 } 14318 14319 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14320 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14321 void VisitBinShlShr(const BinaryOperator *BO) { 14322 // C++17 [expr.shift]p4: 14323 // The expression E1 is sequenced before the expression E2. 14324 if (SemaRef.getLangOpts().CPlusPlus17) 14325 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14326 else { 14327 Visit(BO->getLHS()); 14328 Visit(BO->getRHS()); 14329 } 14330 } 14331 14332 void VisitBinComma(const BinaryOperator *BO) { 14333 // C++11 [expr.comma]p1: 14334 // Every value computation and side effect associated with the left 14335 // expression is sequenced before every value computation and side 14336 // effect associated with the right expression. 14337 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14338 } 14339 14340 void VisitBinAssign(const BinaryOperator *BO) { 14341 SequenceTree::Seq RHSRegion; 14342 SequenceTree::Seq LHSRegion; 14343 if (SemaRef.getLangOpts().CPlusPlus17) { 14344 RHSRegion = Tree.allocate(Region); 14345 LHSRegion = Tree.allocate(Region); 14346 } else { 14347 RHSRegion = Region; 14348 LHSRegion = Region; 14349 } 14350 SequenceTree::Seq OldRegion = Region; 14351 14352 // C++11 [expr.ass]p1: 14353 // [...] the assignment is sequenced after the value computation 14354 // of the right and left operands, [...] 14355 // 14356 // so check it before inspecting the operands and update the 14357 // map afterwards. 14358 Object O = getObject(BO->getLHS(), /*Mod=*/true); 14359 if (O) 14360 notePreMod(O, BO); 14361 14362 if (SemaRef.getLangOpts().CPlusPlus17) { 14363 // C++17 [expr.ass]p1: 14364 // [...] The right operand is sequenced before the left operand. [...] 14365 { 14366 SequencedSubexpression SeqBefore(*this); 14367 Region = RHSRegion; 14368 Visit(BO->getRHS()); 14369 } 14370 14371 Region = LHSRegion; 14372 Visit(BO->getLHS()); 14373 14374 if (O && isa<CompoundAssignOperator>(BO)) 14375 notePostUse(O, BO); 14376 14377 } else { 14378 // C++11 does not specify any sequencing between the LHS and RHS. 14379 Region = LHSRegion; 14380 Visit(BO->getLHS()); 14381 14382 if (O && isa<CompoundAssignOperator>(BO)) 14383 notePostUse(O, BO); 14384 14385 Region = RHSRegion; 14386 Visit(BO->getRHS()); 14387 } 14388 14389 // C++11 [expr.ass]p1: 14390 // the assignment is sequenced [...] before the value computation of the 14391 // assignment expression. 14392 // C11 6.5.16/3 has no such rule. 14393 Region = OldRegion; 14394 if (O) 14395 notePostMod(O, BO, 14396 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14397 : UK_ModAsSideEffect); 14398 if (SemaRef.getLangOpts().CPlusPlus17) { 14399 Tree.merge(RHSRegion); 14400 Tree.merge(LHSRegion); 14401 } 14402 } 14403 14404 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 14405 VisitBinAssign(CAO); 14406 } 14407 14408 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14409 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14410 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 14411 Object O = getObject(UO->getSubExpr(), true); 14412 if (!O) 14413 return VisitExpr(UO); 14414 14415 notePreMod(O, UO); 14416 Visit(UO->getSubExpr()); 14417 // C++11 [expr.pre.incr]p1: 14418 // the expression ++x is equivalent to x+=1 14419 notePostMod(O, UO, 14420 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14421 : UK_ModAsSideEffect); 14422 } 14423 14424 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14425 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14426 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 14427 Object O = getObject(UO->getSubExpr(), true); 14428 if (!O) 14429 return VisitExpr(UO); 14430 14431 notePreMod(O, UO); 14432 Visit(UO->getSubExpr()); 14433 notePostMod(O, UO, UK_ModAsSideEffect); 14434 } 14435 14436 void VisitBinLOr(const BinaryOperator *BO) { 14437 // C++11 [expr.log.or]p2: 14438 // If the second expression is evaluated, every value computation and 14439 // side effect associated with the first expression is sequenced before 14440 // every value computation and side effect associated with the 14441 // second expression. 14442 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14443 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14444 SequenceTree::Seq OldRegion = Region; 14445 14446 EvaluationTracker Eval(*this); 14447 { 14448 SequencedSubexpression Sequenced(*this); 14449 Region = LHSRegion; 14450 Visit(BO->getLHS()); 14451 } 14452 14453 // C++11 [expr.log.or]p1: 14454 // [...] the second operand is not evaluated if the first operand 14455 // evaluates to true. 14456 bool EvalResult = false; 14457 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14458 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 14459 if (ShouldVisitRHS) { 14460 Region = RHSRegion; 14461 Visit(BO->getRHS()); 14462 } 14463 14464 Region = OldRegion; 14465 Tree.merge(LHSRegion); 14466 Tree.merge(RHSRegion); 14467 } 14468 14469 void VisitBinLAnd(const BinaryOperator *BO) { 14470 // C++11 [expr.log.and]p2: 14471 // If the second expression is evaluated, every value computation and 14472 // side effect associated with the first expression is sequenced before 14473 // every value computation and side effect associated with the 14474 // second expression. 14475 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14476 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14477 SequenceTree::Seq OldRegion = Region; 14478 14479 EvaluationTracker Eval(*this); 14480 { 14481 SequencedSubexpression Sequenced(*this); 14482 Region = LHSRegion; 14483 Visit(BO->getLHS()); 14484 } 14485 14486 // C++11 [expr.log.and]p1: 14487 // [...] the second operand is not evaluated if the first operand is false. 14488 bool EvalResult = false; 14489 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14490 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 14491 if (ShouldVisitRHS) { 14492 Region = RHSRegion; 14493 Visit(BO->getRHS()); 14494 } 14495 14496 Region = OldRegion; 14497 Tree.merge(LHSRegion); 14498 Tree.merge(RHSRegion); 14499 } 14500 14501 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 14502 // C++11 [expr.cond]p1: 14503 // [...] Every value computation and side effect associated with the first 14504 // expression is sequenced before every value computation and side effect 14505 // associated with the second or third expression. 14506 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 14507 14508 // No sequencing is specified between the true and false expression. 14509 // However since exactly one of both is going to be evaluated we can 14510 // consider them to be sequenced. This is needed to avoid warning on 14511 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 14512 // both the true and false expressions because we can't evaluate x. 14513 // This will still allow us to detect an expression like (pre C++17) 14514 // "(x ? y += 1 : y += 2) = y". 14515 // 14516 // We don't wrap the visitation of the true and false expression with 14517 // SequencedSubexpression because we don't want to downgrade modifications 14518 // as side effect in the true and false expressions after the visition 14519 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 14520 // not warn between the two "y++", but we should warn between the "y++" 14521 // and the "y". 14522 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 14523 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 14524 SequenceTree::Seq OldRegion = Region; 14525 14526 EvaluationTracker Eval(*this); 14527 { 14528 SequencedSubexpression Sequenced(*this); 14529 Region = ConditionRegion; 14530 Visit(CO->getCond()); 14531 } 14532 14533 // C++11 [expr.cond]p1: 14534 // [...] The first expression is contextually converted to bool (Clause 4). 14535 // It is evaluated and if it is true, the result of the conditional 14536 // expression is the value of the second expression, otherwise that of the 14537 // third expression. Only one of the second and third expressions is 14538 // evaluated. [...] 14539 bool EvalResult = false; 14540 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 14541 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 14542 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 14543 if (ShouldVisitTrueExpr) { 14544 Region = TrueRegion; 14545 Visit(CO->getTrueExpr()); 14546 } 14547 if (ShouldVisitFalseExpr) { 14548 Region = FalseRegion; 14549 Visit(CO->getFalseExpr()); 14550 } 14551 14552 Region = OldRegion; 14553 Tree.merge(ConditionRegion); 14554 Tree.merge(TrueRegion); 14555 Tree.merge(FalseRegion); 14556 } 14557 14558 void VisitCallExpr(const CallExpr *CE) { 14559 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 14560 14561 if (CE->isUnevaluatedBuiltinCall(Context)) 14562 return; 14563 14564 // C++11 [intro.execution]p15: 14565 // When calling a function [...], every value computation and side effect 14566 // associated with any argument expression, or with the postfix expression 14567 // designating the called function, is sequenced before execution of every 14568 // expression or statement in the body of the function [and thus before 14569 // the value computation of its result]. 14570 SequencedSubexpression Sequenced(*this); 14571 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 14572 // C++17 [expr.call]p5 14573 // The postfix-expression is sequenced before each expression in the 14574 // expression-list and any default argument. [...] 14575 SequenceTree::Seq CalleeRegion; 14576 SequenceTree::Seq OtherRegion; 14577 if (SemaRef.getLangOpts().CPlusPlus17) { 14578 CalleeRegion = Tree.allocate(Region); 14579 OtherRegion = Tree.allocate(Region); 14580 } else { 14581 CalleeRegion = Region; 14582 OtherRegion = Region; 14583 } 14584 SequenceTree::Seq OldRegion = Region; 14585 14586 // Visit the callee expression first. 14587 Region = CalleeRegion; 14588 if (SemaRef.getLangOpts().CPlusPlus17) { 14589 SequencedSubexpression Sequenced(*this); 14590 Visit(CE->getCallee()); 14591 } else { 14592 Visit(CE->getCallee()); 14593 } 14594 14595 // Then visit the argument expressions. 14596 Region = OtherRegion; 14597 for (const Expr *Argument : CE->arguments()) 14598 Visit(Argument); 14599 14600 Region = OldRegion; 14601 if (SemaRef.getLangOpts().CPlusPlus17) { 14602 Tree.merge(CalleeRegion); 14603 Tree.merge(OtherRegion); 14604 } 14605 }); 14606 } 14607 14608 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 14609 // C++17 [over.match.oper]p2: 14610 // [...] the operator notation is first transformed to the equivalent 14611 // function-call notation as summarized in Table 12 (where @ denotes one 14612 // of the operators covered in the specified subclause). However, the 14613 // operands are sequenced in the order prescribed for the built-in 14614 // operator (Clause 8). 14615 // 14616 // From the above only overloaded binary operators and overloaded call 14617 // operators have sequencing rules in C++17 that we need to handle 14618 // separately. 14619 if (!SemaRef.getLangOpts().CPlusPlus17 || 14620 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 14621 return VisitCallExpr(CXXOCE); 14622 14623 enum { 14624 NoSequencing, 14625 LHSBeforeRHS, 14626 RHSBeforeLHS, 14627 LHSBeforeRest 14628 } SequencingKind; 14629 switch (CXXOCE->getOperator()) { 14630 case OO_Equal: 14631 case OO_PlusEqual: 14632 case OO_MinusEqual: 14633 case OO_StarEqual: 14634 case OO_SlashEqual: 14635 case OO_PercentEqual: 14636 case OO_CaretEqual: 14637 case OO_AmpEqual: 14638 case OO_PipeEqual: 14639 case OO_LessLessEqual: 14640 case OO_GreaterGreaterEqual: 14641 SequencingKind = RHSBeforeLHS; 14642 break; 14643 14644 case OO_LessLess: 14645 case OO_GreaterGreater: 14646 case OO_AmpAmp: 14647 case OO_PipePipe: 14648 case OO_Comma: 14649 case OO_ArrowStar: 14650 case OO_Subscript: 14651 SequencingKind = LHSBeforeRHS; 14652 break; 14653 14654 case OO_Call: 14655 SequencingKind = LHSBeforeRest; 14656 break; 14657 14658 default: 14659 SequencingKind = NoSequencing; 14660 break; 14661 } 14662 14663 if (SequencingKind == NoSequencing) 14664 return VisitCallExpr(CXXOCE); 14665 14666 // This is a call, so all subexpressions are sequenced before the result. 14667 SequencedSubexpression Sequenced(*this); 14668 14669 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 14670 assert(SemaRef.getLangOpts().CPlusPlus17 && 14671 "Should only get there with C++17 and above!"); 14672 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 14673 "Should only get there with an overloaded binary operator" 14674 " or an overloaded call operator!"); 14675 14676 if (SequencingKind == LHSBeforeRest) { 14677 assert(CXXOCE->getOperator() == OO_Call && 14678 "We should only have an overloaded call operator here!"); 14679 14680 // This is very similar to VisitCallExpr, except that we only have the 14681 // C++17 case. The postfix-expression is the first argument of the 14682 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 14683 // are in the following arguments. 14684 // 14685 // Note that we intentionally do not visit the callee expression since 14686 // it is just a decayed reference to a function. 14687 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 14688 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 14689 SequenceTree::Seq OldRegion = Region; 14690 14691 assert(CXXOCE->getNumArgs() >= 1 && 14692 "An overloaded call operator must have at least one argument" 14693 " for the postfix-expression!"); 14694 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 14695 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 14696 CXXOCE->getNumArgs() - 1); 14697 14698 // Visit the postfix-expression first. 14699 { 14700 Region = PostfixExprRegion; 14701 SequencedSubexpression Sequenced(*this); 14702 Visit(PostfixExpr); 14703 } 14704 14705 // Then visit the argument expressions. 14706 Region = ArgsRegion; 14707 for (const Expr *Arg : Args) 14708 Visit(Arg); 14709 14710 Region = OldRegion; 14711 Tree.merge(PostfixExprRegion); 14712 Tree.merge(ArgsRegion); 14713 } else { 14714 assert(CXXOCE->getNumArgs() == 2 && 14715 "Should only have two arguments here!"); 14716 assert((SequencingKind == LHSBeforeRHS || 14717 SequencingKind == RHSBeforeLHS) && 14718 "Unexpected sequencing kind!"); 14719 14720 // We do not visit the callee expression since it is just a decayed 14721 // reference to a function. 14722 const Expr *E1 = CXXOCE->getArg(0); 14723 const Expr *E2 = CXXOCE->getArg(1); 14724 if (SequencingKind == RHSBeforeLHS) 14725 std::swap(E1, E2); 14726 14727 return VisitSequencedExpressions(E1, E2); 14728 } 14729 }); 14730 } 14731 14732 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14733 // This is a call, so all subexpressions are sequenced before the result. 14734 SequencedSubexpression Sequenced(*this); 14735 14736 if (!CCE->isListInitialization()) 14737 return VisitExpr(CCE); 14738 14739 // In C++11, list initializations are sequenced. 14740 SmallVector<SequenceTree::Seq, 32> Elts; 14741 SequenceTree::Seq Parent = Region; 14742 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14743 E = CCE->arg_end(); 14744 I != E; ++I) { 14745 Region = Tree.allocate(Parent); 14746 Elts.push_back(Region); 14747 Visit(*I); 14748 } 14749 14750 // Forget that the initializers are sequenced. 14751 Region = Parent; 14752 for (unsigned I = 0; I < Elts.size(); ++I) 14753 Tree.merge(Elts[I]); 14754 } 14755 14756 void VisitInitListExpr(const InitListExpr *ILE) { 14757 if (!SemaRef.getLangOpts().CPlusPlus11) 14758 return VisitExpr(ILE); 14759 14760 // In C++11, list initializations are sequenced. 14761 SmallVector<SequenceTree::Seq, 32> Elts; 14762 SequenceTree::Seq Parent = Region; 14763 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14764 const Expr *E = ILE->getInit(I); 14765 if (!E) 14766 continue; 14767 Region = Tree.allocate(Parent); 14768 Elts.push_back(Region); 14769 Visit(E); 14770 } 14771 14772 // Forget that the initializers are sequenced. 14773 Region = Parent; 14774 for (unsigned I = 0; I < Elts.size(); ++I) 14775 Tree.merge(Elts[I]); 14776 } 14777 }; 14778 14779 } // namespace 14780 14781 void Sema::CheckUnsequencedOperations(const Expr *E) { 14782 SmallVector<const Expr *, 8> WorkList; 14783 WorkList.push_back(E); 14784 while (!WorkList.empty()) { 14785 const Expr *Item = WorkList.pop_back_val(); 14786 SequenceChecker(*this, Item, WorkList); 14787 } 14788 } 14789 14790 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14791 bool IsConstexpr) { 14792 llvm::SaveAndRestore<bool> ConstantContext( 14793 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14794 CheckImplicitConversions(E, CheckLoc); 14795 if (!E->isInstantiationDependent()) 14796 CheckUnsequencedOperations(E); 14797 if (!IsConstexpr && !E->isValueDependent()) 14798 CheckForIntOverflow(E); 14799 DiagnoseMisalignedMembers(); 14800 } 14801 14802 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14803 FieldDecl *BitField, 14804 Expr *Init) { 14805 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14806 } 14807 14808 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14809 SourceLocation Loc) { 14810 if (!PType->isVariablyModifiedType()) 14811 return; 14812 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14813 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14814 return; 14815 } 14816 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14817 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14818 return; 14819 } 14820 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14821 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14822 return; 14823 } 14824 14825 const ArrayType *AT = S.Context.getAsArrayType(PType); 14826 if (!AT) 14827 return; 14828 14829 if (AT->getSizeModifier() != ArrayType::Star) { 14830 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14831 return; 14832 } 14833 14834 S.Diag(Loc, diag::err_array_star_in_function_definition); 14835 } 14836 14837 /// CheckParmsForFunctionDef - Check that the parameters of the given 14838 /// function are appropriate for the definition of a function. This 14839 /// takes care of any checks that cannot be performed on the 14840 /// declaration itself, e.g., that the types of each of the function 14841 /// parameters are complete. 14842 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14843 bool CheckParameterNames) { 14844 bool HasInvalidParm = false; 14845 for (ParmVarDecl *Param : Parameters) { 14846 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14847 // function declarator that is part of a function definition of 14848 // that function shall not have incomplete type. 14849 // 14850 // This is also C++ [dcl.fct]p6. 14851 if (!Param->isInvalidDecl() && 14852 RequireCompleteType(Param->getLocation(), Param->getType(), 14853 diag::err_typecheck_decl_incomplete_type)) { 14854 Param->setInvalidDecl(); 14855 HasInvalidParm = true; 14856 } 14857 14858 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14859 // declaration of each parameter shall include an identifier. 14860 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14861 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14862 // Diagnose this as an extension in C17 and earlier. 14863 if (!getLangOpts().C2x) 14864 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14865 } 14866 14867 // C99 6.7.5.3p12: 14868 // If the function declarator is not part of a definition of that 14869 // function, parameters may have incomplete type and may use the [*] 14870 // notation in their sequences of declarator specifiers to specify 14871 // variable length array types. 14872 QualType PType = Param->getOriginalType(); 14873 // FIXME: This diagnostic should point the '[*]' if source-location 14874 // information is added for it. 14875 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14876 14877 // If the parameter is a c++ class type and it has to be destructed in the 14878 // callee function, declare the destructor so that it can be called by the 14879 // callee function. Do not perform any direct access check on the dtor here. 14880 if (!Param->isInvalidDecl()) { 14881 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14882 if (!ClassDecl->isInvalidDecl() && 14883 !ClassDecl->hasIrrelevantDestructor() && 14884 !ClassDecl->isDependentContext() && 14885 ClassDecl->isParamDestroyedInCallee()) { 14886 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14887 MarkFunctionReferenced(Param->getLocation(), Destructor); 14888 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14889 } 14890 } 14891 } 14892 14893 // Parameters with the pass_object_size attribute only need to be marked 14894 // constant at function definitions. Because we lack information about 14895 // whether we're on a declaration or definition when we're instantiating the 14896 // attribute, we need to check for constness here. 14897 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14898 if (!Param->getType().isConstQualified()) 14899 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14900 << Attr->getSpelling() << 1; 14901 14902 // Check for parameter names shadowing fields from the class. 14903 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14904 // The owning context for the parameter should be the function, but we 14905 // want to see if this function's declaration context is a record. 14906 DeclContext *DC = Param->getDeclContext(); 14907 if (DC && DC->isFunctionOrMethod()) { 14908 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14909 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14910 RD, /*DeclIsField*/ false); 14911 } 14912 } 14913 } 14914 14915 return HasInvalidParm; 14916 } 14917 14918 Optional<std::pair<CharUnits, CharUnits>> 14919 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14920 14921 /// Compute the alignment and offset of the base class object given the 14922 /// derived-to-base cast expression and the alignment and offset of the derived 14923 /// class object. 14924 static std::pair<CharUnits, CharUnits> 14925 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14926 CharUnits BaseAlignment, CharUnits Offset, 14927 ASTContext &Ctx) { 14928 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14929 ++PathI) { 14930 const CXXBaseSpecifier *Base = *PathI; 14931 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14932 if (Base->isVirtual()) { 14933 // The complete object may have a lower alignment than the non-virtual 14934 // alignment of the base, in which case the base may be misaligned. Choose 14935 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14936 // conservative lower bound of the complete object alignment. 14937 CharUnits NonVirtualAlignment = 14938 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14939 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14940 Offset = CharUnits::Zero(); 14941 } else { 14942 const ASTRecordLayout &RL = 14943 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14944 Offset += RL.getBaseClassOffset(BaseDecl); 14945 } 14946 DerivedType = Base->getType(); 14947 } 14948 14949 return std::make_pair(BaseAlignment, Offset); 14950 } 14951 14952 /// Compute the alignment and offset of a binary additive operator. 14953 static Optional<std::pair<CharUnits, CharUnits>> 14954 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14955 bool IsSub, ASTContext &Ctx) { 14956 QualType PointeeType = PtrE->getType()->getPointeeType(); 14957 14958 if (!PointeeType->isConstantSizeType()) 14959 return llvm::None; 14960 14961 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14962 14963 if (!P) 14964 return llvm::None; 14965 14966 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14967 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14968 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14969 if (IsSub) 14970 Offset = -Offset; 14971 return std::make_pair(P->first, P->second + Offset); 14972 } 14973 14974 // If the integer expression isn't a constant expression, compute the lower 14975 // bound of the alignment using the alignment and offset of the pointer 14976 // expression and the element size. 14977 return std::make_pair( 14978 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14979 CharUnits::Zero()); 14980 } 14981 14982 /// This helper function takes an lvalue expression and returns the alignment of 14983 /// a VarDecl and a constant offset from the VarDecl. 14984 Optional<std::pair<CharUnits, CharUnits>> 14985 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14986 E = E->IgnoreParens(); 14987 switch (E->getStmtClass()) { 14988 default: 14989 break; 14990 case Stmt::CStyleCastExprClass: 14991 case Stmt::CXXStaticCastExprClass: 14992 case Stmt::ImplicitCastExprClass: { 14993 auto *CE = cast<CastExpr>(E); 14994 const Expr *From = CE->getSubExpr(); 14995 switch (CE->getCastKind()) { 14996 default: 14997 break; 14998 case CK_NoOp: 14999 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 15000 case CK_UncheckedDerivedToBase: 15001 case CK_DerivedToBase: { 15002 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 15003 if (!P) 15004 break; 15005 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 15006 P->second, Ctx); 15007 } 15008 } 15009 break; 15010 } 15011 case Stmt::ArraySubscriptExprClass: { 15012 auto *ASE = cast<ArraySubscriptExpr>(E); 15013 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 15014 false, Ctx); 15015 } 15016 case Stmt::DeclRefExprClass: { 15017 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 15018 // FIXME: If VD is captured by copy or is an escaping __block variable, 15019 // use the alignment of VD's type. 15020 if (!VD->getType()->isReferenceType()) 15021 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 15022 if (VD->hasInit()) 15023 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 15024 } 15025 break; 15026 } 15027 case Stmt::MemberExprClass: { 15028 auto *ME = cast<MemberExpr>(E); 15029 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 15030 if (!FD || FD->getType()->isReferenceType() || 15031 FD->getParent()->isInvalidDecl()) 15032 break; 15033 Optional<std::pair<CharUnits, CharUnits>> P; 15034 if (ME->isArrow()) 15035 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 15036 else 15037 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 15038 if (!P) 15039 break; 15040 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 15041 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 15042 return std::make_pair(P->first, 15043 P->second + CharUnits::fromQuantity(Offset)); 15044 } 15045 case Stmt::UnaryOperatorClass: { 15046 auto *UO = cast<UnaryOperator>(E); 15047 switch (UO->getOpcode()) { 15048 default: 15049 break; 15050 case UO_Deref: 15051 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 15052 } 15053 break; 15054 } 15055 case Stmt::BinaryOperatorClass: { 15056 auto *BO = cast<BinaryOperator>(E); 15057 auto Opcode = BO->getOpcode(); 15058 switch (Opcode) { 15059 default: 15060 break; 15061 case BO_Comma: 15062 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 15063 } 15064 break; 15065 } 15066 } 15067 return llvm::None; 15068 } 15069 15070 /// This helper function takes a pointer expression and returns the alignment of 15071 /// a VarDecl and a constant offset from the VarDecl. 15072 Optional<std::pair<CharUnits, CharUnits>> 15073 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 15074 E = E->IgnoreParens(); 15075 switch (E->getStmtClass()) { 15076 default: 15077 break; 15078 case Stmt::CStyleCastExprClass: 15079 case Stmt::CXXStaticCastExprClass: 15080 case Stmt::ImplicitCastExprClass: { 15081 auto *CE = cast<CastExpr>(E); 15082 const Expr *From = CE->getSubExpr(); 15083 switch (CE->getCastKind()) { 15084 default: 15085 break; 15086 case CK_NoOp: 15087 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 15088 case CK_ArrayToPointerDecay: 15089 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 15090 case CK_UncheckedDerivedToBase: 15091 case CK_DerivedToBase: { 15092 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 15093 if (!P) 15094 break; 15095 return getDerivedToBaseAlignmentAndOffset( 15096 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 15097 } 15098 } 15099 break; 15100 } 15101 case Stmt::CXXThisExprClass: { 15102 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 15103 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 15104 return std::make_pair(Alignment, CharUnits::Zero()); 15105 } 15106 case Stmt::UnaryOperatorClass: { 15107 auto *UO = cast<UnaryOperator>(E); 15108 if (UO->getOpcode() == UO_AddrOf) 15109 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 15110 break; 15111 } 15112 case Stmt::BinaryOperatorClass: { 15113 auto *BO = cast<BinaryOperator>(E); 15114 auto Opcode = BO->getOpcode(); 15115 switch (Opcode) { 15116 default: 15117 break; 15118 case BO_Add: 15119 case BO_Sub: { 15120 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 15121 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 15122 std::swap(LHS, RHS); 15123 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 15124 Ctx); 15125 } 15126 case BO_Comma: 15127 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 15128 } 15129 break; 15130 } 15131 } 15132 return llvm::None; 15133 } 15134 15135 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 15136 // See if we can compute the alignment of a VarDecl and an offset from it. 15137 Optional<std::pair<CharUnits, CharUnits>> P = 15138 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 15139 15140 if (P) 15141 return P->first.alignmentAtOffset(P->second); 15142 15143 // If that failed, return the type's alignment. 15144 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 15145 } 15146 15147 /// CheckCastAlign - Implements -Wcast-align, which warns when a 15148 /// pointer cast increases the alignment requirements. 15149 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 15150 // This is actually a lot of work to potentially be doing on every 15151 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 15152 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 15153 return; 15154 15155 // Ignore dependent types. 15156 if (T->isDependentType() || Op->getType()->isDependentType()) 15157 return; 15158 15159 // Require that the destination be a pointer type. 15160 const PointerType *DestPtr = T->getAs<PointerType>(); 15161 if (!DestPtr) return; 15162 15163 // If the destination has alignment 1, we're done. 15164 QualType DestPointee = DestPtr->getPointeeType(); 15165 if (DestPointee->isIncompleteType()) return; 15166 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 15167 if (DestAlign.isOne()) return; 15168 15169 // Require that the source be a pointer type. 15170 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 15171 if (!SrcPtr) return; 15172 QualType SrcPointee = SrcPtr->getPointeeType(); 15173 15174 // Explicitly allow casts from cv void*. We already implicitly 15175 // allowed casts to cv void*, since they have alignment 1. 15176 // Also allow casts involving incomplete types, which implicitly 15177 // includes 'void'. 15178 if (SrcPointee->isIncompleteType()) return; 15179 15180 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 15181 15182 if (SrcAlign >= DestAlign) return; 15183 15184 Diag(TRange.getBegin(), diag::warn_cast_align) 15185 << Op->getType() << T 15186 << static_cast<unsigned>(SrcAlign.getQuantity()) 15187 << static_cast<unsigned>(DestAlign.getQuantity()) 15188 << TRange << Op->getSourceRange(); 15189 } 15190 15191 /// Check whether this array fits the idiom of a size-one tail padded 15192 /// array member of a struct. 15193 /// 15194 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 15195 /// commonly used to emulate flexible arrays in C89 code. 15196 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 15197 const NamedDecl *ND) { 15198 if (Size != 1 || !ND) return false; 15199 15200 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 15201 if (!FD) return false; 15202 15203 // Don't consider sizes resulting from macro expansions or template argument 15204 // substitution to form C89 tail-padded arrays. 15205 15206 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 15207 while (TInfo) { 15208 TypeLoc TL = TInfo->getTypeLoc(); 15209 // Look through typedefs. 15210 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 15211 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 15212 TInfo = TDL->getTypeSourceInfo(); 15213 continue; 15214 } 15215 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 15216 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 15217 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 15218 return false; 15219 } 15220 break; 15221 } 15222 15223 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 15224 if (!RD) return false; 15225 if (RD->isUnion()) return false; 15226 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15227 if (!CRD->isStandardLayout()) return false; 15228 } 15229 15230 // See if this is the last field decl in the record. 15231 const Decl *D = FD; 15232 while ((D = D->getNextDeclInContext())) 15233 if (isa<FieldDecl>(D)) 15234 return false; 15235 return true; 15236 } 15237 15238 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 15239 const ArraySubscriptExpr *ASE, 15240 bool AllowOnePastEnd, bool IndexNegated) { 15241 // Already diagnosed by the constant evaluator. 15242 if (isConstantEvaluated()) 15243 return; 15244 15245 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 15246 if (IndexExpr->isValueDependent()) 15247 return; 15248 15249 const Type *EffectiveType = 15250 BaseExpr->getType()->getPointeeOrArrayElementType(); 15251 BaseExpr = BaseExpr->IgnoreParenCasts(); 15252 const ConstantArrayType *ArrayTy = 15253 Context.getAsConstantArrayType(BaseExpr->getType()); 15254 15255 const Type *BaseType = 15256 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 15257 bool IsUnboundedArray = (BaseType == nullptr); 15258 if (EffectiveType->isDependentType() || 15259 (!IsUnboundedArray && BaseType->isDependentType())) 15260 return; 15261 15262 Expr::EvalResult Result; 15263 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 15264 return; 15265 15266 llvm::APSInt index = Result.Val.getInt(); 15267 if (IndexNegated) { 15268 index.setIsUnsigned(false); 15269 index = -index; 15270 } 15271 15272 const NamedDecl *ND = nullptr; 15273 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15274 ND = DRE->getDecl(); 15275 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 15276 ND = ME->getMemberDecl(); 15277 15278 if (IsUnboundedArray) { 15279 if (index.isUnsigned() || !index.isNegative()) { 15280 const auto &ASTC = getASTContext(); 15281 unsigned AddrBits = 15282 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 15283 EffectiveType->getCanonicalTypeInternal())); 15284 if (index.getBitWidth() < AddrBits) 15285 index = index.zext(AddrBits); 15286 Optional<CharUnits> ElemCharUnits = 15287 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 15288 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 15289 // pointer) bounds-checking isn't meaningful. 15290 if (!ElemCharUnits) 15291 return; 15292 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 15293 // If index has more active bits than address space, we already know 15294 // we have a bounds violation to warn about. Otherwise, compute 15295 // address of (index + 1)th element, and warn about bounds violation 15296 // only if that address exceeds address space. 15297 if (index.getActiveBits() <= AddrBits) { 15298 bool Overflow; 15299 llvm::APInt Product(index); 15300 Product += 1; 15301 Product = Product.umul_ov(ElemBytes, Overflow); 15302 if (!Overflow && Product.getActiveBits() <= AddrBits) 15303 return; 15304 } 15305 15306 // Need to compute max possible elements in address space, since that 15307 // is included in diag message. 15308 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 15309 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 15310 MaxElems += 1; 15311 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 15312 MaxElems = MaxElems.udiv(ElemBytes); 15313 15314 unsigned DiagID = 15315 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 15316 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 15317 15318 // Diag message shows element size in bits and in "bytes" (platform- 15319 // dependent CharUnits) 15320 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15321 PDiag(DiagID) 15322 << toString(index, 10, true) << AddrBits 15323 << (unsigned)ASTC.toBits(*ElemCharUnits) 15324 << toString(ElemBytes, 10, false) 15325 << toString(MaxElems, 10, false) 15326 << (unsigned)MaxElems.getLimitedValue(~0U) 15327 << IndexExpr->getSourceRange()); 15328 15329 if (!ND) { 15330 // Try harder to find a NamedDecl to point at in the note. 15331 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15332 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15333 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15334 ND = DRE->getDecl(); 15335 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15336 ND = ME->getMemberDecl(); 15337 } 15338 15339 if (ND) 15340 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15341 PDiag(diag::note_array_declared_here) << ND); 15342 } 15343 return; 15344 } 15345 15346 if (index.isUnsigned() || !index.isNegative()) { 15347 // It is possible that the type of the base expression after 15348 // IgnoreParenCasts is incomplete, even though the type of the base 15349 // expression before IgnoreParenCasts is complete (see PR39746 for an 15350 // example). In this case we have no information about whether the array 15351 // access exceeds the array bounds. However we can still diagnose an array 15352 // access which precedes the array bounds. 15353 if (BaseType->isIncompleteType()) 15354 return; 15355 15356 llvm::APInt size = ArrayTy->getSize(); 15357 if (!size.isStrictlyPositive()) 15358 return; 15359 15360 if (BaseType != EffectiveType) { 15361 // Make sure we're comparing apples to apples when comparing index to size 15362 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 15363 uint64_t array_typesize = Context.getTypeSize(BaseType); 15364 // Handle ptrarith_typesize being zero, such as when casting to void* 15365 if (!ptrarith_typesize) ptrarith_typesize = 1; 15366 if (ptrarith_typesize != array_typesize) { 15367 // There's a cast to a different size type involved 15368 uint64_t ratio = array_typesize / ptrarith_typesize; 15369 // TODO: Be smarter about handling cases where array_typesize is not a 15370 // multiple of ptrarith_typesize 15371 if (ptrarith_typesize * ratio == array_typesize) 15372 size *= llvm::APInt(size.getBitWidth(), ratio); 15373 } 15374 } 15375 15376 if (size.getBitWidth() > index.getBitWidth()) 15377 index = index.zext(size.getBitWidth()); 15378 else if (size.getBitWidth() < index.getBitWidth()) 15379 size = size.zext(index.getBitWidth()); 15380 15381 // For array subscripting the index must be less than size, but for pointer 15382 // arithmetic also allow the index (offset) to be equal to size since 15383 // computing the next address after the end of the array is legal and 15384 // commonly done e.g. in C++ iterators and range-based for loops. 15385 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 15386 return; 15387 15388 // Also don't warn for arrays of size 1 which are members of some 15389 // structure. These are often used to approximate flexible arrays in C89 15390 // code. 15391 if (IsTailPaddedMemberArray(*this, size, ND)) 15392 return; 15393 15394 // Suppress the warning if the subscript expression (as identified by the 15395 // ']' location) and the index expression are both from macro expansions 15396 // within a system header. 15397 if (ASE) { 15398 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 15399 ASE->getRBracketLoc()); 15400 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 15401 SourceLocation IndexLoc = 15402 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 15403 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 15404 return; 15405 } 15406 } 15407 15408 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 15409 : diag::warn_ptr_arith_exceeds_bounds; 15410 15411 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15412 PDiag(DiagID) << toString(index, 10, true) 15413 << toString(size, 10, true) 15414 << (unsigned)size.getLimitedValue(~0U) 15415 << IndexExpr->getSourceRange()); 15416 } else { 15417 unsigned DiagID = diag::warn_array_index_precedes_bounds; 15418 if (!ASE) { 15419 DiagID = diag::warn_ptr_arith_precedes_bounds; 15420 if (index.isNegative()) index = -index; 15421 } 15422 15423 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15424 PDiag(DiagID) << toString(index, 10, true) 15425 << IndexExpr->getSourceRange()); 15426 } 15427 15428 if (!ND) { 15429 // Try harder to find a NamedDecl to point at in the note. 15430 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15431 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15432 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15433 ND = DRE->getDecl(); 15434 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15435 ND = ME->getMemberDecl(); 15436 } 15437 15438 if (ND) 15439 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15440 PDiag(diag::note_array_declared_here) << ND); 15441 } 15442 15443 void Sema::CheckArrayAccess(const Expr *expr) { 15444 int AllowOnePastEnd = 0; 15445 while (expr) { 15446 expr = expr->IgnoreParenImpCasts(); 15447 switch (expr->getStmtClass()) { 15448 case Stmt::ArraySubscriptExprClass: { 15449 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 15450 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 15451 AllowOnePastEnd > 0); 15452 expr = ASE->getBase(); 15453 break; 15454 } 15455 case Stmt::MemberExprClass: { 15456 expr = cast<MemberExpr>(expr)->getBase(); 15457 break; 15458 } 15459 case Stmt::OMPArraySectionExprClass: { 15460 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 15461 if (ASE->getLowerBound()) 15462 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 15463 /*ASE=*/nullptr, AllowOnePastEnd > 0); 15464 return; 15465 } 15466 case Stmt::UnaryOperatorClass: { 15467 // Only unwrap the * and & unary operators 15468 const UnaryOperator *UO = cast<UnaryOperator>(expr); 15469 expr = UO->getSubExpr(); 15470 switch (UO->getOpcode()) { 15471 case UO_AddrOf: 15472 AllowOnePastEnd++; 15473 break; 15474 case UO_Deref: 15475 AllowOnePastEnd--; 15476 break; 15477 default: 15478 return; 15479 } 15480 break; 15481 } 15482 case Stmt::ConditionalOperatorClass: { 15483 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 15484 if (const Expr *lhs = cond->getLHS()) 15485 CheckArrayAccess(lhs); 15486 if (const Expr *rhs = cond->getRHS()) 15487 CheckArrayAccess(rhs); 15488 return; 15489 } 15490 case Stmt::CXXOperatorCallExprClass: { 15491 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 15492 for (const auto *Arg : OCE->arguments()) 15493 CheckArrayAccess(Arg); 15494 return; 15495 } 15496 default: 15497 return; 15498 } 15499 } 15500 } 15501 15502 //===--- CHECK: Objective-C retain cycles ----------------------------------// 15503 15504 namespace { 15505 15506 struct RetainCycleOwner { 15507 VarDecl *Variable = nullptr; 15508 SourceRange Range; 15509 SourceLocation Loc; 15510 bool Indirect = false; 15511 15512 RetainCycleOwner() = default; 15513 15514 void setLocsFrom(Expr *e) { 15515 Loc = e->getExprLoc(); 15516 Range = e->getSourceRange(); 15517 } 15518 }; 15519 15520 } // namespace 15521 15522 /// Consider whether capturing the given variable can possibly lead to 15523 /// a retain cycle. 15524 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 15525 // In ARC, it's captured strongly iff the variable has __strong 15526 // lifetime. In MRR, it's captured strongly if the variable is 15527 // __block and has an appropriate type. 15528 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15529 return false; 15530 15531 owner.Variable = var; 15532 if (ref) 15533 owner.setLocsFrom(ref); 15534 return true; 15535 } 15536 15537 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 15538 while (true) { 15539 e = e->IgnoreParens(); 15540 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 15541 switch (cast->getCastKind()) { 15542 case CK_BitCast: 15543 case CK_LValueBitCast: 15544 case CK_LValueToRValue: 15545 case CK_ARCReclaimReturnedObject: 15546 e = cast->getSubExpr(); 15547 continue; 15548 15549 default: 15550 return false; 15551 } 15552 } 15553 15554 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 15555 ObjCIvarDecl *ivar = ref->getDecl(); 15556 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15557 return false; 15558 15559 // Try to find a retain cycle in the base. 15560 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 15561 return false; 15562 15563 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 15564 owner.Indirect = true; 15565 return true; 15566 } 15567 15568 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 15569 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 15570 if (!var) return false; 15571 return considerVariable(var, ref, owner); 15572 } 15573 15574 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 15575 if (member->isArrow()) return false; 15576 15577 // Don't count this as an indirect ownership. 15578 e = member->getBase(); 15579 continue; 15580 } 15581 15582 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 15583 // Only pay attention to pseudo-objects on property references. 15584 ObjCPropertyRefExpr *pre 15585 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 15586 ->IgnoreParens()); 15587 if (!pre) return false; 15588 if (pre->isImplicitProperty()) return false; 15589 ObjCPropertyDecl *property = pre->getExplicitProperty(); 15590 if (!property->isRetaining() && 15591 !(property->getPropertyIvarDecl() && 15592 property->getPropertyIvarDecl()->getType() 15593 .getObjCLifetime() == Qualifiers::OCL_Strong)) 15594 return false; 15595 15596 owner.Indirect = true; 15597 if (pre->isSuperReceiver()) { 15598 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 15599 if (!owner.Variable) 15600 return false; 15601 owner.Loc = pre->getLocation(); 15602 owner.Range = pre->getSourceRange(); 15603 return true; 15604 } 15605 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 15606 ->getSourceExpr()); 15607 continue; 15608 } 15609 15610 // Array ivars? 15611 15612 return false; 15613 } 15614 } 15615 15616 namespace { 15617 15618 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 15619 ASTContext &Context; 15620 VarDecl *Variable; 15621 Expr *Capturer = nullptr; 15622 bool VarWillBeReased = false; 15623 15624 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 15625 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 15626 Context(Context), Variable(variable) {} 15627 15628 void VisitDeclRefExpr(DeclRefExpr *ref) { 15629 if (ref->getDecl() == Variable && !Capturer) 15630 Capturer = ref; 15631 } 15632 15633 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 15634 if (Capturer) return; 15635 Visit(ref->getBase()); 15636 if (Capturer && ref->isFreeIvar()) 15637 Capturer = ref; 15638 } 15639 15640 void VisitBlockExpr(BlockExpr *block) { 15641 // Look inside nested blocks 15642 if (block->getBlockDecl()->capturesVariable(Variable)) 15643 Visit(block->getBlockDecl()->getBody()); 15644 } 15645 15646 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 15647 if (Capturer) return; 15648 if (OVE->getSourceExpr()) 15649 Visit(OVE->getSourceExpr()); 15650 } 15651 15652 void VisitBinaryOperator(BinaryOperator *BinOp) { 15653 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 15654 return; 15655 Expr *LHS = BinOp->getLHS(); 15656 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 15657 if (DRE->getDecl() != Variable) 15658 return; 15659 if (Expr *RHS = BinOp->getRHS()) { 15660 RHS = RHS->IgnoreParenCasts(); 15661 Optional<llvm::APSInt> Value; 15662 VarWillBeReased = 15663 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 15664 *Value == 0); 15665 } 15666 } 15667 } 15668 }; 15669 15670 } // namespace 15671 15672 /// Check whether the given argument is a block which captures a 15673 /// variable. 15674 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 15675 assert(owner.Variable && owner.Loc.isValid()); 15676 15677 e = e->IgnoreParenCasts(); 15678 15679 // Look through [^{...} copy] and Block_copy(^{...}). 15680 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 15681 Selector Cmd = ME->getSelector(); 15682 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 15683 e = ME->getInstanceReceiver(); 15684 if (!e) 15685 return nullptr; 15686 e = e->IgnoreParenCasts(); 15687 } 15688 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 15689 if (CE->getNumArgs() == 1) { 15690 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 15691 if (Fn) { 15692 const IdentifierInfo *FnI = Fn->getIdentifier(); 15693 if (FnI && FnI->isStr("_Block_copy")) { 15694 e = CE->getArg(0)->IgnoreParenCasts(); 15695 } 15696 } 15697 } 15698 } 15699 15700 BlockExpr *block = dyn_cast<BlockExpr>(e); 15701 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 15702 return nullptr; 15703 15704 FindCaptureVisitor visitor(S.Context, owner.Variable); 15705 visitor.Visit(block->getBlockDecl()->getBody()); 15706 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15707 } 15708 15709 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15710 RetainCycleOwner &owner) { 15711 assert(capturer); 15712 assert(owner.Variable && owner.Loc.isValid()); 15713 15714 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15715 << owner.Variable << capturer->getSourceRange(); 15716 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15717 << owner.Indirect << owner.Range; 15718 } 15719 15720 /// Check for a keyword selector that starts with the word 'add' or 15721 /// 'set'. 15722 static bool isSetterLikeSelector(Selector sel) { 15723 if (sel.isUnarySelector()) return false; 15724 15725 StringRef str = sel.getNameForSlot(0); 15726 while (!str.empty() && str.front() == '_') str = str.substr(1); 15727 if (str.startswith("set")) 15728 str = str.substr(3); 15729 else if (str.startswith("add")) { 15730 // Specially allow 'addOperationWithBlock:'. 15731 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15732 return false; 15733 str = str.substr(3); 15734 } 15735 else 15736 return false; 15737 15738 if (str.empty()) return true; 15739 return !isLowercase(str.front()); 15740 } 15741 15742 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15743 ObjCMessageExpr *Message) { 15744 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15745 Message->getReceiverInterface(), 15746 NSAPI::ClassId_NSMutableArray); 15747 if (!IsMutableArray) { 15748 return None; 15749 } 15750 15751 Selector Sel = Message->getSelector(); 15752 15753 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15754 S.NSAPIObj->getNSArrayMethodKind(Sel); 15755 if (!MKOpt) { 15756 return None; 15757 } 15758 15759 NSAPI::NSArrayMethodKind MK = *MKOpt; 15760 15761 switch (MK) { 15762 case NSAPI::NSMutableArr_addObject: 15763 case NSAPI::NSMutableArr_insertObjectAtIndex: 15764 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15765 return 0; 15766 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15767 return 1; 15768 15769 default: 15770 return None; 15771 } 15772 15773 return None; 15774 } 15775 15776 static 15777 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15778 ObjCMessageExpr *Message) { 15779 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15780 Message->getReceiverInterface(), 15781 NSAPI::ClassId_NSMutableDictionary); 15782 if (!IsMutableDictionary) { 15783 return None; 15784 } 15785 15786 Selector Sel = Message->getSelector(); 15787 15788 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 15789 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 15790 if (!MKOpt) { 15791 return None; 15792 } 15793 15794 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 15795 15796 switch (MK) { 15797 case NSAPI::NSMutableDict_setObjectForKey: 15798 case NSAPI::NSMutableDict_setValueForKey: 15799 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 15800 return 0; 15801 15802 default: 15803 return None; 15804 } 15805 15806 return None; 15807 } 15808 15809 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 15810 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 15811 Message->getReceiverInterface(), 15812 NSAPI::ClassId_NSMutableSet); 15813 15814 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 15815 Message->getReceiverInterface(), 15816 NSAPI::ClassId_NSMutableOrderedSet); 15817 if (!IsMutableSet && !IsMutableOrderedSet) { 15818 return None; 15819 } 15820 15821 Selector Sel = Message->getSelector(); 15822 15823 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15824 if (!MKOpt) { 15825 return None; 15826 } 15827 15828 NSAPI::NSSetMethodKind MK = *MKOpt; 15829 15830 switch (MK) { 15831 case NSAPI::NSMutableSet_addObject: 15832 case NSAPI::NSOrderedSet_setObjectAtIndex: 15833 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15834 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15835 return 0; 15836 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 15837 return 1; 15838 } 15839 15840 return None; 15841 } 15842 15843 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 15844 if (!Message->isInstanceMessage()) { 15845 return; 15846 } 15847 15848 Optional<int> ArgOpt; 15849 15850 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 15851 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 15852 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 15853 return; 15854 } 15855 15856 int ArgIndex = *ArgOpt; 15857 15858 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 15859 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 15860 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 15861 } 15862 15863 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 15864 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15865 if (ArgRE->isObjCSelfExpr()) { 15866 Diag(Message->getSourceRange().getBegin(), 15867 diag::warn_objc_circular_container) 15868 << ArgRE->getDecl() << StringRef("'super'"); 15869 } 15870 } 15871 } else { 15872 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 15873 15874 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 15875 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 15876 } 15877 15878 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 15879 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15880 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 15881 ValueDecl *Decl = ReceiverRE->getDecl(); 15882 Diag(Message->getSourceRange().getBegin(), 15883 diag::warn_objc_circular_container) 15884 << Decl << Decl; 15885 if (!ArgRE->isObjCSelfExpr()) { 15886 Diag(Decl->getLocation(), 15887 diag::note_objc_circular_container_declared_here) 15888 << Decl; 15889 } 15890 } 15891 } 15892 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15893 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15894 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15895 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15896 Diag(Message->getSourceRange().getBegin(), 15897 diag::warn_objc_circular_container) 15898 << Decl << Decl; 15899 Diag(Decl->getLocation(), 15900 diag::note_objc_circular_container_declared_here) 15901 << Decl; 15902 } 15903 } 15904 } 15905 } 15906 } 15907 15908 /// Check a message send to see if it's likely to cause a retain cycle. 15909 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15910 // Only check instance methods whose selector looks like a setter. 15911 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15912 return; 15913 15914 // Try to find a variable that the receiver is strongly owned by. 15915 RetainCycleOwner owner; 15916 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15917 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15918 return; 15919 } else { 15920 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15921 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15922 owner.Loc = msg->getSuperLoc(); 15923 owner.Range = msg->getSuperLoc(); 15924 } 15925 15926 // Check whether the receiver is captured by any of the arguments. 15927 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15928 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15929 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15930 // noescape blocks should not be retained by the method. 15931 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15932 continue; 15933 return diagnoseRetainCycle(*this, capturer, owner); 15934 } 15935 } 15936 } 15937 15938 /// Check a property assign to see if it's likely to cause a retain cycle. 15939 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15940 RetainCycleOwner owner; 15941 if (!findRetainCycleOwner(*this, receiver, owner)) 15942 return; 15943 15944 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15945 diagnoseRetainCycle(*this, capturer, owner); 15946 } 15947 15948 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15949 RetainCycleOwner Owner; 15950 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15951 return; 15952 15953 // Because we don't have an expression for the variable, we have to set the 15954 // location explicitly here. 15955 Owner.Loc = Var->getLocation(); 15956 Owner.Range = Var->getSourceRange(); 15957 15958 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15959 diagnoseRetainCycle(*this, Capturer, Owner); 15960 } 15961 15962 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15963 Expr *RHS, bool isProperty) { 15964 // Check if RHS is an Objective-C object literal, which also can get 15965 // immediately zapped in a weak reference. Note that we explicitly 15966 // allow ObjCStringLiterals, since those are designed to never really die. 15967 RHS = RHS->IgnoreParenImpCasts(); 15968 15969 // This enum needs to match with the 'select' in 15970 // warn_objc_arc_literal_assign (off-by-1). 15971 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15972 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15973 return false; 15974 15975 S.Diag(Loc, diag::warn_arc_literal_assign) 15976 << (unsigned) Kind 15977 << (isProperty ? 0 : 1) 15978 << RHS->getSourceRange(); 15979 15980 return true; 15981 } 15982 15983 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15984 Qualifiers::ObjCLifetime LT, 15985 Expr *RHS, bool isProperty) { 15986 // Strip off any implicit cast added to get to the one ARC-specific. 15987 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15988 if (cast->getCastKind() == CK_ARCConsumeObject) { 15989 S.Diag(Loc, diag::warn_arc_retained_assign) 15990 << (LT == Qualifiers::OCL_ExplicitNone) 15991 << (isProperty ? 0 : 1) 15992 << RHS->getSourceRange(); 15993 return true; 15994 } 15995 RHS = cast->getSubExpr(); 15996 } 15997 15998 if (LT == Qualifiers::OCL_Weak && 15999 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 16000 return true; 16001 16002 return false; 16003 } 16004 16005 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 16006 QualType LHS, Expr *RHS) { 16007 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 16008 16009 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 16010 return false; 16011 16012 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 16013 return true; 16014 16015 return false; 16016 } 16017 16018 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 16019 Expr *LHS, Expr *RHS) { 16020 QualType LHSType; 16021 // PropertyRef on LHS type need be directly obtained from 16022 // its declaration as it has a PseudoType. 16023 ObjCPropertyRefExpr *PRE 16024 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 16025 if (PRE && !PRE->isImplicitProperty()) { 16026 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 16027 if (PD) 16028 LHSType = PD->getType(); 16029 } 16030 16031 if (LHSType.isNull()) 16032 LHSType = LHS->getType(); 16033 16034 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 16035 16036 if (LT == Qualifiers::OCL_Weak) { 16037 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 16038 getCurFunction()->markSafeWeakUse(LHS); 16039 } 16040 16041 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 16042 return; 16043 16044 // FIXME. Check for other life times. 16045 if (LT != Qualifiers::OCL_None) 16046 return; 16047 16048 if (PRE) { 16049 if (PRE->isImplicitProperty()) 16050 return; 16051 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 16052 if (!PD) 16053 return; 16054 16055 unsigned Attributes = PD->getPropertyAttributes(); 16056 if (Attributes & ObjCPropertyAttribute::kind_assign) { 16057 // when 'assign' attribute was not explicitly specified 16058 // by user, ignore it and rely on property type itself 16059 // for lifetime info. 16060 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 16061 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 16062 LHSType->isObjCRetainableType()) 16063 return; 16064 16065 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 16066 if (cast->getCastKind() == CK_ARCConsumeObject) { 16067 Diag(Loc, diag::warn_arc_retained_property_assign) 16068 << RHS->getSourceRange(); 16069 return; 16070 } 16071 RHS = cast->getSubExpr(); 16072 } 16073 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 16074 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 16075 return; 16076 } 16077 } 16078 } 16079 16080 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 16081 16082 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 16083 SourceLocation StmtLoc, 16084 const NullStmt *Body) { 16085 // Do not warn if the body is a macro that expands to nothing, e.g: 16086 // 16087 // #define CALL(x) 16088 // if (condition) 16089 // CALL(0); 16090 if (Body->hasLeadingEmptyMacro()) 16091 return false; 16092 16093 // Get line numbers of statement and body. 16094 bool StmtLineInvalid; 16095 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 16096 &StmtLineInvalid); 16097 if (StmtLineInvalid) 16098 return false; 16099 16100 bool BodyLineInvalid; 16101 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 16102 &BodyLineInvalid); 16103 if (BodyLineInvalid) 16104 return false; 16105 16106 // Warn if null statement and body are on the same line. 16107 if (StmtLine != BodyLine) 16108 return false; 16109 16110 return true; 16111 } 16112 16113 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 16114 const Stmt *Body, 16115 unsigned DiagID) { 16116 // Since this is a syntactic check, don't emit diagnostic for template 16117 // instantiations, this just adds noise. 16118 if (CurrentInstantiationScope) 16119 return; 16120 16121 // The body should be a null statement. 16122 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 16123 if (!NBody) 16124 return; 16125 16126 // Do the usual checks. 16127 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 16128 return; 16129 16130 Diag(NBody->getSemiLoc(), DiagID); 16131 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 16132 } 16133 16134 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 16135 const Stmt *PossibleBody) { 16136 assert(!CurrentInstantiationScope); // Ensured by caller 16137 16138 SourceLocation StmtLoc; 16139 const Stmt *Body; 16140 unsigned DiagID; 16141 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 16142 StmtLoc = FS->getRParenLoc(); 16143 Body = FS->getBody(); 16144 DiagID = diag::warn_empty_for_body; 16145 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 16146 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 16147 Body = WS->getBody(); 16148 DiagID = diag::warn_empty_while_body; 16149 } else 16150 return; // Neither `for' nor `while'. 16151 16152 // The body should be a null statement. 16153 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 16154 if (!NBody) 16155 return; 16156 16157 // Skip expensive checks if diagnostic is disabled. 16158 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 16159 return; 16160 16161 // Do the usual checks. 16162 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 16163 return; 16164 16165 // `for(...);' and `while(...);' are popular idioms, so in order to keep 16166 // noise level low, emit diagnostics only if for/while is followed by a 16167 // CompoundStmt, e.g.: 16168 // for (int i = 0; i < n; i++); 16169 // { 16170 // a(i); 16171 // } 16172 // or if for/while is followed by a statement with more indentation 16173 // than for/while itself: 16174 // for (int i = 0; i < n; i++); 16175 // a(i); 16176 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 16177 if (!ProbableTypo) { 16178 bool BodyColInvalid; 16179 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 16180 PossibleBody->getBeginLoc(), &BodyColInvalid); 16181 if (BodyColInvalid) 16182 return; 16183 16184 bool StmtColInvalid; 16185 unsigned StmtCol = 16186 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 16187 if (StmtColInvalid) 16188 return; 16189 16190 if (BodyCol > StmtCol) 16191 ProbableTypo = true; 16192 } 16193 16194 if (ProbableTypo) { 16195 Diag(NBody->getSemiLoc(), DiagID); 16196 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 16197 } 16198 } 16199 16200 //===--- CHECK: Warn on self move with std::move. -------------------------===// 16201 16202 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 16203 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 16204 SourceLocation OpLoc) { 16205 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 16206 return; 16207 16208 if (inTemplateInstantiation()) 16209 return; 16210 16211 // Strip parens and casts away. 16212 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 16213 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 16214 16215 // Check for a call expression 16216 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 16217 if (!CE || CE->getNumArgs() != 1) 16218 return; 16219 16220 // Check for a call to std::move 16221 if (!CE->isCallToStdMove()) 16222 return; 16223 16224 // Get argument from std::move 16225 RHSExpr = CE->getArg(0); 16226 16227 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 16228 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 16229 16230 // Two DeclRefExpr's, check that the decls are the same. 16231 if (LHSDeclRef && RHSDeclRef) { 16232 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16233 return; 16234 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16235 RHSDeclRef->getDecl()->getCanonicalDecl()) 16236 return; 16237 16238 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16239 << LHSExpr->getSourceRange() 16240 << RHSExpr->getSourceRange(); 16241 return; 16242 } 16243 16244 // Member variables require a different approach to check for self moves. 16245 // MemberExpr's are the same if every nested MemberExpr refers to the same 16246 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 16247 // the base Expr's are CXXThisExpr's. 16248 const Expr *LHSBase = LHSExpr; 16249 const Expr *RHSBase = RHSExpr; 16250 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 16251 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 16252 if (!LHSME || !RHSME) 16253 return; 16254 16255 while (LHSME && RHSME) { 16256 if (LHSME->getMemberDecl()->getCanonicalDecl() != 16257 RHSME->getMemberDecl()->getCanonicalDecl()) 16258 return; 16259 16260 LHSBase = LHSME->getBase(); 16261 RHSBase = RHSME->getBase(); 16262 LHSME = dyn_cast<MemberExpr>(LHSBase); 16263 RHSME = dyn_cast<MemberExpr>(RHSBase); 16264 } 16265 16266 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 16267 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 16268 if (LHSDeclRef && RHSDeclRef) { 16269 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16270 return; 16271 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16272 RHSDeclRef->getDecl()->getCanonicalDecl()) 16273 return; 16274 16275 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16276 << LHSExpr->getSourceRange() 16277 << RHSExpr->getSourceRange(); 16278 return; 16279 } 16280 16281 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 16282 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16283 << LHSExpr->getSourceRange() 16284 << RHSExpr->getSourceRange(); 16285 } 16286 16287 //===--- Layout compatibility ----------------------------------------------// 16288 16289 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 16290 16291 /// Check if two enumeration types are layout-compatible. 16292 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 16293 // C++11 [dcl.enum] p8: 16294 // Two enumeration types are layout-compatible if they have the same 16295 // underlying type. 16296 return ED1->isComplete() && ED2->isComplete() && 16297 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 16298 } 16299 16300 /// Check if two fields are layout-compatible. 16301 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 16302 FieldDecl *Field2) { 16303 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 16304 return false; 16305 16306 if (Field1->isBitField() != Field2->isBitField()) 16307 return false; 16308 16309 if (Field1->isBitField()) { 16310 // Make sure that the bit-fields are the same length. 16311 unsigned Bits1 = Field1->getBitWidthValue(C); 16312 unsigned Bits2 = Field2->getBitWidthValue(C); 16313 16314 if (Bits1 != Bits2) 16315 return false; 16316 } 16317 16318 return true; 16319 } 16320 16321 /// Check if two standard-layout structs are layout-compatible. 16322 /// (C++11 [class.mem] p17) 16323 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 16324 RecordDecl *RD2) { 16325 // If both records are C++ classes, check that base classes match. 16326 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 16327 // If one of records is a CXXRecordDecl we are in C++ mode, 16328 // thus the other one is a CXXRecordDecl, too. 16329 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 16330 // Check number of base classes. 16331 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 16332 return false; 16333 16334 // Check the base classes. 16335 for (CXXRecordDecl::base_class_const_iterator 16336 Base1 = D1CXX->bases_begin(), 16337 BaseEnd1 = D1CXX->bases_end(), 16338 Base2 = D2CXX->bases_begin(); 16339 Base1 != BaseEnd1; 16340 ++Base1, ++Base2) { 16341 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 16342 return false; 16343 } 16344 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 16345 // If only RD2 is a C++ class, it should have zero base classes. 16346 if (D2CXX->getNumBases() > 0) 16347 return false; 16348 } 16349 16350 // Check the fields. 16351 RecordDecl::field_iterator Field2 = RD2->field_begin(), 16352 Field2End = RD2->field_end(), 16353 Field1 = RD1->field_begin(), 16354 Field1End = RD1->field_end(); 16355 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 16356 if (!isLayoutCompatible(C, *Field1, *Field2)) 16357 return false; 16358 } 16359 if (Field1 != Field1End || Field2 != Field2End) 16360 return false; 16361 16362 return true; 16363 } 16364 16365 /// Check if two standard-layout unions are layout-compatible. 16366 /// (C++11 [class.mem] p18) 16367 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 16368 RecordDecl *RD2) { 16369 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 16370 for (auto *Field2 : RD2->fields()) 16371 UnmatchedFields.insert(Field2); 16372 16373 for (auto *Field1 : RD1->fields()) { 16374 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 16375 I = UnmatchedFields.begin(), 16376 E = UnmatchedFields.end(); 16377 16378 for ( ; I != E; ++I) { 16379 if (isLayoutCompatible(C, Field1, *I)) { 16380 bool Result = UnmatchedFields.erase(*I); 16381 (void) Result; 16382 assert(Result); 16383 break; 16384 } 16385 } 16386 if (I == E) 16387 return false; 16388 } 16389 16390 return UnmatchedFields.empty(); 16391 } 16392 16393 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 16394 RecordDecl *RD2) { 16395 if (RD1->isUnion() != RD2->isUnion()) 16396 return false; 16397 16398 if (RD1->isUnion()) 16399 return isLayoutCompatibleUnion(C, RD1, RD2); 16400 else 16401 return isLayoutCompatibleStruct(C, RD1, RD2); 16402 } 16403 16404 /// Check if two types are layout-compatible in C++11 sense. 16405 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 16406 if (T1.isNull() || T2.isNull()) 16407 return false; 16408 16409 // C++11 [basic.types] p11: 16410 // If two types T1 and T2 are the same type, then T1 and T2 are 16411 // layout-compatible types. 16412 if (C.hasSameType(T1, T2)) 16413 return true; 16414 16415 T1 = T1.getCanonicalType().getUnqualifiedType(); 16416 T2 = T2.getCanonicalType().getUnqualifiedType(); 16417 16418 const Type::TypeClass TC1 = T1->getTypeClass(); 16419 const Type::TypeClass TC2 = T2->getTypeClass(); 16420 16421 if (TC1 != TC2) 16422 return false; 16423 16424 if (TC1 == Type::Enum) { 16425 return isLayoutCompatible(C, 16426 cast<EnumType>(T1)->getDecl(), 16427 cast<EnumType>(T2)->getDecl()); 16428 } else if (TC1 == Type::Record) { 16429 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 16430 return false; 16431 16432 return isLayoutCompatible(C, 16433 cast<RecordType>(T1)->getDecl(), 16434 cast<RecordType>(T2)->getDecl()); 16435 } 16436 16437 return false; 16438 } 16439 16440 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 16441 16442 /// Given a type tag expression find the type tag itself. 16443 /// 16444 /// \param TypeExpr Type tag expression, as it appears in user's code. 16445 /// 16446 /// \param VD Declaration of an identifier that appears in a type tag. 16447 /// 16448 /// \param MagicValue Type tag magic value. 16449 /// 16450 /// \param isConstantEvaluated whether the evalaution should be performed in 16451 16452 /// constant context. 16453 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 16454 const ValueDecl **VD, uint64_t *MagicValue, 16455 bool isConstantEvaluated) { 16456 while(true) { 16457 if (!TypeExpr) 16458 return false; 16459 16460 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 16461 16462 switch (TypeExpr->getStmtClass()) { 16463 case Stmt::UnaryOperatorClass: { 16464 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 16465 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 16466 TypeExpr = UO->getSubExpr(); 16467 continue; 16468 } 16469 return false; 16470 } 16471 16472 case Stmt::DeclRefExprClass: { 16473 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 16474 *VD = DRE->getDecl(); 16475 return true; 16476 } 16477 16478 case Stmt::IntegerLiteralClass: { 16479 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 16480 llvm::APInt MagicValueAPInt = IL->getValue(); 16481 if (MagicValueAPInt.getActiveBits() <= 64) { 16482 *MagicValue = MagicValueAPInt.getZExtValue(); 16483 return true; 16484 } else 16485 return false; 16486 } 16487 16488 case Stmt::BinaryConditionalOperatorClass: 16489 case Stmt::ConditionalOperatorClass: { 16490 const AbstractConditionalOperator *ACO = 16491 cast<AbstractConditionalOperator>(TypeExpr); 16492 bool Result; 16493 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 16494 isConstantEvaluated)) { 16495 if (Result) 16496 TypeExpr = ACO->getTrueExpr(); 16497 else 16498 TypeExpr = ACO->getFalseExpr(); 16499 continue; 16500 } 16501 return false; 16502 } 16503 16504 case Stmt::BinaryOperatorClass: { 16505 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 16506 if (BO->getOpcode() == BO_Comma) { 16507 TypeExpr = BO->getRHS(); 16508 continue; 16509 } 16510 return false; 16511 } 16512 16513 default: 16514 return false; 16515 } 16516 } 16517 } 16518 16519 /// Retrieve the C type corresponding to type tag TypeExpr. 16520 /// 16521 /// \param TypeExpr Expression that specifies a type tag. 16522 /// 16523 /// \param MagicValues Registered magic values. 16524 /// 16525 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 16526 /// kind. 16527 /// 16528 /// \param TypeInfo Information about the corresponding C type. 16529 /// 16530 /// \param isConstantEvaluated whether the evalaution should be performed in 16531 /// constant context. 16532 /// 16533 /// \returns true if the corresponding C type was found. 16534 static bool GetMatchingCType( 16535 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 16536 const ASTContext &Ctx, 16537 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 16538 *MagicValues, 16539 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 16540 bool isConstantEvaluated) { 16541 FoundWrongKind = false; 16542 16543 // Variable declaration that has type_tag_for_datatype attribute. 16544 const ValueDecl *VD = nullptr; 16545 16546 uint64_t MagicValue; 16547 16548 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 16549 return false; 16550 16551 if (VD) { 16552 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 16553 if (I->getArgumentKind() != ArgumentKind) { 16554 FoundWrongKind = true; 16555 return false; 16556 } 16557 TypeInfo.Type = I->getMatchingCType(); 16558 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 16559 TypeInfo.MustBeNull = I->getMustBeNull(); 16560 return true; 16561 } 16562 return false; 16563 } 16564 16565 if (!MagicValues) 16566 return false; 16567 16568 llvm::DenseMap<Sema::TypeTagMagicValue, 16569 Sema::TypeTagData>::const_iterator I = 16570 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 16571 if (I == MagicValues->end()) 16572 return false; 16573 16574 TypeInfo = I->second; 16575 return true; 16576 } 16577 16578 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 16579 uint64_t MagicValue, QualType Type, 16580 bool LayoutCompatible, 16581 bool MustBeNull) { 16582 if (!TypeTagForDatatypeMagicValues) 16583 TypeTagForDatatypeMagicValues.reset( 16584 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 16585 16586 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 16587 (*TypeTagForDatatypeMagicValues)[Magic] = 16588 TypeTagData(Type, LayoutCompatible, MustBeNull); 16589 } 16590 16591 static bool IsSameCharType(QualType T1, QualType T2) { 16592 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 16593 if (!BT1) 16594 return false; 16595 16596 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 16597 if (!BT2) 16598 return false; 16599 16600 BuiltinType::Kind T1Kind = BT1->getKind(); 16601 BuiltinType::Kind T2Kind = BT2->getKind(); 16602 16603 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 16604 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 16605 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 16606 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 16607 } 16608 16609 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 16610 const ArrayRef<const Expr *> ExprArgs, 16611 SourceLocation CallSiteLoc) { 16612 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 16613 bool IsPointerAttr = Attr->getIsPointer(); 16614 16615 // Retrieve the argument representing the 'type_tag'. 16616 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 16617 if (TypeTagIdxAST >= ExprArgs.size()) { 16618 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16619 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 16620 return; 16621 } 16622 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 16623 bool FoundWrongKind; 16624 TypeTagData TypeInfo; 16625 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 16626 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 16627 TypeInfo, isConstantEvaluated())) { 16628 if (FoundWrongKind) 16629 Diag(TypeTagExpr->getExprLoc(), 16630 diag::warn_type_tag_for_datatype_wrong_kind) 16631 << TypeTagExpr->getSourceRange(); 16632 return; 16633 } 16634 16635 // Retrieve the argument representing the 'arg_idx'. 16636 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 16637 if (ArgumentIdxAST >= ExprArgs.size()) { 16638 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16639 << 1 << Attr->getArgumentIdx().getSourceIndex(); 16640 return; 16641 } 16642 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 16643 if (IsPointerAttr) { 16644 // Skip implicit cast of pointer to `void *' (as a function argument). 16645 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 16646 if (ICE->getType()->isVoidPointerType() && 16647 ICE->getCastKind() == CK_BitCast) 16648 ArgumentExpr = ICE->getSubExpr(); 16649 } 16650 QualType ArgumentType = ArgumentExpr->getType(); 16651 16652 // Passing a `void*' pointer shouldn't trigger a warning. 16653 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 16654 return; 16655 16656 if (TypeInfo.MustBeNull) { 16657 // Type tag with matching void type requires a null pointer. 16658 if (!ArgumentExpr->isNullPointerConstant(Context, 16659 Expr::NPC_ValueDependentIsNotNull)) { 16660 Diag(ArgumentExpr->getExprLoc(), 16661 diag::warn_type_safety_null_pointer_required) 16662 << ArgumentKind->getName() 16663 << ArgumentExpr->getSourceRange() 16664 << TypeTagExpr->getSourceRange(); 16665 } 16666 return; 16667 } 16668 16669 QualType RequiredType = TypeInfo.Type; 16670 if (IsPointerAttr) 16671 RequiredType = Context.getPointerType(RequiredType); 16672 16673 bool mismatch = false; 16674 if (!TypeInfo.LayoutCompatible) { 16675 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 16676 16677 // C++11 [basic.fundamental] p1: 16678 // Plain char, signed char, and unsigned char are three distinct types. 16679 // 16680 // But we treat plain `char' as equivalent to `signed char' or `unsigned 16681 // char' depending on the current char signedness mode. 16682 if (mismatch) 16683 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 16684 RequiredType->getPointeeType())) || 16685 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 16686 mismatch = false; 16687 } else 16688 if (IsPointerAttr) 16689 mismatch = !isLayoutCompatible(Context, 16690 ArgumentType->getPointeeType(), 16691 RequiredType->getPointeeType()); 16692 else 16693 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 16694 16695 if (mismatch) 16696 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 16697 << ArgumentType << ArgumentKind 16698 << TypeInfo.LayoutCompatible << RequiredType 16699 << ArgumentExpr->getSourceRange() 16700 << TypeTagExpr->getSourceRange(); 16701 } 16702 16703 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 16704 CharUnits Alignment) { 16705 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16706 } 16707 16708 void Sema::DiagnoseMisalignedMembers() { 16709 for (MisalignedMember &m : MisalignedMembers) { 16710 const NamedDecl *ND = m.RD; 16711 if (ND->getName().empty()) { 16712 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16713 ND = TD; 16714 } 16715 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16716 << m.MD << ND << m.E->getSourceRange(); 16717 } 16718 MisalignedMembers.clear(); 16719 } 16720 16721 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16722 E = E->IgnoreParens(); 16723 if (!T->isPointerType() && !T->isIntegerType()) 16724 return; 16725 if (isa<UnaryOperator>(E) && 16726 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16727 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16728 if (isa<MemberExpr>(Op)) { 16729 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16730 if (MA != MisalignedMembers.end() && 16731 (T->isIntegerType() || 16732 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16733 Context.getTypeAlignInChars( 16734 T->getPointeeType()) <= MA->Alignment)))) 16735 MisalignedMembers.erase(MA); 16736 } 16737 } 16738 } 16739 16740 void Sema::RefersToMemberWithReducedAlignment( 16741 Expr *E, 16742 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16743 Action) { 16744 const auto *ME = dyn_cast<MemberExpr>(E); 16745 if (!ME) 16746 return; 16747 16748 // No need to check expressions with an __unaligned-qualified type. 16749 if (E->getType().getQualifiers().hasUnaligned()) 16750 return; 16751 16752 // For a chain of MemberExpr like "a.b.c.d" this list 16753 // will keep FieldDecl's like [d, c, b]. 16754 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16755 const MemberExpr *TopME = nullptr; 16756 bool AnyIsPacked = false; 16757 do { 16758 QualType BaseType = ME->getBase()->getType(); 16759 if (BaseType->isDependentType()) 16760 return; 16761 if (ME->isArrow()) 16762 BaseType = BaseType->getPointeeType(); 16763 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16764 if (RD->isInvalidDecl()) 16765 return; 16766 16767 ValueDecl *MD = ME->getMemberDecl(); 16768 auto *FD = dyn_cast<FieldDecl>(MD); 16769 // We do not care about non-data members. 16770 if (!FD || FD->isInvalidDecl()) 16771 return; 16772 16773 AnyIsPacked = 16774 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16775 ReverseMemberChain.push_back(FD); 16776 16777 TopME = ME; 16778 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16779 } while (ME); 16780 assert(TopME && "We did not compute a topmost MemberExpr!"); 16781 16782 // Not the scope of this diagnostic. 16783 if (!AnyIsPacked) 16784 return; 16785 16786 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 16787 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 16788 // TODO: The innermost base of the member expression may be too complicated. 16789 // For now, just disregard these cases. This is left for future 16790 // improvement. 16791 if (!DRE && !isa<CXXThisExpr>(TopBase)) 16792 return; 16793 16794 // Alignment expected by the whole expression. 16795 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 16796 16797 // No need to do anything else with this case. 16798 if (ExpectedAlignment.isOne()) 16799 return; 16800 16801 // Synthesize offset of the whole access. 16802 CharUnits Offset; 16803 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain)) 16804 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD)); 16805 16806 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 16807 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 16808 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 16809 16810 // The base expression of the innermost MemberExpr may give 16811 // stronger guarantees than the class containing the member. 16812 if (DRE && !TopME->isArrow()) { 16813 const ValueDecl *VD = DRE->getDecl(); 16814 if (!VD->getType()->isReferenceType()) 16815 CompleteObjectAlignment = 16816 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 16817 } 16818 16819 // Check if the synthesized offset fulfills the alignment. 16820 if (Offset % ExpectedAlignment != 0 || 16821 // It may fulfill the offset it but the effective alignment may still be 16822 // lower than the expected expression alignment. 16823 CompleteObjectAlignment < ExpectedAlignment) { 16824 // If this happens, we want to determine a sensible culprit of this. 16825 // Intuitively, watching the chain of member expressions from right to 16826 // left, we start with the required alignment (as required by the field 16827 // type) but some packed attribute in that chain has reduced the alignment. 16828 // It may happen that another packed structure increases it again. But if 16829 // we are here such increase has not been enough. So pointing the first 16830 // FieldDecl that either is packed or else its RecordDecl is, 16831 // seems reasonable. 16832 FieldDecl *FD = nullptr; 16833 CharUnits Alignment; 16834 for (FieldDecl *FDI : ReverseMemberChain) { 16835 if (FDI->hasAttr<PackedAttr>() || 16836 FDI->getParent()->hasAttr<PackedAttr>()) { 16837 FD = FDI; 16838 Alignment = std::min( 16839 Context.getTypeAlignInChars(FD->getType()), 16840 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 16841 break; 16842 } 16843 } 16844 assert(FD && "We did not find a packed FieldDecl!"); 16845 Action(E, FD->getParent(), FD, Alignment); 16846 } 16847 } 16848 16849 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 16850 using namespace std::placeholders; 16851 16852 RefersToMemberWithReducedAlignment( 16853 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 16854 _2, _3, _4)); 16855 } 16856 16857 // Check if \p Ty is a valid type for the elementwise math builtins. If it is 16858 // not a valid type, emit an error message and return true. Otherwise return 16859 // false. 16860 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, 16861 QualType Ty) { 16862 if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) { 16863 S.Diag(Loc, diag::err_builtin_invalid_arg_type) 16864 << 1 << /* vector, integer or float ty*/ 0 << Ty; 16865 return true; 16866 } 16867 return false; 16868 } 16869 16870 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) { 16871 if (checkArgCount(*this, TheCall, 1)) 16872 return true; 16873 16874 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 16875 if (A.isInvalid()) 16876 return true; 16877 16878 TheCall->setArg(0, A.get()); 16879 QualType TyA = A.get()->getType(); 16880 16881 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA)) 16882 return true; 16883 16884 TheCall->setType(TyA); 16885 return false; 16886 } 16887 16888 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) { 16889 if (checkArgCount(*this, TheCall, 2)) 16890 return true; 16891 16892 ExprResult A = TheCall->getArg(0); 16893 ExprResult B = TheCall->getArg(1); 16894 // Do standard promotions between the two arguments, returning their common 16895 // type. 16896 QualType Res = 16897 UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison); 16898 if (A.isInvalid() || B.isInvalid()) 16899 return true; 16900 16901 QualType TyA = A.get()->getType(); 16902 QualType TyB = B.get()->getType(); 16903 16904 if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType()) 16905 return Diag(A.get()->getBeginLoc(), 16906 diag::err_typecheck_call_different_arg_types) 16907 << TyA << TyB; 16908 16909 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA)) 16910 return true; 16911 16912 TheCall->setArg(0, A.get()); 16913 TheCall->setArg(1, B.get()); 16914 TheCall->setType(Res); 16915 return false; 16916 } 16917 16918 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) { 16919 if (checkArgCount(*this, TheCall, 1)) 16920 return true; 16921 16922 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 16923 if (A.isInvalid()) 16924 return true; 16925 16926 TheCall->setArg(0, A.get()); 16927 return false; 16928 } 16929 16930 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 16931 ExprResult CallResult) { 16932 if (checkArgCount(*this, TheCall, 1)) 16933 return ExprError(); 16934 16935 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 16936 if (MatrixArg.isInvalid()) 16937 return MatrixArg; 16938 Expr *Matrix = MatrixArg.get(); 16939 16940 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 16941 if (!MType) { 16942 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16943 << 1 << /* matrix ty*/ 1 << Matrix->getType(); 16944 return ExprError(); 16945 } 16946 16947 // Create returned matrix type by swapping rows and columns of the argument 16948 // matrix type. 16949 QualType ResultType = Context.getConstantMatrixType( 16950 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 16951 16952 // Change the return type to the type of the returned matrix. 16953 TheCall->setType(ResultType); 16954 16955 // Update call argument to use the possibly converted matrix argument. 16956 TheCall->setArg(0, Matrix); 16957 return CallResult; 16958 } 16959 16960 // Get and verify the matrix dimensions. 16961 static llvm::Optional<unsigned> 16962 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16963 SourceLocation ErrorPos; 16964 Optional<llvm::APSInt> Value = 16965 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16966 if (!Value) { 16967 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16968 << Name; 16969 return {}; 16970 } 16971 uint64_t Dim = Value->getZExtValue(); 16972 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16973 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16974 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16975 return {}; 16976 } 16977 return Dim; 16978 } 16979 16980 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16981 ExprResult CallResult) { 16982 if (!getLangOpts().MatrixTypes) { 16983 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16984 return ExprError(); 16985 } 16986 16987 if (checkArgCount(*this, TheCall, 4)) 16988 return ExprError(); 16989 16990 unsigned PtrArgIdx = 0; 16991 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16992 Expr *RowsExpr = TheCall->getArg(1); 16993 Expr *ColumnsExpr = TheCall->getArg(2); 16994 Expr *StrideExpr = TheCall->getArg(3); 16995 16996 bool ArgError = false; 16997 16998 // Check pointer argument. 16999 { 17000 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 17001 if (PtrConv.isInvalid()) 17002 return PtrConv; 17003 PtrExpr = PtrConv.get(); 17004 TheCall->setArg(0, PtrExpr); 17005 if (PtrExpr->isTypeDependent()) { 17006 TheCall->setType(Context.DependentTy); 17007 return TheCall; 17008 } 17009 } 17010 17011 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 17012 QualType ElementTy; 17013 if (!PtrTy) { 17014 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17015 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 17016 ArgError = true; 17017 } else { 17018 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 17019 17020 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 17021 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17022 << PtrArgIdx + 1 << /* pointer to element ty*/ 2 17023 << PtrExpr->getType(); 17024 ArgError = true; 17025 } 17026 } 17027 17028 // Apply default Lvalue conversions and convert the expression to size_t. 17029 auto ApplyArgumentConversions = [this](Expr *E) { 17030 ExprResult Conv = DefaultLvalueConversion(E); 17031 if (Conv.isInvalid()) 17032 return Conv; 17033 17034 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 17035 }; 17036 17037 // Apply conversion to row and column expressions. 17038 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 17039 if (!RowsConv.isInvalid()) { 17040 RowsExpr = RowsConv.get(); 17041 TheCall->setArg(1, RowsExpr); 17042 } else 17043 RowsExpr = nullptr; 17044 17045 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 17046 if (!ColumnsConv.isInvalid()) { 17047 ColumnsExpr = ColumnsConv.get(); 17048 TheCall->setArg(2, ColumnsExpr); 17049 } else 17050 ColumnsExpr = nullptr; 17051 17052 // If any any part of the result matrix type is still pending, just use 17053 // Context.DependentTy, until all parts are resolved. 17054 if ((RowsExpr && RowsExpr->isTypeDependent()) || 17055 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 17056 TheCall->setType(Context.DependentTy); 17057 return CallResult; 17058 } 17059 17060 // Check row and column dimensions. 17061 llvm::Optional<unsigned> MaybeRows; 17062 if (RowsExpr) 17063 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 17064 17065 llvm::Optional<unsigned> MaybeColumns; 17066 if (ColumnsExpr) 17067 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 17068 17069 // Check stride argument. 17070 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 17071 if (StrideConv.isInvalid()) 17072 return ExprError(); 17073 StrideExpr = StrideConv.get(); 17074 TheCall->setArg(3, StrideExpr); 17075 17076 if (MaybeRows) { 17077 if (Optional<llvm::APSInt> Value = 17078 StrideExpr->getIntegerConstantExpr(Context)) { 17079 uint64_t Stride = Value->getZExtValue(); 17080 if (Stride < *MaybeRows) { 17081 Diag(StrideExpr->getBeginLoc(), 17082 diag::err_builtin_matrix_stride_too_small); 17083 ArgError = true; 17084 } 17085 } 17086 } 17087 17088 if (ArgError || !MaybeRows || !MaybeColumns) 17089 return ExprError(); 17090 17091 TheCall->setType( 17092 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 17093 return CallResult; 17094 } 17095 17096 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 17097 ExprResult CallResult) { 17098 if (checkArgCount(*this, TheCall, 3)) 17099 return ExprError(); 17100 17101 unsigned PtrArgIdx = 1; 17102 Expr *MatrixExpr = TheCall->getArg(0); 17103 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 17104 Expr *StrideExpr = TheCall->getArg(2); 17105 17106 bool ArgError = false; 17107 17108 { 17109 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 17110 if (MatrixConv.isInvalid()) 17111 return MatrixConv; 17112 MatrixExpr = MatrixConv.get(); 17113 TheCall->setArg(0, MatrixExpr); 17114 } 17115 if (MatrixExpr->isTypeDependent()) { 17116 TheCall->setType(Context.DependentTy); 17117 return TheCall; 17118 } 17119 17120 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 17121 if (!MatrixTy) { 17122 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17123 << 1 << /*matrix ty */ 1 << MatrixExpr->getType(); 17124 ArgError = true; 17125 } 17126 17127 { 17128 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 17129 if (PtrConv.isInvalid()) 17130 return PtrConv; 17131 PtrExpr = PtrConv.get(); 17132 TheCall->setArg(1, PtrExpr); 17133 if (PtrExpr->isTypeDependent()) { 17134 TheCall->setType(Context.DependentTy); 17135 return TheCall; 17136 } 17137 } 17138 17139 // Check pointer argument. 17140 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 17141 if (!PtrTy) { 17142 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17143 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 17144 ArgError = true; 17145 } else { 17146 QualType ElementTy = PtrTy->getPointeeType(); 17147 if (ElementTy.isConstQualified()) { 17148 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 17149 ArgError = true; 17150 } 17151 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 17152 if (MatrixTy && 17153 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 17154 Diag(PtrExpr->getBeginLoc(), 17155 diag::err_builtin_matrix_pointer_arg_mismatch) 17156 << ElementTy << MatrixTy->getElementType(); 17157 ArgError = true; 17158 } 17159 } 17160 17161 // Apply default Lvalue conversions and convert the stride expression to 17162 // size_t. 17163 { 17164 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 17165 if (StrideConv.isInvalid()) 17166 return StrideConv; 17167 17168 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 17169 if (StrideConv.isInvalid()) 17170 return StrideConv; 17171 StrideExpr = StrideConv.get(); 17172 TheCall->setArg(2, StrideExpr); 17173 } 17174 17175 // Check stride argument. 17176 if (MatrixTy) { 17177 if (Optional<llvm::APSInt> Value = 17178 StrideExpr->getIntegerConstantExpr(Context)) { 17179 uint64_t Stride = Value->getZExtValue(); 17180 if (Stride < MatrixTy->getNumRows()) { 17181 Diag(StrideExpr->getBeginLoc(), 17182 diag::err_builtin_matrix_stride_too_small); 17183 ArgError = true; 17184 } 17185 } 17186 } 17187 17188 if (ArgError) 17189 return ExprError(); 17190 17191 return CallResult; 17192 } 17193 17194 /// \brief Enforce the bounds of a TCB 17195 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 17196 /// directly calls other functions in the same TCB as marked by the enforce_tcb 17197 /// and enforce_tcb_leaf attributes. 17198 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 17199 const FunctionDecl *Callee) { 17200 const FunctionDecl *Caller = getCurFunctionDecl(); 17201 17202 // Calls to builtins are not enforced. 17203 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 17204 Callee->getBuiltinID() != 0) 17205 return; 17206 17207 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 17208 // all TCBs the callee is a part of. 17209 llvm::StringSet<> CalleeTCBs; 17210 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 17211 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 17212 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 17213 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 17214 17215 // Go through the TCBs the caller is a part of and emit warnings if Caller 17216 // is in a TCB that the Callee is not. 17217 for_each( 17218 Caller->specific_attrs<EnforceTCBAttr>(), 17219 [&](const auto *A) { 17220 StringRef CallerTCB = A->getTCBName(); 17221 if (CalleeTCBs.count(CallerTCB) == 0) { 17222 this->Diag(TheCall->getExprLoc(), 17223 diag::warn_tcb_enforcement_violation) << Callee 17224 << CallerTCB; 17225 } 17226 }); 17227 } 17228