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, 503 const TargetInfo &) override { 504 505 const size_t FieldWidth = computeFieldWidth(FS); 506 const size_t Precision = computePrecision(FS); 507 508 // The actual format. 509 switch (FS.getConversionSpecifier().getKind()) { 510 // Just a char. 511 case analyze_format_string::ConversionSpecifier::cArg: 512 case analyze_format_string::ConversionSpecifier::CArg: 513 Size += std::max(FieldWidth, (size_t)1); 514 break; 515 // Just an integer. 516 case analyze_format_string::ConversionSpecifier::dArg: 517 case analyze_format_string::ConversionSpecifier::DArg: 518 case analyze_format_string::ConversionSpecifier::iArg: 519 case analyze_format_string::ConversionSpecifier::oArg: 520 case analyze_format_string::ConversionSpecifier::OArg: 521 case analyze_format_string::ConversionSpecifier::uArg: 522 case analyze_format_string::ConversionSpecifier::UArg: 523 case analyze_format_string::ConversionSpecifier::xArg: 524 case analyze_format_string::ConversionSpecifier::XArg: 525 Size += std::max(FieldWidth, Precision); 526 break; 527 528 // %g style conversion switches between %f or %e style dynamically. 529 // %f always takes less space, so default to it. 530 case analyze_format_string::ConversionSpecifier::gArg: 531 case analyze_format_string::ConversionSpecifier::GArg: 532 533 // Floating point number in the form '[+]ddd.ddd'. 534 case analyze_format_string::ConversionSpecifier::fArg: 535 case analyze_format_string::ConversionSpecifier::FArg: 536 Size += std::max(FieldWidth, 1 /* integer part */ + 537 (Precision ? 1 + Precision 538 : 0) /* period + decimal */); 539 break; 540 541 // Floating point number in the form '[-]d.ddde[+-]dd'. 542 case analyze_format_string::ConversionSpecifier::eArg: 543 case analyze_format_string::ConversionSpecifier::EArg: 544 Size += 545 std::max(FieldWidth, 546 1 /* integer part */ + 547 (Precision ? 1 + Precision : 0) /* period + decimal */ + 548 1 /* e or E letter */ + 2 /* exponent */); 549 break; 550 551 // Floating point number in the form '[-]0xh.hhhhp±dd'. 552 case analyze_format_string::ConversionSpecifier::aArg: 553 case analyze_format_string::ConversionSpecifier::AArg: 554 Size += 555 std::max(FieldWidth, 556 2 /* 0x */ + 1 /* integer part */ + 557 (Precision ? 1 + Precision : 0) /* period + decimal */ + 558 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 559 break; 560 561 // Just a string. 562 case analyze_format_string::ConversionSpecifier::sArg: 563 case analyze_format_string::ConversionSpecifier::SArg: 564 Size += FieldWidth; 565 break; 566 567 // Just a pointer in the form '0xddd'. 568 case analyze_format_string::ConversionSpecifier::pArg: 569 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 570 break; 571 572 // A plain percent. 573 case analyze_format_string::ConversionSpecifier::PercentArg: 574 Size += 1; 575 break; 576 577 default: 578 break; 579 } 580 581 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 582 583 if (FS.hasAlternativeForm()) { 584 switch (FS.getConversionSpecifier().getKind()) { 585 default: 586 break; 587 // Force a leading '0'. 588 case analyze_format_string::ConversionSpecifier::oArg: 589 Size += 1; 590 break; 591 // Force a leading '0x'. 592 case analyze_format_string::ConversionSpecifier::xArg: 593 case analyze_format_string::ConversionSpecifier::XArg: 594 Size += 2; 595 break; 596 // Force a period '.' before decimal, even if precision is 0. 597 case analyze_format_string::ConversionSpecifier::aArg: 598 case analyze_format_string::ConversionSpecifier::AArg: 599 case analyze_format_string::ConversionSpecifier::eArg: 600 case analyze_format_string::ConversionSpecifier::EArg: 601 case analyze_format_string::ConversionSpecifier::fArg: 602 case analyze_format_string::ConversionSpecifier::FArg: 603 case analyze_format_string::ConversionSpecifier::gArg: 604 case analyze_format_string::ConversionSpecifier::GArg: 605 Size += (Precision ? 0 : 1); 606 break; 607 } 608 } 609 assert(SpecifierLen <= Size && "no underflow"); 610 Size -= SpecifierLen; 611 return true; 612 } 613 614 size_t getSizeLowerBound() const { return Size; } 615 616 private: 617 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 618 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 619 size_t FieldWidth = 0; 620 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 621 FieldWidth = FW.getConstantAmount(); 622 return FieldWidth; 623 } 624 625 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 626 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 627 size_t Precision = 0; 628 629 // See man 3 printf for default precision value based on the specifier. 630 switch (FW.getHowSpecified()) { 631 case analyze_format_string::OptionalAmount::NotSpecified: 632 switch (FS.getConversionSpecifier().getKind()) { 633 default: 634 break; 635 case analyze_format_string::ConversionSpecifier::dArg: // %d 636 case analyze_format_string::ConversionSpecifier::DArg: // %D 637 case analyze_format_string::ConversionSpecifier::iArg: // %i 638 Precision = 1; 639 break; 640 case analyze_format_string::ConversionSpecifier::oArg: // %d 641 case analyze_format_string::ConversionSpecifier::OArg: // %D 642 case analyze_format_string::ConversionSpecifier::uArg: // %d 643 case analyze_format_string::ConversionSpecifier::UArg: // %D 644 case analyze_format_string::ConversionSpecifier::xArg: // %d 645 case analyze_format_string::ConversionSpecifier::XArg: // %D 646 Precision = 1; 647 break; 648 case analyze_format_string::ConversionSpecifier::fArg: // %f 649 case analyze_format_string::ConversionSpecifier::FArg: // %F 650 case analyze_format_string::ConversionSpecifier::eArg: // %e 651 case analyze_format_string::ConversionSpecifier::EArg: // %E 652 case analyze_format_string::ConversionSpecifier::gArg: // %g 653 case analyze_format_string::ConversionSpecifier::GArg: // %G 654 Precision = 6; 655 break; 656 case analyze_format_string::ConversionSpecifier::pArg: // %d 657 Precision = 1; 658 break; 659 } 660 break; 661 case analyze_format_string::OptionalAmount::Constant: 662 Precision = FW.getConstantAmount(); 663 break; 664 default: 665 break; 666 } 667 return Precision; 668 } 669 }; 670 671 } // namespace 672 673 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 674 CallExpr *TheCall) { 675 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 676 isConstantEvaluated()) 677 return; 678 679 bool UseDABAttr = false; 680 const FunctionDecl *UseDecl = FD; 681 682 const auto *DABAttr = FD->getAttr<DiagnoseAsBuiltinAttr>(); 683 if (DABAttr) { 684 UseDecl = DABAttr->getFunction(); 685 assert(UseDecl && "Missing FunctionDecl in DiagnoseAsBuiltin attribute!"); 686 UseDABAttr = true; 687 } 688 689 unsigned BuiltinID = UseDecl->getBuiltinID(/*ConsiderWrappers=*/true); 690 691 if (!BuiltinID) 692 return; 693 694 const TargetInfo &TI = getASTContext().getTargetInfo(); 695 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 696 697 auto TranslateIndex = [&](unsigned Index) -> Optional<unsigned> { 698 // If we refer to a diagnose_as_builtin attribute, we need to change the 699 // argument index to refer to the arguments of the called function. Unless 700 // the index is out of bounds, which presumably means it's a variadic 701 // function. 702 if (!UseDABAttr) 703 return Index; 704 unsigned DABIndices = DABAttr->argIndices_size(); 705 unsigned NewIndex = Index < DABIndices 706 ? DABAttr->argIndices_begin()[Index] 707 : Index - DABIndices + FD->getNumParams(); 708 if (NewIndex >= TheCall->getNumArgs()) 709 return llvm::None; 710 return NewIndex; 711 }; 712 713 auto ComputeExplicitObjectSizeArgument = 714 [&](unsigned Index) -> Optional<llvm::APSInt> { 715 Optional<unsigned> IndexOptional = TranslateIndex(Index); 716 if (!IndexOptional) 717 return llvm::None; 718 unsigned NewIndex = IndexOptional.getValue(); 719 Expr::EvalResult Result; 720 Expr *SizeArg = TheCall->getArg(NewIndex); 721 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 722 return llvm::None; 723 llvm::APSInt Integer = Result.Val.getInt(); 724 Integer.setIsUnsigned(true); 725 return Integer; 726 }; 727 728 auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 729 // If the parameter has a pass_object_size attribute, then we should use its 730 // (potentially) more strict checking mode. Otherwise, conservatively assume 731 // type 0. 732 int BOSType = 0; 733 // This check can fail for variadic functions. 734 if (Index < FD->getNumParams()) { 735 if (const auto *POS = 736 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>()) 737 BOSType = POS->getType(); 738 } 739 740 Optional<unsigned> IndexOptional = TranslateIndex(Index); 741 if (!IndexOptional) 742 return llvm::None; 743 unsigned NewIndex = IndexOptional.getValue(); 744 745 const Expr *ObjArg = TheCall->getArg(NewIndex); 746 uint64_t Result; 747 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 748 return llvm::None; 749 750 // Get the object size in the target's size_t width. 751 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 752 }; 753 754 auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 755 Optional<unsigned> IndexOptional = TranslateIndex(Index); 756 if (!IndexOptional) 757 return llvm::None; 758 unsigned NewIndex = IndexOptional.getValue(); 759 760 const Expr *ObjArg = TheCall->getArg(NewIndex); 761 uint64_t Result; 762 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext())) 763 return llvm::None; 764 // Add 1 for null byte. 765 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth); 766 }; 767 768 Optional<llvm::APSInt> SourceSize; 769 Optional<llvm::APSInt> DestinationSize; 770 unsigned DiagID = 0; 771 bool IsChkVariant = false; 772 773 auto GetFunctionName = [&]() { 774 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 775 // Skim off the details of whichever builtin was called to produce a better 776 // diagnostic, as it's unlikely that the user wrote the __builtin 777 // explicitly. 778 if (IsChkVariant) { 779 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 780 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 781 } else if (FunctionName.startswith("__builtin_")) { 782 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 783 } 784 return FunctionName; 785 }; 786 787 switch (BuiltinID) { 788 default: 789 return; 790 case Builtin::BI__builtin_strcpy: 791 case Builtin::BIstrcpy: { 792 DiagID = diag::warn_fortify_strlen_overflow; 793 SourceSize = ComputeStrLenArgument(1); 794 DestinationSize = ComputeSizeArgument(0); 795 break; 796 } 797 798 case Builtin::BI__builtin___strcpy_chk: { 799 DiagID = diag::warn_fortify_strlen_overflow; 800 SourceSize = ComputeStrLenArgument(1); 801 DestinationSize = ComputeExplicitObjectSizeArgument(2); 802 IsChkVariant = true; 803 break; 804 } 805 806 case Builtin::BIscanf: 807 case Builtin::BIfscanf: 808 case Builtin::BIsscanf: { 809 unsigned FormatIndex = 1; 810 unsigned DataIndex = 2; 811 if (BuiltinID == Builtin::BIscanf) { 812 FormatIndex = 0; 813 DataIndex = 1; 814 } 815 816 const auto *FormatExpr = 817 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 818 819 const auto *Format = dyn_cast<StringLiteral>(FormatExpr); 820 if (!Format) 821 return; 822 823 if (!Format->isAscii() && !Format->isUTF8()) 824 return; 825 826 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize, 827 unsigned SourceSize) { 828 DiagID = diag::warn_fortify_scanf_overflow; 829 unsigned Index = ArgIndex + DataIndex; 830 StringRef FunctionName = GetFunctionName(); 831 DiagRuntimeBehavior(TheCall->getArg(Index)->getBeginLoc(), TheCall, 832 PDiag(DiagID) << FunctionName << (Index + 1) 833 << DestSize << SourceSize); 834 }; 835 836 StringRef FormatStrRef = Format->getString(); 837 auto ShiftedComputeSizeArgument = [&](unsigned Index) { 838 return ComputeSizeArgument(Index + DataIndex); 839 }; 840 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose); 841 const char *FormatBytes = FormatStrRef.data(); 842 const ConstantArrayType *T = 843 Context.getAsConstantArrayType(Format->getType()); 844 assert(T && "String literal not of constant array type!"); 845 size_t TypeSize = T->getSize().getZExtValue(); 846 847 // In case there's a null byte somewhere. 848 size_t StrLen = 849 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 850 851 analyze_format_string::ParseScanfString(H, FormatBytes, 852 FormatBytes + StrLen, getLangOpts(), 853 Context.getTargetInfo()); 854 855 // Unlike the other cases, in this one we have already issued the diagnostic 856 // here, so no need to continue (because unlike the other cases, here the 857 // diagnostic refers to the argument number). 858 return; 859 } 860 861 case Builtin::BIsprintf: 862 case Builtin::BI__builtin___sprintf_chk: { 863 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 864 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 865 866 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 867 868 if (!Format->isAscii() && !Format->isUTF8()) 869 return; 870 871 StringRef FormatStrRef = Format->getString(); 872 EstimateSizeFormatHandler H(FormatStrRef); 873 const char *FormatBytes = FormatStrRef.data(); 874 const ConstantArrayType *T = 875 Context.getAsConstantArrayType(Format->getType()); 876 assert(T && "String literal not of constant array type!"); 877 size_t TypeSize = T->getSize().getZExtValue(); 878 879 // In case there's a null byte somewhere. 880 size_t StrLen = 881 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 882 if (!analyze_format_string::ParsePrintfString( 883 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 884 Context.getTargetInfo(), false)) { 885 DiagID = diag::warn_fortify_source_format_overflow; 886 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 887 .extOrTrunc(SizeTypeWidth); 888 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 889 DestinationSize = ComputeExplicitObjectSizeArgument(2); 890 IsChkVariant = true; 891 } else { 892 DestinationSize = ComputeSizeArgument(0); 893 } 894 break; 895 } 896 } 897 return; 898 } 899 case Builtin::BI__builtin___memcpy_chk: 900 case Builtin::BI__builtin___memmove_chk: 901 case Builtin::BI__builtin___memset_chk: 902 case Builtin::BI__builtin___strlcat_chk: 903 case Builtin::BI__builtin___strlcpy_chk: 904 case Builtin::BI__builtin___strncat_chk: 905 case Builtin::BI__builtin___strncpy_chk: 906 case Builtin::BI__builtin___stpncpy_chk: 907 case Builtin::BI__builtin___memccpy_chk: 908 case Builtin::BI__builtin___mempcpy_chk: { 909 DiagID = diag::warn_builtin_chk_overflow; 910 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2); 911 DestinationSize = 912 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 913 IsChkVariant = true; 914 break; 915 } 916 917 case Builtin::BI__builtin___snprintf_chk: 918 case Builtin::BI__builtin___vsnprintf_chk: { 919 DiagID = diag::warn_builtin_chk_overflow; 920 SourceSize = ComputeExplicitObjectSizeArgument(1); 921 DestinationSize = ComputeExplicitObjectSizeArgument(3); 922 IsChkVariant = true; 923 break; 924 } 925 926 case Builtin::BIstrncat: 927 case Builtin::BI__builtin_strncat: 928 case Builtin::BIstrncpy: 929 case Builtin::BI__builtin_strncpy: 930 case Builtin::BIstpncpy: 931 case Builtin::BI__builtin_stpncpy: { 932 // Whether these functions overflow depends on the runtime strlen of the 933 // string, not just the buffer size, so emitting the "always overflow" 934 // diagnostic isn't quite right. We should still diagnose passing a buffer 935 // size larger than the destination buffer though; this is a runtime abort 936 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 937 DiagID = diag::warn_fortify_source_size_mismatch; 938 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 939 DestinationSize = ComputeSizeArgument(0); 940 break; 941 } 942 943 case Builtin::BImemcpy: 944 case Builtin::BI__builtin_memcpy: 945 case Builtin::BImemmove: 946 case Builtin::BI__builtin_memmove: 947 case Builtin::BImemset: 948 case Builtin::BI__builtin_memset: 949 case Builtin::BImempcpy: 950 case Builtin::BI__builtin_mempcpy: { 951 DiagID = diag::warn_fortify_source_overflow; 952 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 953 DestinationSize = ComputeSizeArgument(0); 954 break; 955 } 956 case Builtin::BIsnprintf: 957 case Builtin::BI__builtin_snprintf: 958 case Builtin::BIvsnprintf: 959 case Builtin::BI__builtin_vsnprintf: { 960 DiagID = diag::warn_fortify_source_size_mismatch; 961 SourceSize = ComputeExplicitObjectSizeArgument(1); 962 DestinationSize = ComputeSizeArgument(0); 963 break; 964 } 965 } 966 967 if (!SourceSize || !DestinationSize || 968 llvm::APSInt::compareValues(SourceSize.getValue(), 969 DestinationSize.getValue()) <= 0) 970 return; 971 972 StringRef FunctionName = GetFunctionName(); 973 974 SmallString<16> DestinationStr; 975 SmallString<16> SourceStr; 976 DestinationSize->toString(DestinationStr, /*Radix=*/10); 977 SourceSize->toString(SourceStr, /*Radix=*/10); 978 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 979 PDiag(DiagID) 980 << FunctionName << DestinationStr << SourceStr); 981 } 982 983 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 984 Scope::ScopeFlags NeededScopeFlags, 985 unsigned DiagID) { 986 // Scopes aren't available during instantiation. Fortunately, builtin 987 // functions cannot be template args so they cannot be formed through template 988 // instantiation. Therefore checking once during the parse is sufficient. 989 if (SemaRef.inTemplateInstantiation()) 990 return false; 991 992 Scope *S = SemaRef.getCurScope(); 993 while (S && !S->isSEHExceptScope()) 994 S = S->getParent(); 995 if (!S || !(S->getFlags() & NeededScopeFlags)) { 996 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 997 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 998 << DRE->getDecl()->getIdentifier(); 999 return true; 1000 } 1001 1002 return false; 1003 } 1004 1005 static inline bool isBlockPointer(Expr *Arg) { 1006 return Arg->getType()->isBlockPointerType(); 1007 } 1008 1009 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 1010 /// void*, which is a requirement of device side enqueue. 1011 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 1012 const BlockPointerType *BPT = 1013 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 1014 ArrayRef<QualType> Params = 1015 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 1016 unsigned ArgCounter = 0; 1017 bool IllegalParams = false; 1018 // Iterate through the block parameters until either one is found that is not 1019 // a local void*, or the block is valid. 1020 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 1021 I != E; ++I, ++ArgCounter) { 1022 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 1023 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 1024 LangAS::opencl_local) { 1025 // Get the location of the error. If a block literal has been passed 1026 // (BlockExpr) then we can point straight to the offending argument, 1027 // else we just point to the variable reference. 1028 SourceLocation ErrorLoc; 1029 if (isa<BlockExpr>(BlockArg)) { 1030 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 1031 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 1032 } else if (isa<DeclRefExpr>(BlockArg)) { 1033 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 1034 } 1035 S.Diag(ErrorLoc, 1036 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 1037 IllegalParams = true; 1038 } 1039 } 1040 1041 return IllegalParams; 1042 } 1043 1044 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 1045 // OpenCL device can support extension but not the feature as extension 1046 // requires subgroup independent forward progress, but subgroup independent 1047 // forward progress is optional in OpenCL C 3.0 __opencl_c_subgroups feature. 1048 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts()) && 1049 !S.getOpenCLOptions().isSupported("__opencl_c_subgroups", 1050 S.getLangOpts())) { 1051 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 1052 << 1 << Call->getDirectCallee() 1053 << "cl_khr_subgroups or __opencl_c_subgroups"; 1054 return true; 1055 } 1056 return false; 1057 } 1058 1059 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 1060 if (checkArgCount(S, TheCall, 2)) 1061 return true; 1062 1063 if (checkOpenCLSubgroupExt(S, TheCall)) 1064 return true; 1065 1066 // First argument is an ndrange_t type. 1067 Expr *NDRangeArg = TheCall->getArg(0); 1068 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 1069 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1070 << TheCall->getDirectCallee() << "'ndrange_t'"; 1071 return true; 1072 } 1073 1074 Expr *BlockArg = TheCall->getArg(1); 1075 if (!isBlockPointer(BlockArg)) { 1076 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1077 << TheCall->getDirectCallee() << "block"; 1078 return true; 1079 } 1080 return checkOpenCLBlockArgs(S, BlockArg); 1081 } 1082 1083 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 1084 /// get_kernel_work_group_size 1085 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 1086 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 1087 if (checkArgCount(S, TheCall, 1)) 1088 return true; 1089 1090 Expr *BlockArg = TheCall->getArg(0); 1091 if (!isBlockPointer(BlockArg)) { 1092 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1093 << TheCall->getDirectCallee() << "block"; 1094 return true; 1095 } 1096 return checkOpenCLBlockArgs(S, BlockArg); 1097 } 1098 1099 /// Diagnose integer type and any valid implicit conversion to it. 1100 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 1101 const QualType &IntType); 1102 1103 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 1104 unsigned Start, unsigned End) { 1105 bool IllegalParams = false; 1106 for (unsigned I = Start; I <= End; ++I) 1107 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 1108 S.Context.getSizeType()); 1109 return IllegalParams; 1110 } 1111 1112 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 1113 /// 'local void*' parameter of passed block. 1114 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 1115 Expr *BlockArg, 1116 unsigned NumNonVarArgs) { 1117 const BlockPointerType *BPT = 1118 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 1119 unsigned NumBlockParams = 1120 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 1121 unsigned TotalNumArgs = TheCall->getNumArgs(); 1122 1123 // For each argument passed to the block, a corresponding uint needs to 1124 // be passed to describe the size of the local memory. 1125 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 1126 S.Diag(TheCall->getBeginLoc(), 1127 diag::err_opencl_enqueue_kernel_local_size_args); 1128 return true; 1129 } 1130 1131 // Check that the sizes of the local memory are specified by integers. 1132 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 1133 TotalNumArgs - 1); 1134 } 1135 1136 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 1137 /// overload formats specified in Table 6.13.17.1. 1138 /// int enqueue_kernel(queue_t queue, 1139 /// kernel_enqueue_flags_t flags, 1140 /// const ndrange_t ndrange, 1141 /// void (^block)(void)) 1142 /// int enqueue_kernel(queue_t queue, 1143 /// kernel_enqueue_flags_t flags, 1144 /// const ndrange_t ndrange, 1145 /// uint num_events_in_wait_list, 1146 /// clk_event_t *event_wait_list, 1147 /// clk_event_t *event_ret, 1148 /// void (^block)(void)) 1149 /// int enqueue_kernel(queue_t queue, 1150 /// kernel_enqueue_flags_t flags, 1151 /// const ndrange_t ndrange, 1152 /// void (^block)(local void*, ...), 1153 /// uint size0, ...) 1154 /// int enqueue_kernel(queue_t queue, 1155 /// kernel_enqueue_flags_t flags, 1156 /// const ndrange_t ndrange, 1157 /// uint num_events_in_wait_list, 1158 /// clk_event_t *event_wait_list, 1159 /// clk_event_t *event_ret, 1160 /// void (^block)(local void*, ...), 1161 /// uint size0, ...) 1162 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 1163 unsigned NumArgs = TheCall->getNumArgs(); 1164 1165 if (NumArgs < 4) { 1166 S.Diag(TheCall->getBeginLoc(), 1167 diag::err_typecheck_call_too_few_args_at_least) 1168 << 0 << 4 << NumArgs; 1169 return true; 1170 } 1171 1172 Expr *Arg0 = TheCall->getArg(0); 1173 Expr *Arg1 = TheCall->getArg(1); 1174 Expr *Arg2 = TheCall->getArg(2); 1175 Expr *Arg3 = TheCall->getArg(3); 1176 1177 // First argument always needs to be a queue_t type. 1178 if (!Arg0->getType()->isQueueT()) { 1179 S.Diag(TheCall->getArg(0)->getBeginLoc(), 1180 diag::err_opencl_builtin_expected_type) 1181 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 1182 return true; 1183 } 1184 1185 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 1186 if (!Arg1->getType()->isIntegerType()) { 1187 S.Diag(TheCall->getArg(1)->getBeginLoc(), 1188 diag::err_opencl_builtin_expected_type) 1189 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 1190 return true; 1191 } 1192 1193 // Third argument is always an ndrange_t type. 1194 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 1195 S.Diag(TheCall->getArg(2)->getBeginLoc(), 1196 diag::err_opencl_builtin_expected_type) 1197 << TheCall->getDirectCallee() << "'ndrange_t'"; 1198 return true; 1199 } 1200 1201 // With four arguments, there is only one form that the function could be 1202 // called in: no events and no variable arguments. 1203 if (NumArgs == 4) { 1204 // check that the last argument is the right block type. 1205 if (!isBlockPointer(Arg3)) { 1206 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1207 << TheCall->getDirectCallee() << "block"; 1208 return true; 1209 } 1210 // we have a block type, check the prototype 1211 const BlockPointerType *BPT = 1212 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1213 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1214 S.Diag(Arg3->getBeginLoc(), 1215 diag::err_opencl_enqueue_kernel_blocks_no_args); 1216 return true; 1217 } 1218 return false; 1219 } 1220 // we can have block + varargs. 1221 if (isBlockPointer(Arg3)) 1222 return (checkOpenCLBlockArgs(S, Arg3) || 1223 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1224 // last two cases with either exactly 7 args or 7 args and varargs. 1225 if (NumArgs >= 7) { 1226 // check common block argument. 1227 Expr *Arg6 = TheCall->getArg(6); 1228 if (!isBlockPointer(Arg6)) { 1229 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1230 << TheCall->getDirectCallee() << "block"; 1231 return true; 1232 } 1233 if (checkOpenCLBlockArgs(S, Arg6)) 1234 return true; 1235 1236 // Forth argument has to be any integer type. 1237 if (!Arg3->getType()->isIntegerType()) { 1238 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1239 diag::err_opencl_builtin_expected_type) 1240 << TheCall->getDirectCallee() << "integer"; 1241 return true; 1242 } 1243 // check remaining common arguments. 1244 Expr *Arg4 = TheCall->getArg(4); 1245 Expr *Arg5 = TheCall->getArg(5); 1246 1247 // Fifth argument is always passed as a pointer to clk_event_t. 1248 if (!Arg4->isNullPointerConstant(S.Context, 1249 Expr::NPC_ValueDependentIsNotNull) && 1250 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1251 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1252 diag::err_opencl_builtin_expected_type) 1253 << TheCall->getDirectCallee() 1254 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1255 return true; 1256 } 1257 1258 // Sixth argument is always passed as a pointer to clk_event_t. 1259 if (!Arg5->isNullPointerConstant(S.Context, 1260 Expr::NPC_ValueDependentIsNotNull) && 1261 !(Arg5->getType()->isPointerType() && 1262 Arg5->getType()->getPointeeType()->isClkEventT())) { 1263 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1264 diag::err_opencl_builtin_expected_type) 1265 << TheCall->getDirectCallee() 1266 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1267 return true; 1268 } 1269 1270 if (NumArgs == 7) 1271 return false; 1272 1273 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1274 } 1275 1276 // None of the specific case has been detected, give generic error 1277 S.Diag(TheCall->getBeginLoc(), 1278 diag::err_opencl_enqueue_kernel_incorrect_args); 1279 return true; 1280 } 1281 1282 /// Returns OpenCL access qual. 1283 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1284 return D->getAttr<OpenCLAccessAttr>(); 1285 } 1286 1287 /// Returns true if pipe element type is different from the pointer. 1288 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1289 const Expr *Arg0 = Call->getArg(0); 1290 // First argument type should always be pipe. 1291 if (!Arg0->getType()->isPipeType()) { 1292 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1293 << Call->getDirectCallee() << Arg0->getSourceRange(); 1294 return true; 1295 } 1296 OpenCLAccessAttr *AccessQual = 1297 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1298 // Validates the access qualifier is compatible with the call. 1299 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1300 // read_only and write_only, and assumed to be read_only if no qualifier is 1301 // specified. 1302 switch (Call->getDirectCallee()->getBuiltinID()) { 1303 case Builtin::BIread_pipe: 1304 case Builtin::BIreserve_read_pipe: 1305 case Builtin::BIcommit_read_pipe: 1306 case Builtin::BIwork_group_reserve_read_pipe: 1307 case Builtin::BIsub_group_reserve_read_pipe: 1308 case Builtin::BIwork_group_commit_read_pipe: 1309 case Builtin::BIsub_group_commit_read_pipe: 1310 if (!(!AccessQual || AccessQual->isReadOnly())) { 1311 S.Diag(Arg0->getBeginLoc(), 1312 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1313 << "read_only" << Arg0->getSourceRange(); 1314 return true; 1315 } 1316 break; 1317 case Builtin::BIwrite_pipe: 1318 case Builtin::BIreserve_write_pipe: 1319 case Builtin::BIcommit_write_pipe: 1320 case Builtin::BIwork_group_reserve_write_pipe: 1321 case Builtin::BIsub_group_reserve_write_pipe: 1322 case Builtin::BIwork_group_commit_write_pipe: 1323 case Builtin::BIsub_group_commit_write_pipe: 1324 if (!(AccessQual && AccessQual->isWriteOnly())) { 1325 S.Diag(Arg0->getBeginLoc(), 1326 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1327 << "write_only" << Arg0->getSourceRange(); 1328 return true; 1329 } 1330 break; 1331 default: 1332 break; 1333 } 1334 return false; 1335 } 1336 1337 /// Returns true if pipe element type is different from the pointer. 1338 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1339 const Expr *Arg0 = Call->getArg(0); 1340 const Expr *ArgIdx = Call->getArg(Idx); 1341 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1342 const QualType EltTy = PipeTy->getElementType(); 1343 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1344 // The Idx argument should be a pointer and the type of the pointer and 1345 // the type of pipe element should also be the same. 1346 if (!ArgTy || 1347 !S.Context.hasSameType( 1348 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1349 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1350 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1351 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1352 return true; 1353 } 1354 return false; 1355 } 1356 1357 // Performs semantic analysis for the read/write_pipe call. 1358 // \param S Reference to the semantic analyzer. 1359 // \param Call A pointer to the builtin call. 1360 // \return True if a semantic error has been found, false otherwise. 1361 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1362 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1363 // functions have two forms. 1364 switch (Call->getNumArgs()) { 1365 case 2: 1366 if (checkOpenCLPipeArg(S, Call)) 1367 return true; 1368 // The call with 2 arguments should be 1369 // read/write_pipe(pipe T, T*). 1370 // Check packet type T. 1371 if (checkOpenCLPipePacketType(S, Call, 1)) 1372 return true; 1373 break; 1374 1375 case 4: { 1376 if (checkOpenCLPipeArg(S, Call)) 1377 return true; 1378 // The call with 4 arguments should be 1379 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1380 // Check reserve_id_t. 1381 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1382 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1383 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1384 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1385 return true; 1386 } 1387 1388 // Check the index. 1389 const Expr *Arg2 = Call->getArg(2); 1390 if (!Arg2->getType()->isIntegerType() && 1391 !Arg2->getType()->isUnsignedIntegerType()) { 1392 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1393 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1394 << Arg2->getType() << Arg2->getSourceRange(); 1395 return true; 1396 } 1397 1398 // Check packet type T. 1399 if (checkOpenCLPipePacketType(S, Call, 3)) 1400 return true; 1401 } break; 1402 default: 1403 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1404 << Call->getDirectCallee() << Call->getSourceRange(); 1405 return true; 1406 } 1407 1408 return false; 1409 } 1410 1411 // Performs a semantic analysis on the {work_group_/sub_group_ 1412 // /_}reserve_{read/write}_pipe 1413 // \param S Reference to the semantic analyzer. 1414 // \param Call The call to the builtin function to be analyzed. 1415 // \return True if a semantic error was found, false otherwise. 1416 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1417 if (checkArgCount(S, Call, 2)) 1418 return true; 1419 1420 if (checkOpenCLPipeArg(S, Call)) 1421 return true; 1422 1423 // Check the reserve size. 1424 if (!Call->getArg(1)->getType()->isIntegerType() && 1425 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1426 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1427 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1428 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1429 return true; 1430 } 1431 1432 // Since return type of reserve_read/write_pipe built-in function is 1433 // reserve_id_t, which is not defined in the builtin def file , we used int 1434 // as return type and need to override the return type of these functions. 1435 Call->setType(S.Context.OCLReserveIDTy); 1436 1437 return false; 1438 } 1439 1440 // Performs a semantic analysis on {work_group_/sub_group_ 1441 // /_}commit_{read/write}_pipe 1442 // \param S Reference to the semantic analyzer. 1443 // \param Call The call to the builtin function to be analyzed. 1444 // \return True if a semantic error was found, false otherwise. 1445 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1446 if (checkArgCount(S, Call, 2)) 1447 return true; 1448 1449 if (checkOpenCLPipeArg(S, Call)) 1450 return true; 1451 1452 // Check reserve_id_t. 1453 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1454 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1455 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1456 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1457 return true; 1458 } 1459 1460 return false; 1461 } 1462 1463 // Performs a semantic analysis on the call to built-in Pipe 1464 // Query Functions. 1465 // \param S Reference to the semantic analyzer. 1466 // \param Call The call to the builtin function to be analyzed. 1467 // \return True if a semantic error was found, false otherwise. 1468 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1469 if (checkArgCount(S, Call, 1)) 1470 return true; 1471 1472 if (!Call->getArg(0)->getType()->isPipeType()) { 1473 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1474 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1475 return true; 1476 } 1477 1478 return false; 1479 } 1480 1481 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1482 // Performs semantic analysis for the to_global/local/private call. 1483 // \param S Reference to the semantic analyzer. 1484 // \param BuiltinID ID of the builtin function. 1485 // \param Call A pointer to the builtin call. 1486 // \return True if a semantic error has been found, false otherwise. 1487 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1488 CallExpr *Call) { 1489 if (checkArgCount(S, Call, 1)) 1490 return true; 1491 1492 auto RT = Call->getArg(0)->getType(); 1493 if (!RT->isPointerType() || RT->getPointeeType() 1494 .getAddressSpace() == LangAS::opencl_constant) { 1495 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1496 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1497 return true; 1498 } 1499 1500 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1501 S.Diag(Call->getArg(0)->getBeginLoc(), 1502 diag::warn_opencl_generic_address_space_arg) 1503 << Call->getDirectCallee()->getNameInfo().getAsString() 1504 << Call->getArg(0)->getSourceRange(); 1505 } 1506 1507 RT = RT->getPointeeType(); 1508 auto Qual = RT.getQualifiers(); 1509 switch (BuiltinID) { 1510 case Builtin::BIto_global: 1511 Qual.setAddressSpace(LangAS::opencl_global); 1512 break; 1513 case Builtin::BIto_local: 1514 Qual.setAddressSpace(LangAS::opencl_local); 1515 break; 1516 case Builtin::BIto_private: 1517 Qual.setAddressSpace(LangAS::opencl_private); 1518 break; 1519 default: 1520 llvm_unreachable("Invalid builtin function"); 1521 } 1522 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1523 RT.getUnqualifiedType(), Qual))); 1524 1525 return false; 1526 } 1527 1528 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1529 if (checkArgCount(S, TheCall, 1)) 1530 return ExprError(); 1531 1532 // Compute __builtin_launder's parameter type from the argument. 1533 // The parameter type is: 1534 // * The type of the argument if it's not an array or function type, 1535 // Otherwise, 1536 // * The decayed argument type. 1537 QualType ParamTy = [&]() { 1538 QualType ArgTy = TheCall->getArg(0)->getType(); 1539 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1540 return S.Context.getPointerType(Ty->getElementType()); 1541 if (ArgTy->isFunctionType()) { 1542 return S.Context.getPointerType(ArgTy); 1543 } 1544 return ArgTy; 1545 }(); 1546 1547 TheCall->setType(ParamTy); 1548 1549 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1550 if (!ParamTy->isPointerType()) 1551 return 0; 1552 if (ParamTy->isFunctionPointerType()) 1553 return 1; 1554 if (ParamTy->isVoidPointerType()) 1555 return 2; 1556 return llvm::Optional<unsigned>{}; 1557 }(); 1558 if (DiagSelect.hasValue()) { 1559 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1560 << DiagSelect.getValue() << TheCall->getSourceRange(); 1561 return ExprError(); 1562 } 1563 1564 // We either have an incomplete class type, or we have a class template 1565 // whose instantiation has not been forced. Example: 1566 // 1567 // template <class T> struct Foo { T value; }; 1568 // Foo<int> *p = nullptr; 1569 // auto *d = __builtin_launder(p); 1570 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1571 diag::err_incomplete_type)) 1572 return ExprError(); 1573 1574 assert(ParamTy->getPointeeType()->isObjectType() && 1575 "Unhandled non-object pointer case"); 1576 1577 InitializedEntity Entity = 1578 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1579 ExprResult Arg = 1580 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1581 if (Arg.isInvalid()) 1582 return ExprError(); 1583 TheCall->setArg(0, Arg.get()); 1584 1585 return TheCall; 1586 } 1587 1588 // Emit an error and return true if the current object format type is in the 1589 // list of unsupported types. 1590 static bool CheckBuiltinTargetNotInUnsupported( 1591 Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1592 ArrayRef<llvm::Triple::ObjectFormatType> UnsupportedObjectFormatTypes) { 1593 llvm::Triple::ObjectFormatType CurObjFormat = 1594 S.getASTContext().getTargetInfo().getTriple().getObjectFormat(); 1595 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) { 1596 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1597 << TheCall->getSourceRange(); 1598 return true; 1599 } 1600 return false; 1601 } 1602 1603 // Emit an error and return true if the current architecture is not in the list 1604 // of supported architectures. 1605 static bool 1606 CheckBuiltinTargetInSupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1607 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1608 llvm::Triple::ArchType CurArch = 1609 S.getASTContext().getTargetInfo().getTriple().getArch(); 1610 if (llvm::is_contained(SupportedArchs, CurArch)) 1611 return false; 1612 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1613 << TheCall->getSourceRange(); 1614 return true; 1615 } 1616 1617 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1618 SourceLocation CallSiteLoc); 1619 1620 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1621 CallExpr *TheCall) { 1622 switch (TI.getTriple().getArch()) { 1623 default: 1624 // Some builtins don't require additional checking, so just consider these 1625 // acceptable. 1626 return false; 1627 case llvm::Triple::arm: 1628 case llvm::Triple::armeb: 1629 case llvm::Triple::thumb: 1630 case llvm::Triple::thumbeb: 1631 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1632 case llvm::Triple::aarch64: 1633 case llvm::Triple::aarch64_32: 1634 case llvm::Triple::aarch64_be: 1635 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1636 case llvm::Triple::bpfeb: 1637 case llvm::Triple::bpfel: 1638 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1639 case llvm::Triple::hexagon: 1640 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1641 case llvm::Triple::mips: 1642 case llvm::Triple::mipsel: 1643 case llvm::Triple::mips64: 1644 case llvm::Triple::mips64el: 1645 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1646 case llvm::Triple::systemz: 1647 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1648 case llvm::Triple::x86: 1649 case llvm::Triple::x86_64: 1650 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1651 case llvm::Triple::ppc: 1652 case llvm::Triple::ppcle: 1653 case llvm::Triple::ppc64: 1654 case llvm::Triple::ppc64le: 1655 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1656 case llvm::Triple::amdgcn: 1657 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1658 case llvm::Triple::riscv32: 1659 case llvm::Triple::riscv64: 1660 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1661 } 1662 } 1663 1664 ExprResult 1665 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1666 CallExpr *TheCall) { 1667 ExprResult TheCallResult(TheCall); 1668 1669 // Find out if any arguments are required to be integer constant expressions. 1670 unsigned ICEArguments = 0; 1671 ASTContext::GetBuiltinTypeError Error; 1672 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1673 if (Error != ASTContext::GE_None) 1674 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1675 1676 // If any arguments are required to be ICE's, check and diagnose. 1677 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1678 // Skip arguments not required to be ICE's. 1679 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1680 1681 llvm::APSInt Result; 1682 // If we don't have enough arguments, continue so we can issue better 1683 // diagnostic in checkArgCount(...) 1684 if (ArgNo < TheCall->getNumArgs() && 1685 SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1686 return true; 1687 ICEArguments &= ~(1 << ArgNo); 1688 } 1689 1690 switch (BuiltinID) { 1691 case Builtin::BI__builtin___CFStringMakeConstantString: 1692 // CFStringMakeConstantString is currently not implemented for GOFF (i.e., 1693 // on z/OS) and for XCOFF (i.e., on AIX). Emit unsupported 1694 if (CheckBuiltinTargetNotInUnsupported( 1695 *this, BuiltinID, TheCall, 1696 {llvm::Triple::GOFF, llvm::Triple::XCOFF})) 1697 return ExprError(); 1698 assert(TheCall->getNumArgs() == 1 && 1699 "Wrong # arguments to builtin CFStringMakeConstantString"); 1700 if (CheckObjCString(TheCall->getArg(0))) 1701 return ExprError(); 1702 break; 1703 case Builtin::BI__builtin_ms_va_start: 1704 case Builtin::BI__builtin_stdarg_start: 1705 case Builtin::BI__builtin_va_start: 1706 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1707 return ExprError(); 1708 break; 1709 case Builtin::BI__va_start: { 1710 switch (Context.getTargetInfo().getTriple().getArch()) { 1711 case llvm::Triple::aarch64: 1712 case llvm::Triple::arm: 1713 case llvm::Triple::thumb: 1714 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1715 return ExprError(); 1716 break; 1717 default: 1718 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1719 return ExprError(); 1720 break; 1721 } 1722 break; 1723 } 1724 1725 // The acquire, release, and no fence variants are ARM and AArch64 only. 1726 case Builtin::BI_interlockedbittestandset_acq: 1727 case Builtin::BI_interlockedbittestandset_rel: 1728 case Builtin::BI_interlockedbittestandset_nf: 1729 case Builtin::BI_interlockedbittestandreset_acq: 1730 case Builtin::BI_interlockedbittestandreset_rel: 1731 case Builtin::BI_interlockedbittestandreset_nf: 1732 if (CheckBuiltinTargetInSupported( 1733 *this, BuiltinID, TheCall, 1734 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1735 return ExprError(); 1736 break; 1737 1738 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1739 case Builtin::BI_bittest64: 1740 case Builtin::BI_bittestandcomplement64: 1741 case Builtin::BI_bittestandreset64: 1742 case Builtin::BI_bittestandset64: 1743 case Builtin::BI_interlockedbittestandreset64: 1744 case Builtin::BI_interlockedbittestandset64: 1745 if (CheckBuiltinTargetInSupported(*this, BuiltinID, TheCall, 1746 {llvm::Triple::x86_64, llvm::Triple::arm, 1747 llvm::Triple::thumb, 1748 llvm::Triple::aarch64})) 1749 return ExprError(); 1750 break; 1751 1752 case Builtin::BI__builtin_isgreater: 1753 case Builtin::BI__builtin_isgreaterequal: 1754 case Builtin::BI__builtin_isless: 1755 case Builtin::BI__builtin_islessequal: 1756 case Builtin::BI__builtin_islessgreater: 1757 case Builtin::BI__builtin_isunordered: 1758 if (SemaBuiltinUnorderedCompare(TheCall)) 1759 return ExprError(); 1760 break; 1761 case Builtin::BI__builtin_fpclassify: 1762 if (SemaBuiltinFPClassification(TheCall, 6)) 1763 return ExprError(); 1764 break; 1765 case Builtin::BI__builtin_isfinite: 1766 case Builtin::BI__builtin_isinf: 1767 case Builtin::BI__builtin_isinf_sign: 1768 case Builtin::BI__builtin_isnan: 1769 case Builtin::BI__builtin_isnormal: 1770 case Builtin::BI__builtin_signbit: 1771 case Builtin::BI__builtin_signbitf: 1772 case Builtin::BI__builtin_signbitl: 1773 if (SemaBuiltinFPClassification(TheCall, 1)) 1774 return ExprError(); 1775 break; 1776 case Builtin::BI__builtin_shufflevector: 1777 return SemaBuiltinShuffleVector(TheCall); 1778 // TheCall will be freed by the smart pointer here, but that's fine, since 1779 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1780 case Builtin::BI__builtin_prefetch: 1781 if (SemaBuiltinPrefetch(TheCall)) 1782 return ExprError(); 1783 break; 1784 case Builtin::BI__builtin_alloca_with_align: 1785 case Builtin::BI__builtin_alloca_with_align_uninitialized: 1786 if (SemaBuiltinAllocaWithAlign(TheCall)) 1787 return ExprError(); 1788 LLVM_FALLTHROUGH; 1789 case Builtin::BI__builtin_alloca: 1790 case Builtin::BI__builtin_alloca_uninitialized: 1791 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1792 << TheCall->getDirectCallee(); 1793 break; 1794 case Builtin::BI__arithmetic_fence: 1795 if (SemaBuiltinArithmeticFence(TheCall)) 1796 return ExprError(); 1797 break; 1798 case Builtin::BI__assume: 1799 case Builtin::BI__builtin_assume: 1800 if (SemaBuiltinAssume(TheCall)) 1801 return ExprError(); 1802 break; 1803 case Builtin::BI__builtin_assume_aligned: 1804 if (SemaBuiltinAssumeAligned(TheCall)) 1805 return ExprError(); 1806 break; 1807 case Builtin::BI__builtin_dynamic_object_size: 1808 case Builtin::BI__builtin_object_size: 1809 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1810 return ExprError(); 1811 break; 1812 case Builtin::BI__builtin_longjmp: 1813 if (SemaBuiltinLongjmp(TheCall)) 1814 return ExprError(); 1815 break; 1816 case Builtin::BI__builtin_setjmp: 1817 if (SemaBuiltinSetjmp(TheCall)) 1818 return ExprError(); 1819 break; 1820 case Builtin::BI__builtin_classify_type: 1821 if (checkArgCount(*this, TheCall, 1)) return true; 1822 TheCall->setType(Context.IntTy); 1823 break; 1824 case Builtin::BI__builtin_complex: 1825 if (SemaBuiltinComplex(TheCall)) 1826 return ExprError(); 1827 break; 1828 case Builtin::BI__builtin_constant_p: { 1829 if (checkArgCount(*this, TheCall, 1)) return true; 1830 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1831 if (Arg.isInvalid()) return true; 1832 TheCall->setArg(0, Arg.get()); 1833 TheCall->setType(Context.IntTy); 1834 break; 1835 } 1836 case Builtin::BI__builtin_launder: 1837 return SemaBuiltinLaunder(*this, TheCall); 1838 case Builtin::BI__sync_fetch_and_add: 1839 case Builtin::BI__sync_fetch_and_add_1: 1840 case Builtin::BI__sync_fetch_and_add_2: 1841 case Builtin::BI__sync_fetch_and_add_4: 1842 case Builtin::BI__sync_fetch_and_add_8: 1843 case Builtin::BI__sync_fetch_and_add_16: 1844 case Builtin::BI__sync_fetch_and_sub: 1845 case Builtin::BI__sync_fetch_and_sub_1: 1846 case Builtin::BI__sync_fetch_and_sub_2: 1847 case Builtin::BI__sync_fetch_and_sub_4: 1848 case Builtin::BI__sync_fetch_and_sub_8: 1849 case Builtin::BI__sync_fetch_and_sub_16: 1850 case Builtin::BI__sync_fetch_and_or: 1851 case Builtin::BI__sync_fetch_and_or_1: 1852 case Builtin::BI__sync_fetch_and_or_2: 1853 case Builtin::BI__sync_fetch_and_or_4: 1854 case Builtin::BI__sync_fetch_and_or_8: 1855 case Builtin::BI__sync_fetch_and_or_16: 1856 case Builtin::BI__sync_fetch_and_and: 1857 case Builtin::BI__sync_fetch_and_and_1: 1858 case Builtin::BI__sync_fetch_and_and_2: 1859 case Builtin::BI__sync_fetch_and_and_4: 1860 case Builtin::BI__sync_fetch_and_and_8: 1861 case Builtin::BI__sync_fetch_and_and_16: 1862 case Builtin::BI__sync_fetch_and_xor: 1863 case Builtin::BI__sync_fetch_and_xor_1: 1864 case Builtin::BI__sync_fetch_and_xor_2: 1865 case Builtin::BI__sync_fetch_and_xor_4: 1866 case Builtin::BI__sync_fetch_and_xor_8: 1867 case Builtin::BI__sync_fetch_and_xor_16: 1868 case Builtin::BI__sync_fetch_and_nand: 1869 case Builtin::BI__sync_fetch_and_nand_1: 1870 case Builtin::BI__sync_fetch_and_nand_2: 1871 case Builtin::BI__sync_fetch_and_nand_4: 1872 case Builtin::BI__sync_fetch_and_nand_8: 1873 case Builtin::BI__sync_fetch_and_nand_16: 1874 case Builtin::BI__sync_add_and_fetch: 1875 case Builtin::BI__sync_add_and_fetch_1: 1876 case Builtin::BI__sync_add_and_fetch_2: 1877 case Builtin::BI__sync_add_and_fetch_4: 1878 case Builtin::BI__sync_add_and_fetch_8: 1879 case Builtin::BI__sync_add_and_fetch_16: 1880 case Builtin::BI__sync_sub_and_fetch: 1881 case Builtin::BI__sync_sub_and_fetch_1: 1882 case Builtin::BI__sync_sub_and_fetch_2: 1883 case Builtin::BI__sync_sub_and_fetch_4: 1884 case Builtin::BI__sync_sub_and_fetch_8: 1885 case Builtin::BI__sync_sub_and_fetch_16: 1886 case Builtin::BI__sync_and_and_fetch: 1887 case Builtin::BI__sync_and_and_fetch_1: 1888 case Builtin::BI__sync_and_and_fetch_2: 1889 case Builtin::BI__sync_and_and_fetch_4: 1890 case Builtin::BI__sync_and_and_fetch_8: 1891 case Builtin::BI__sync_and_and_fetch_16: 1892 case Builtin::BI__sync_or_and_fetch: 1893 case Builtin::BI__sync_or_and_fetch_1: 1894 case Builtin::BI__sync_or_and_fetch_2: 1895 case Builtin::BI__sync_or_and_fetch_4: 1896 case Builtin::BI__sync_or_and_fetch_8: 1897 case Builtin::BI__sync_or_and_fetch_16: 1898 case Builtin::BI__sync_xor_and_fetch: 1899 case Builtin::BI__sync_xor_and_fetch_1: 1900 case Builtin::BI__sync_xor_and_fetch_2: 1901 case Builtin::BI__sync_xor_and_fetch_4: 1902 case Builtin::BI__sync_xor_and_fetch_8: 1903 case Builtin::BI__sync_xor_and_fetch_16: 1904 case Builtin::BI__sync_nand_and_fetch: 1905 case Builtin::BI__sync_nand_and_fetch_1: 1906 case Builtin::BI__sync_nand_and_fetch_2: 1907 case Builtin::BI__sync_nand_and_fetch_4: 1908 case Builtin::BI__sync_nand_and_fetch_8: 1909 case Builtin::BI__sync_nand_and_fetch_16: 1910 case Builtin::BI__sync_val_compare_and_swap: 1911 case Builtin::BI__sync_val_compare_and_swap_1: 1912 case Builtin::BI__sync_val_compare_and_swap_2: 1913 case Builtin::BI__sync_val_compare_and_swap_4: 1914 case Builtin::BI__sync_val_compare_and_swap_8: 1915 case Builtin::BI__sync_val_compare_and_swap_16: 1916 case Builtin::BI__sync_bool_compare_and_swap: 1917 case Builtin::BI__sync_bool_compare_and_swap_1: 1918 case Builtin::BI__sync_bool_compare_and_swap_2: 1919 case Builtin::BI__sync_bool_compare_and_swap_4: 1920 case Builtin::BI__sync_bool_compare_and_swap_8: 1921 case Builtin::BI__sync_bool_compare_and_swap_16: 1922 case Builtin::BI__sync_lock_test_and_set: 1923 case Builtin::BI__sync_lock_test_and_set_1: 1924 case Builtin::BI__sync_lock_test_and_set_2: 1925 case Builtin::BI__sync_lock_test_and_set_4: 1926 case Builtin::BI__sync_lock_test_and_set_8: 1927 case Builtin::BI__sync_lock_test_and_set_16: 1928 case Builtin::BI__sync_lock_release: 1929 case Builtin::BI__sync_lock_release_1: 1930 case Builtin::BI__sync_lock_release_2: 1931 case Builtin::BI__sync_lock_release_4: 1932 case Builtin::BI__sync_lock_release_8: 1933 case Builtin::BI__sync_lock_release_16: 1934 case Builtin::BI__sync_swap: 1935 case Builtin::BI__sync_swap_1: 1936 case Builtin::BI__sync_swap_2: 1937 case Builtin::BI__sync_swap_4: 1938 case Builtin::BI__sync_swap_8: 1939 case Builtin::BI__sync_swap_16: 1940 return SemaBuiltinAtomicOverloaded(TheCallResult); 1941 case Builtin::BI__sync_synchronize: 1942 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1943 << TheCall->getCallee()->getSourceRange(); 1944 break; 1945 case Builtin::BI__builtin_nontemporal_load: 1946 case Builtin::BI__builtin_nontemporal_store: 1947 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1948 case Builtin::BI__builtin_memcpy_inline: { 1949 if (checkArgCount(*this, TheCall, 3)) 1950 return ExprError(); 1951 auto ArgArrayConversionFailed = [&](unsigned Arg) { 1952 ExprResult ArgExpr = 1953 DefaultFunctionArrayLvalueConversion(TheCall->getArg(Arg)); 1954 if (ArgExpr.isInvalid()) 1955 return true; 1956 TheCall->setArg(Arg, ArgExpr.get()); 1957 return false; 1958 }; 1959 1960 if (ArgArrayConversionFailed(0) || ArgArrayConversionFailed(1)) 1961 return true; 1962 clang::Expr *SizeOp = TheCall->getArg(2); 1963 // We warn about copying to or from `nullptr` pointers when `size` is 1964 // greater than 0. When `size` is value dependent we cannot evaluate its 1965 // value so we bail out. 1966 if (SizeOp->isValueDependent()) 1967 break; 1968 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) { 1969 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1970 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1971 } 1972 break; 1973 } 1974 #define BUILTIN(ID, TYPE, ATTRS) 1975 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1976 case Builtin::BI##ID: \ 1977 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1978 #include "clang/Basic/Builtins.def" 1979 case Builtin::BI__annotation: 1980 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1981 return ExprError(); 1982 break; 1983 case Builtin::BI__builtin_annotation: 1984 if (SemaBuiltinAnnotation(*this, TheCall)) 1985 return ExprError(); 1986 break; 1987 case Builtin::BI__builtin_addressof: 1988 if (SemaBuiltinAddressof(*this, TheCall)) 1989 return ExprError(); 1990 break; 1991 case Builtin::BI__builtin_function_start: 1992 if (SemaBuiltinFunctionStart(*this, TheCall)) 1993 return ExprError(); 1994 break; 1995 case Builtin::BI__builtin_is_aligned: 1996 case Builtin::BI__builtin_align_up: 1997 case Builtin::BI__builtin_align_down: 1998 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1999 return ExprError(); 2000 break; 2001 case Builtin::BI__builtin_add_overflow: 2002 case Builtin::BI__builtin_sub_overflow: 2003 case Builtin::BI__builtin_mul_overflow: 2004 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 2005 return ExprError(); 2006 break; 2007 case Builtin::BI__builtin_operator_new: 2008 case Builtin::BI__builtin_operator_delete: { 2009 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 2010 ExprResult Res = 2011 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 2012 if (Res.isInvalid()) 2013 CorrectDelayedTyposInExpr(TheCallResult.get()); 2014 return Res; 2015 } 2016 case Builtin::BI__builtin_dump_struct: { 2017 // We first want to ensure we are called with 2 arguments 2018 if (checkArgCount(*this, TheCall, 2)) 2019 return ExprError(); 2020 // Ensure that the first argument is of type 'struct XX *' 2021 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 2022 const QualType PtrArgType = PtrArg->getType(); 2023 if (!PtrArgType->isPointerType() || 2024 !PtrArgType->getPointeeType()->isRecordType()) { 2025 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 2026 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 2027 << "structure pointer"; 2028 return ExprError(); 2029 } 2030 2031 // Ensure that the second argument is of type 'FunctionType' 2032 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 2033 const QualType FnPtrArgType = FnPtrArg->getType(); 2034 if (!FnPtrArgType->isPointerType()) { 2035 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 2036 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 2037 << FnPtrArgType << "'int (*)(const char *, ...)'"; 2038 return ExprError(); 2039 } 2040 2041 const auto *FuncType = 2042 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 2043 2044 if (!FuncType) { 2045 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 2046 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 2047 << FnPtrArgType << "'int (*)(const char *, ...)'"; 2048 return ExprError(); 2049 } 2050 2051 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 2052 if (!FT->getNumParams()) { 2053 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 2054 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 2055 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 2056 return ExprError(); 2057 } 2058 QualType PT = FT->getParamType(0); 2059 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 2060 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 2061 !PT->getPointeeType().isConstQualified()) { 2062 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 2063 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 2064 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 2065 return ExprError(); 2066 } 2067 } 2068 2069 TheCall->setType(Context.IntTy); 2070 break; 2071 } 2072 case Builtin::BI__builtin_expect_with_probability: { 2073 // We first want to ensure we are called with 3 arguments 2074 if (checkArgCount(*this, TheCall, 3)) 2075 return ExprError(); 2076 // then check probability is constant float in range [0.0, 1.0] 2077 const Expr *ProbArg = TheCall->getArg(2); 2078 SmallVector<PartialDiagnosticAt, 8> Notes; 2079 Expr::EvalResult Eval; 2080 Eval.Diag = &Notes; 2081 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 2082 !Eval.Val.isFloat()) { 2083 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 2084 << ProbArg->getSourceRange(); 2085 for (const PartialDiagnosticAt &PDiag : Notes) 2086 Diag(PDiag.first, PDiag.second); 2087 return ExprError(); 2088 } 2089 llvm::APFloat Probability = Eval.Val.getFloat(); 2090 bool LoseInfo = false; 2091 Probability.convert(llvm::APFloat::IEEEdouble(), 2092 llvm::RoundingMode::Dynamic, &LoseInfo); 2093 if (!(Probability >= llvm::APFloat(0.0) && 2094 Probability <= llvm::APFloat(1.0))) { 2095 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 2096 << ProbArg->getSourceRange(); 2097 return ExprError(); 2098 } 2099 break; 2100 } 2101 case Builtin::BI__builtin_preserve_access_index: 2102 if (SemaBuiltinPreserveAI(*this, TheCall)) 2103 return ExprError(); 2104 break; 2105 case Builtin::BI__builtin_call_with_static_chain: 2106 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 2107 return ExprError(); 2108 break; 2109 case Builtin::BI__exception_code: 2110 case Builtin::BI_exception_code: 2111 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 2112 diag::err_seh___except_block)) 2113 return ExprError(); 2114 break; 2115 case Builtin::BI__exception_info: 2116 case Builtin::BI_exception_info: 2117 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 2118 diag::err_seh___except_filter)) 2119 return ExprError(); 2120 break; 2121 case Builtin::BI__GetExceptionInfo: 2122 if (checkArgCount(*this, TheCall, 1)) 2123 return ExprError(); 2124 2125 if (CheckCXXThrowOperand( 2126 TheCall->getBeginLoc(), 2127 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 2128 TheCall)) 2129 return ExprError(); 2130 2131 TheCall->setType(Context.VoidPtrTy); 2132 break; 2133 // OpenCL v2.0, s6.13.16 - Pipe functions 2134 case Builtin::BIread_pipe: 2135 case Builtin::BIwrite_pipe: 2136 // Since those two functions are declared with var args, we need a semantic 2137 // check for the argument. 2138 if (SemaBuiltinRWPipe(*this, TheCall)) 2139 return ExprError(); 2140 break; 2141 case Builtin::BIreserve_read_pipe: 2142 case Builtin::BIreserve_write_pipe: 2143 case Builtin::BIwork_group_reserve_read_pipe: 2144 case Builtin::BIwork_group_reserve_write_pipe: 2145 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 2146 return ExprError(); 2147 break; 2148 case Builtin::BIsub_group_reserve_read_pipe: 2149 case Builtin::BIsub_group_reserve_write_pipe: 2150 if (checkOpenCLSubgroupExt(*this, TheCall) || 2151 SemaBuiltinReserveRWPipe(*this, TheCall)) 2152 return ExprError(); 2153 break; 2154 case Builtin::BIcommit_read_pipe: 2155 case Builtin::BIcommit_write_pipe: 2156 case Builtin::BIwork_group_commit_read_pipe: 2157 case Builtin::BIwork_group_commit_write_pipe: 2158 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 2159 return ExprError(); 2160 break; 2161 case Builtin::BIsub_group_commit_read_pipe: 2162 case Builtin::BIsub_group_commit_write_pipe: 2163 if (checkOpenCLSubgroupExt(*this, TheCall) || 2164 SemaBuiltinCommitRWPipe(*this, TheCall)) 2165 return ExprError(); 2166 break; 2167 case Builtin::BIget_pipe_num_packets: 2168 case Builtin::BIget_pipe_max_packets: 2169 if (SemaBuiltinPipePackets(*this, TheCall)) 2170 return ExprError(); 2171 break; 2172 case Builtin::BIto_global: 2173 case Builtin::BIto_local: 2174 case Builtin::BIto_private: 2175 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 2176 return ExprError(); 2177 break; 2178 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 2179 case Builtin::BIenqueue_kernel: 2180 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 2181 return ExprError(); 2182 break; 2183 case Builtin::BIget_kernel_work_group_size: 2184 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 2185 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 2186 return ExprError(); 2187 break; 2188 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 2189 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 2190 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 2191 return ExprError(); 2192 break; 2193 case Builtin::BI__builtin_os_log_format: 2194 Cleanup.setExprNeedsCleanups(true); 2195 LLVM_FALLTHROUGH; 2196 case Builtin::BI__builtin_os_log_format_buffer_size: 2197 if (SemaBuiltinOSLogFormat(TheCall)) 2198 return ExprError(); 2199 break; 2200 case Builtin::BI__builtin_frame_address: 2201 case Builtin::BI__builtin_return_address: { 2202 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 2203 return ExprError(); 2204 2205 // -Wframe-address warning if non-zero passed to builtin 2206 // return/frame address. 2207 Expr::EvalResult Result; 2208 if (!TheCall->getArg(0)->isValueDependent() && 2209 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 2210 Result.Val.getInt() != 0) 2211 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 2212 << ((BuiltinID == Builtin::BI__builtin_return_address) 2213 ? "__builtin_return_address" 2214 : "__builtin_frame_address") 2215 << TheCall->getSourceRange(); 2216 break; 2217 } 2218 2219 // __builtin_elementwise_abs restricts the element type to signed integers or 2220 // floating point types only. 2221 case Builtin::BI__builtin_elementwise_abs: { 2222 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall)) 2223 return ExprError(); 2224 2225 QualType ArgTy = TheCall->getArg(0)->getType(); 2226 QualType EltTy = ArgTy; 2227 2228 if (auto *VecTy = EltTy->getAs<VectorType>()) 2229 EltTy = VecTy->getElementType(); 2230 if (EltTy->isUnsignedIntegerType()) { 2231 Diag(TheCall->getArg(0)->getBeginLoc(), 2232 diag::err_builtin_invalid_arg_type) 2233 << 1 << /* signed integer or float ty*/ 3 << ArgTy; 2234 return ExprError(); 2235 } 2236 break; 2237 } 2238 2239 // These builtins restrict the element type to floating point 2240 // types only. 2241 case Builtin::BI__builtin_elementwise_ceil: 2242 case Builtin::BI__builtin_elementwise_floor: 2243 case Builtin::BI__builtin_elementwise_roundeven: 2244 case Builtin::BI__builtin_elementwise_trunc: { 2245 if (PrepareBuiltinElementwiseMathOneArgCall(TheCall)) 2246 return ExprError(); 2247 2248 QualType ArgTy = TheCall->getArg(0)->getType(); 2249 QualType EltTy = ArgTy; 2250 2251 if (auto *VecTy = EltTy->getAs<VectorType>()) 2252 EltTy = VecTy->getElementType(); 2253 if (!EltTy->isFloatingType()) { 2254 Diag(TheCall->getArg(0)->getBeginLoc(), 2255 diag::err_builtin_invalid_arg_type) 2256 << 1 << /* float ty*/ 5 << ArgTy; 2257 2258 return ExprError(); 2259 } 2260 break; 2261 } 2262 2263 // These builtins restrict the element type to integer 2264 // types only. 2265 case Builtin::BI__builtin_elementwise_add_sat: 2266 case Builtin::BI__builtin_elementwise_sub_sat: { 2267 if (SemaBuiltinElementwiseMath(TheCall)) 2268 return ExprError(); 2269 2270 const Expr *Arg = TheCall->getArg(0); 2271 QualType ArgTy = Arg->getType(); 2272 QualType EltTy = ArgTy; 2273 2274 if (auto *VecTy = EltTy->getAs<VectorType>()) 2275 EltTy = VecTy->getElementType(); 2276 2277 if (!EltTy->isIntegerType()) { 2278 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2279 << 1 << /* integer ty */ 6 << ArgTy; 2280 return ExprError(); 2281 } 2282 break; 2283 } 2284 2285 case Builtin::BI__builtin_elementwise_min: 2286 case Builtin::BI__builtin_elementwise_max: 2287 if (SemaBuiltinElementwiseMath(TheCall)) 2288 return ExprError(); 2289 break; 2290 case Builtin::BI__builtin_reduce_max: 2291 case Builtin::BI__builtin_reduce_min: { 2292 if (PrepareBuiltinReduceMathOneArgCall(TheCall)) 2293 return ExprError(); 2294 2295 const Expr *Arg = TheCall->getArg(0); 2296 const auto *TyA = Arg->getType()->getAs<VectorType>(); 2297 if (!TyA) { 2298 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2299 << 1 << /* vector ty*/ 4 << Arg->getType(); 2300 return ExprError(); 2301 } 2302 2303 TheCall->setType(TyA->getElementType()); 2304 break; 2305 } 2306 2307 // These builtins support vectors of integers only. 2308 case Builtin::BI__builtin_reduce_xor: 2309 case Builtin::BI__builtin_reduce_or: 2310 case Builtin::BI__builtin_reduce_and: { 2311 if (PrepareBuiltinReduceMathOneArgCall(TheCall)) 2312 return ExprError(); 2313 2314 const Expr *Arg = TheCall->getArg(0); 2315 const auto *TyA = Arg->getType()->getAs<VectorType>(); 2316 if (!TyA || !TyA->getElementType()->isIntegerType()) { 2317 Diag(Arg->getBeginLoc(), diag::err_builtin_invalid_arg_type) 2318 << 1 << /* vector of integers */ 6 << Arg->getType(); 2319 return ExprError(); 2320 } 2321 TheCall->setType(TyA->getElementType()); 2322 break; 2323 } 2324 2325 case Builtin::BI__builtin_matrix_transpose: 2326 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 2327 2328 case Builtin::BI__builtin_matrix_column_major_load: 2329 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 2330 2331 case Builtin::BI__builtin_matrix_column_major_store: 2332 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 2333 2334 case Builtin::BI__builtin_get_device_side_mangled_name: { 2335 auto Check = [](CallExpr *TheCall) { 2336 if (TheCall->getNumArgs() != 1) 2337 return false; 2338 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 2339 if (!DRE) 2340 return false; 2341 auto *D = DRE->getDecl(); 2342 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 2343 return false; 2344 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 2345 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 2346 }; 2347 if (!Check(TheCall)) { 2348 Diag(TheCall->getBeginLoc(), 2349 diag::err_hip_invalid_args_builtin_mangled_name); 2350 return ExprError(); 2351 } 2352 } 2353 } 2354 2355 // Since the target specific builtins for each arch overlap, only check those 2356 // of the arch we are compiling for. 2357 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 2358 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 2359 assert(Context.getAuxTargetInfo() && 2360 "Aux Target Builtin, but not an aux target?"); 2361 2362 if (CheckTSBuiltinFunctionCall( 2363 *Context.getAuxTargetInfo(), 2364 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2365 return ExprError(); 2366 } else { 2367 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2368 TheCall)) 2369 return ExprError(); 2370 } 2371 } 2372 2373 return TheCallResult; 2374 } 2375 2376 // Get the valid immediate range for the specified NEON type code. 2377 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2378 NeonTypeFlags Type(t); 2379 int IsQuad = ForceQuad ? true : Type.isQuad(); 2380 switch (Type.getEltType()) { 2381 case NeonTypeFlags::Int8: 2382 case NeonTypeFlags::Poly8: 2383 return shift ? 7 : (8 << IsQuad) - 1; 2384 case NeonTypeFlags::Int16: 2385 case NeonTypeFlags::Poly16: 2386 return shift ? 15 : (4 << IsQuad) - 1; 2387 case NeonTypeFlags::Int32: 2388 return shift ? 31 : (2 << IsQuad) - 1; 2389 case NeonTypeFlags::Int64: 2390 case NeonTypeFlags::Poly64: 2391 return shift ? 63 : (1 << IsQuad) - 1; 2392 case NeonTypeFlags::Poly128: 2393 return shift ? 127 : (1 << IsQuad) - 1; 2394 case NeonTypeFlags::Float16: 2395 assert(!shift && "cannot shift float types!"); 2396 return (4 << IsQuad) - 1; 2397 case NeonTypeFlags::Float32: 2398 assert(!shift && "cannot shift float types!"); 2399 return (2 << IsQuad) - 1; 2400 case NeonTypeFlags::Float64: 2401 assert(!shift && "cannot shift float types!"); 2402 return (1 << IsQuad) - 1; 2403 case NeonTypeFlags::BFloat16: 2404 assert(!shift && "cannot shift float types!"); 2405 return (4 << IsQuad) - 1; 2406 } 2407 llvm_unreachable("Invalid NeonTypeFlag!"); 2408 } 2409 2410 /// getNeonEltType - Return the QualType corresponding to the elements of 2411 /// the vector type specified by the NeonTypeFlags. This is used to check 2412 /// the pointer arguments for Neon load/store intrinsics. 2413 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2414 bool IsPolyUnsigned, bool IsInt64Long) { 2415 switch (Flags.getEltType()) { 2416 case NeonTypeFlags::Int8: 2417 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2418 case NeonTypeFlags::Int16: 2419 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2420 case NeonTypeFlags::Int32: 2421 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2422 case NeonTypeFlags::Int64: 2423 if (IsInt64Long) 2424 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2425 else 2426 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2427 : Context.LongLongTy; 2428 case NeonTypeFlags::Poly8: 2429 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2430 case NeonTypeFlags::Poly16: 2431 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2432 case NeonTypeFlags::Poly64: 2433 if (IsInt64Long) 2434 return Context.UnsignedLongTy; 2435 else 2436 return Context.UnsignedLongLongTy; 2437 case NeonTypeFlags::Poly128: 2438 break; 2439 case NeonTypeFlags::Float16: 2440 return Context.HalfTy; 2441 case NeonTypeFlags::Float32: 2442 return Context.FloatTy; 2443 case NeonTypeFlags::Float64: 2444 return Context.DoubleTy; 2445 case NeonTypeFlags::BFloat16: 2446 return Context.BFloat16Ty; 2447 } 2448 llvm_unreachable("Invalid NeonTypeFlag!"); 2449 } 2450 2451 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2452 // Range check SVE intrinsics that take immediate values. 2453 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2454 2455 switch (BuiltinID) { 2456 default: 2457 return false; 2458 #define GET_SVE_IMMEDIATE_CHECK 2459 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2460 #undef GET_SVE_IMMEDIATE_CHECK 2461 } 2462 2463 // Perform all the immediate checks for this builtin call. 2464 bool HasError = false; 2465 for (auto &I : ImmChecks) { 2466 int ArgNum, CheckTy, ElementSizeInBits; 2467 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2468 2469 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2470 2471 // Function that checks whether the operand (ArgNum) is an immediate 2472 // that is one of the predefined values. 2473 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2474 int ErrDiag) -> bool { 2475 // We can't check the value of a dependent argument. 2476 Expr *Arg = TheCall->getArg(ArgNum); 2477 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2478 return false; 2479 2480 // Check constant-ness first. 2481 llvm::APSInt Imm; 2482 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2483 return true; 2484 2485 if (!CheckImm(Imm.getSExtValue())) 2486 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2487 return false; 2488 }; 2489 2490 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2491 case SVETypeFlags::ImmCheck0_31: 2492 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2493 HasError = true; 2494 break; 2495 case SVETypeFlags::ImmCheck0_13: 2496 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2497 HasError = true; 2498 break; 2499 case SVETypeFlags::ImmCheck1_16: 2500 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2501 HasError = true; 2502 break; 2503 case SVETypeFlags::ImmCheck0_7: 2504 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2505 HasError = true; 2506 break; 2507 case SVETypeFlags::ImmCheckExtract: 2508 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2509 (2048 / ElementSizeInBits) - 1)) 2510 HasError = true; 2511 break; 2512 case SVETypeFlags::ImmCheckShiftRight: 2513 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2514 HasError = true; 2515 break; 2516 case SVETypeFlags::ImmCheckShiftRightNarrow: 2517 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2518 ElementSizeInBits / 2)) 2519 HasError = true; 2520 break; 2521 case SVETypeFlags::ImmCheckShiftLeft: 2522 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2523 ElementSizeInBits - 1)) 2524 HasError = true; 2525 break; 2526 case SVETypeFlags::ImmCheckLaneIndex: 2527 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2528 (128 / (1 * ElementSizeInBits)) - 1)) 2529 HasError = true; 2530 break; 2531 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2532 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2533 (128 / (2 * ElementSizeInBits)) - 1)) 2534 HasError = true; 2535 break; 2536 case SVETypeFlags::ImmCheckLaneIndexDot: 2537 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2538 (128 / (4 * ElementSizeInBits)) - 1)) 2539 HasError = true; 2540 break; 2541 case SVETypeFlags::ImmCheckComplexRot90_270: 2542 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2543 diag::err_rotation_argument_to_cadd)) 2544 HasError = true; 2545 break; 2546 case SVETypeFlags::ImmCheckComplexRotAll90: 2547 if (CheckImmediateInSet( 2548 [](int64_t V) { 2549 return V == 0 || V == 90 || V == 180 || V == 270; 2550 }, 2551 diag::err_rotation_argument_to_cmla)) 2552 HasError = true; 2553 break; 2554 case SVETypeFlags::ImmCheck0_1: 2555 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2556 HasError = true; 2557 break; 2558 case SVETypeFlags::ImmCheck0_2: 2559 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2560 HasError = true; 2561 break; 2562 case SVETypeFlags::ImmCheck0_3: 2563 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2564 HasError = true; 2565 break; 2566 } 2567 } 2568 2569 return HasError; 2570 } 2571 2572 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2573 unsigned BuiltinID, CallExpr *TheCall) { 2574 llvm::APSInt Result; 2575 uint64_t mask = 0; 2576 unsigned TV = 0; 2577 int PtrArgNum = -1; 2578 bool HasConstPtr = false; 2579 switch (BuiltinID) { 2580 #define GET_NEON_OVERLOAD_CHECK 2581 #include "clang/Basic/arm_neon.inc" 2582 #include "clang/Basic/arm_fp16.inc" 2583 #undef GET_NEON_OVERLOAD_CHECK 2584 } 2585 2586 // For NEON intrinsics which are overloaded on vector element type, validate 2587 // the immediate which specifies which variant to emit. 2588 unsigned ImmArg = TheCall->getNumArgs()-1; 2589 if (mask) { 2590 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2591 return true; 2592 2593 TV = Result.getLimitedValue(64); 2594 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2595 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2596 << TheCall->getArg(ImmArg)->getSourceRange(); 2597 } 2598 2599 if (PtrArgNum >= 0) { 2600 // Check that pointer arguments have the specified type. 2601 Expr *Arg = TheCall->getArg(PtrArgNum); 2602 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2603 Arg = ICE->getSubExpr(); 2604 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2605 QualType RHSTy = RHS.get()->getType(); 2606 2607 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2608 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2609 Arch == llvm::Triple::aarch64_32 || 2610 Arch == llvm::Triple::aarch64_be; 2611 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2612 QualType EltTy = 2613 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2614 if (HasConstPtr) 2615 EltTy = EltTy.withConst(); 2616 QualType LHSTy = Context.getPointerType(EltTy); 2617 AssignConvertType ConvTy; 2618 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2619 if (RHS.isInvalid()) 2620 return true; 2621 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2622 RHS.get(), AA_Assigning)) 2623 return true; 2624 } 2625 2626 // For NEON intrinsics which take an immediate value as part of the 2627 // instruction, range check them here. 2628 unsigned i = 0, l = 0, u = 0; 2629 switch (BuiltinID) { 2630 default: 2631 return false; 2632 #define GET_NEON_IMMEDIATE_CHECK 2633 #include "clang/Basic/arm_neon.inc" 2634 #include "clang/Basic/arm_fp16.inc" 2635 #undef GET_NEON_IMMEDIATE_CHECK 2636 } 2637 2638 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2639 } 2640 2641 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2642 switch (BuiltinID) { 2643 default: 2644 return false; 2645 #include "clang/Basic/arm_mve_builtin_sema.inc" 2646 } 2647 } 2648 2649 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2650 CallExpr *TheCall) { 2651 bool Err = false; 2652 switch (BuiltinID) { 2653 default: 2654 return false; 2655 #include "clang/Basic/arm_cde_builtin_sema.inc" 2656 } 2657 2658 if (Err) 2659 return true; 2660 2661 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2662 } 2663 2664 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2665 const Expr *CoprocArg, bool WantCDE) { 2666 if (isConstantEvaluated()) 2667 return false; 2668 2669 // We can't check the value of a dependent argument. 2670 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2671 return false; 2672 2673 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2674 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2675 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2676 2677 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2678 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2679 2680 if (IsCDECoproc != WantCDE) 2681 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2682 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2683 2684 return false; 2685 } 2686 2687 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2688 unsigned MaxWidth) { 2689 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2690 BuiltinID == ARM::BI__builtin_arm_ldaex || 2691 BuiltinID == ARM::BI__builtin_arm_strex || 2692 BuiltinID == ARM::BI__builtin_arm_stlex || 2693 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2694 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2695 BuiltinID == AArch64::BI__builtin_arm_strex || 2696 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2697 "unexpected ARM builtin"); 2698 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2699 BuiltinID == ARM::BI__builtin_arm_ldaex || 2700 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2701 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2702 2703 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2704 2705 // Ensure that we have the proper number of arguments. 2706 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2707 return true; 2708 2709 // Inspect the pointer argument of the atomic builtin. This should always be 2710 // a pointer type, whose element is an integral scalar or pointer type. 2711 // Because it is a pointer type, we don't have to worry about any implicit 2712 // casts here. 2713 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2714 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2715 if (PointerArgRes.isInvalid()) 2716 return true; 2717 PointerArg = PointerArgRes.get(); 2718 2719 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2720 if (!pointerType) { 2721 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2722 << PointerArg->getType() << PointerArg->getSourceRange(); 2723 return true; 2724 } 2725 2726 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2727 // task is to insert the appropriate casts into the AST. First work out just 2728 // what the appropriate type is. 2729 QualType ValType = pointerType->getPointeeType(); 2730 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2731 if (IsLdrex) 2732 AddrType.addConst(); 2733 2734 // Issue a warning if the cast is dodgy. 2735 CastKind CastNeeded = CK_NoOp; 2736 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2737 CastNeeded = CK_BitCast; 2738 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2739 << PointerArg->getType() << Context.getPointerType(AddrType) 2740 << AA_Passing << PointerArg->getSourceRange(); 2741 } 2742 2743 // Finally, do the cast and replace the argument with the corrected version. 2744 AddrType = Context.getPointerType(AddrType); 2745 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2746 if (PointerArgRes.isInvalid()) 2747 return true; 2748 PointerArg = PointerArgRes.get(); 2749 2750 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2751 2752 // In general, we allow ints, floats and pointers to be loaded and stored. 2753 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2754 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2755 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2756 << PointerArg->getType() << PointerArg->getSourceRange(); 2757 return true; 2758 } 2759 2760 // But ARM doesn't have instructions to deal with 128-bit versions. 2761 if (Context.getTypeSize(ValType) > MaxWidth) { 2762 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2763 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2764 << PointerArg->getType() << PointerArg->getSourceRange(); 2765 return true; 2766 } 2767 2768 switch (ValType.getObjCLifetime()) { 2769 case Qualifiers::OCL_None: 2770 case Qualifiers::OCL_ExplicitNone: 2771 // okay 2772 break; 2773 2774 case Qualifiers::OCL_Weak: 2775 case Qualifiers::OCL_Strong: 2776 case Qualifiers::OCL_Autoreleasing: 2777 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2778 << ValType << PointerArg->getSourceRange(); 2779 return true; 2780 } 2781 2782 if (IsLdrex) { 2783 TheCall->setType(ValType); 2784 return false; 2785 } 2786 2787 // Initialize the argument to be stored. 2788 ExprResult ValArg = TheCall->getArg(0); 2789 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2790 Context, ValType, /*consume*/ false); 2791 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2792 if (ValArg.isInvalid()) 2793 return true; 2794 TheCall->setArg(0, ValArg.get()); 2795 2796 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2797 // but the custom checker bypasses all default analysis. 2798 TheCall->setType(Context.IntTy); 2799 return false; 2800 } 2801 2802 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2803 CallExpr *TheCall) { 2804 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2805 BuiltinID == ARM::BI__builtin_arm_ldaex || 2806 BuiltinID == ARM::BI__builtin_arm_strex || 2807 BuiltinID == ARM::BI__builtin_arm_stlex) { 2808 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2809 } 2810 2811 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2812 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2813 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2814 } 2815 2816 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2817 BuiltinID == ARM::BI__builtin_arm_wsr64) 2818 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2819 2820 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2821 BuiltinID == ARM::BI__builtin_arm_rsrp || 2822 BuiltinID == ARM::BI__builtin_arm_wsr || 2823 BuiltinID == ARM::BI__builtin_arm_wsrp) 2824 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2825 2826 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2827 return true; 2828 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2829 return true; 2830 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2831 return true; 2832 2833 // For intrinsics which take an immediate value as part of the instruction, 2834 // range check them here. 2835 // FIXME: VFP Intrinsics should error if VFP not present. 2836 switch (BuiltinID) { 2837 default: return false; 2838 case ARM::BI__builtin_arm_ssat: 2839 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2840 case ARM::BI__builtin_arm_usat: 2841 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2842 case ARM::BI__builtin_arm_ssat16: 2843 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2844 case ARM::BI__builtin_arm_usat16: 2845 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2846 case ARM::BI__builtin_arm_vcvtr_f: 2847 case ARM::BI__builtin_arm_vcvtr_d: 2848 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2849 case ARM::BI__builtin_arm_dmb: 2850 case ARM::BI__builtin_arm_dsb: 2851 case ARM::BI__builtin_arm_isb: 2852 case ARM::BI__builtin_arm_dbg: 2853 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2854 case ARM::BI__builtin_arm_cdp: 2855 case ARM::BI__builtin_arm_cdp2: 2856 case ARM::BI__builtin_arm_mcr: 2857 case ARM::BI__builtin_arm_mcr2: 2858 case ARM::BI__builtin_arm_mrc: 2859 case ARM::BI__builtin_arm_mrc2: 2860 case ARM::BI__builtin_arm_mcrr: 2861 case ARM::BI__builtin_arm_mcrr2: 2862 case ARM::BI__builtin_arm_mrrc: 2863 case ARM::BI__builtin_arm_mrrc2: 2864 case ARM::BI__builtin_arm_ldc: 2865 case ARM::BI__builtin_arm_ldcl: 2866 case ARM::BI__builtin_arm_ldc2: 2867 case ARM::BI__builtin_arm_ldc2l: 2868 case ARM::BI__builtin_arm_stc: 2869 case ARM::BI__builtin_arm_stcl: 2870 case ARM::BI__builtin_arm_stc2: 2871 case ARM::BI__builtin_arm_stc2l: 2872 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2873 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2874 /*WantCDE*/ false); 2875 } 2876 } 2877 2878 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2879 unsigned BuiltinID, 2880 CallExpr *TheCall) { 2881 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2882 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2883 BuiltinID == AArch64::BI__builtin_arm_strex || 2884 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2885 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2886 } 2887 2888 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2889 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2890 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2891 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2892 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2893 } 2894 2895 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2896 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2897 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2898 2899 // Memory Tagging Extensions (MTE) Intrinsics 2900 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2901 BuiltinID == AArch64::BI__builtin_arm_addg || 2902 BuiltinID == AArch64::BI__builtin_arm_gmi || 2903 BuiltinID == AArch64::BI__builtin_arm_ldg || 2904 BuiltinID == AArch64::BI__builtin_arm_stg || 2905 BuiltinID == AArch64::BI__builtin_arm_subp) { 2906 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2907 } 2908 2909 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2910 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2911 BuiltinID == AArch64::BI__builtin_arm_wsr || 2912 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2913 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2914 2915 // Only check the valid encoding range. Any constant in this range would be 2916 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2917 // an exception for incorrect registers. This matches MSVC behavior. 2918 if (BuiltinID == AArch64::BI_ReadStatusReg || 2919 BuiltinID == AArch64::BI_WriteStatusReg) 2920 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2921 2922 if (BuiltinID == AArch64::BI__getReg) 2923 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2924 2925 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2926 return true; 2927 2928 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2929 return true; 2930 2931 // For intrinsics which take an immediate value as part of the instruction, 2932 // range check them here. 2933 unsigned i = 0, l = 0, u = 0; 2934 switch (BuiltinID) { 2935 default: return false; 2936 case AArch64::BI__builtin_arm_dmb: 2937 case AArch64::BI__builtin_arm_dsb: 2938 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2939 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2940 } 2941 2942 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2943 } 2944 2945 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2946 if (Arg->getType()->getAsPlaceholderType()) 2947 return false; 2948 2949 // The first argument needs to be a record field access. 2950 // If it is an array element access, we delay decision 2951 // to BPF backend to check whether the access is a 2952 // field access or not. 2953 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2954 isa<MemberExpr>(Arg->IgnoreParens()) || 2955 isa<ArraySubscriptExpr>(Arg->IgnoreParens())); 2956 } 2957 2958 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2959 QualType VectorTy, QualType EltTy) { 2960 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2961 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2962 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2963 << Call->getSourceRange() << VectorEltTy << EltTy; 2964 return false; 2965 } 2966 return true; 2967 } 2968 2969 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2970 QualType ArgType = Arg->getType(); 2971 if (ArgType->getAsPlaceholderType()) 2972 return false; 2973 2974 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2975 // format: 2976 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2977 // 2. <type> var; 2978 // __builtin_preserve_type_info(var, flag); 2979 if (!isa<DeclRefExpr>(Arg->IgnoreParens()) && 2980 !isa<UnaryOperator>(Arg->IgnoreParens())) 2981 return false; 2982 2983 // Typedef type. 2984 if (ArgType->getAs<TypedefType>()) 2985 return true; 2986 2987 // Record type or Enum type. 2988 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2989 if (const auto *RT = Ty->getAs<RecordType>()) { 2990 if (!RT->getDecl()->getDeclName().isEmpty()) 2991 return true; 2992 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2993 if (!ET->getDecl()->getDeclName().isEmpty()) 2994 return true; 2995 } 2996 2997 return false; 2998 } 2999 3000 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 3001 QualType ArgType = Arg->getType(); 3002 if (ArgType->getAsPlaceholderType()) 3003 return false; 3004 3005 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 3006 // format: 3007 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 3008 // flag); 3009 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 3010 if (!UO) 3011 return false; 3012 3013 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 3014 if (!CE) 3015 return false; 3016 if (CE->getCastKind() != CK_IntegralToPointer && 3017 CE->getCastKind() != CK_NullToPointer) 3018 return false; 3019 3020 // The integer must be from an EnumConstantDecl. 3021 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 3022 if (!DR) 3023 return false; 3024 3025 const EnumConstantDecl *Enumerator = 3026 dyn_cast<EnumConstantDecl>(DR->getDecl()); 3027 if (!Enumerator) 3028 return false; 3029 3030 // The type must be EnumType. 3031 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 3032 const auto *ET = Ty->getAs<EnumType>(); 3033 if (!ET) 3034 return false; 3035 3036 // The enum value must be supported. 3037 return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator); 3038 } 3039 3040 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 3041 CallExpr *TheCall) { 3042 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 3043 BuiltinID == BPF::BI__builtin_btf_type_id || 3044 BuiltinID == BPF::BI__builtin_preserve_type_info || 3045 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 3046 "unexpected BPF builtin"); 3047 3048 if (checkArgCount(*this, TheCall, 2)) 3049 return true; 3050 3051 // The second argument needs to be a constant int 3052 Expr *Arg = TheCall->getArg(1); 3053 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 3054 diag::kind kind; 3055 if (!Value) { 3056 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 3057 kind = diag::err_preserve_field_info_not_const; 3058 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 3059 kind = diag::err_btf_type_id_not_const; 3060 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 3061 kind = diag::err_preserve_type_info_not_const; 3062 else 3063 kind = diag::err_preserve_enum_value_not_const; 3064 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 3065 return true; 3066 } 3067 3068 // The first argument 3069 Arg = TheCall->getArg(0); 3070 bool InvalidArg = false; 3071 bool ReturnUnsignedInt = true; 3072 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 3073 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 3074 InvalidArg = true; 3075 kind = diag::err_preserve_field_info_not_field; 3076 } 3077 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 3078 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 3079 InvalidArg = true; 3080 kind = diag::err_preserve_type_info_invalid; 3081 } 3082 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 3083 if (!isValidBPFPreserveEnumValueArg(Arg)) { 3084 InvalidArg = true; 3085 kind = diag::err_preserve_enum_value_invalid; 3086 } 3087 ReturnUnsignedInt = false; 3088 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 3089 ReturnUnsignedInt = false; 3090 } 3091 3092 if (InvalidArg) { 3093 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 3094 return true; 3095 } 3096 3097 if (ReturnUnsignedInt) 3098 TheCall->setType(Context.UnsignedIntTy); 3099 else 3100 TheCall->setType(Context.UnsignedLongTy); 3101 return false; 3102 } 3103 3104 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3105 struct ArgInfo { 3106 uint8_t OpNum; 3107 bool IsSigned; 3108 uint8_t BitWidth; 3109 uint8_t Align; 3110 }; 3111 struct BuiltinInfo { 3112 unsigned BuiltinID; 3113 ArgInfo Infos[2]; 3114 }; 3115 3116 static BuiltinInfo Infos[] = { 3117 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 3118 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 3119 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 3120 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 3121 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 3122 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 3123 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 3124 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 3125 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 3126 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 3127 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 3128 3129 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 3130 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 3131 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 3132 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 3133 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 3134 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 3135 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 3136 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 3137 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 3138 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 3139 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 3140 3141 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 3142 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 3143 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 3144 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 3145 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 3146 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 3147 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 3148 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 3149 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 3150 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 3151 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 3152 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 3153 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 3154 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 3155 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 3156 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 3157 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 3158 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 3159 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 3160 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 3161 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 3162 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 3163 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 3164 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 3165 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 3166 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 3167 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 3168 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 3169 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 3170 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 3171 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 3172 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 3173 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 3174 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 3175 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 3176 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 3177 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 3178 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 3179 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 3180 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 3181 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 3182 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 3183 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 3184 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 3185 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 3186 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 3187 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 3188 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 3189 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 3190 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 3191 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 3192 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 3193 {{ 1, false, 6, 0 }} }, 3194 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 3195 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 3196 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 3197 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 3198 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 3199 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 3200 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 3201 {{ 1, false, 5, 0 }} }, 3202 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 3203 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 3204 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 3205 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 3206 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 3207 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 3208 { 2, false, 5, 0 }} }, 3209 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 3210 { 2, false, 6, 0 }} }, 3211 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 3212 { 3, false, 5, 0 }} }, 3213 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 3214 { 3, false, 6, 0 }} }, 3215 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 3216 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 3217 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 3218 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 3219 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 3220 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 3221 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 3222 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 3223 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 3224 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 3225 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 3226 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 3227 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 3228 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 3229 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 3230 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 3231 {{ 2, false, 4, 0 }, 3232 { 3, false, 5, 0 }} }, 3233 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 3234 {{ 2, false, 4, 0 }, 3235 { 3, false, 5, 0 }} }, 3236 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 3237 {{ 2, false, 4, 0 }, 3238 { 3, false, 5, 0 }} }, 3239 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 3240 {{ 2, false, 4, 0 }, 3241 { 3, false, 5, 0 }} }, 3242 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 3243 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 3244 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 3245 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 3246 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 3247 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 3248 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 3249 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 3250 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 3251 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 3252 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 3253 { 2, false, 5, 0 }} }, 3254 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 3255 { 2, false, 6, 0 }} }, 3256 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 3257 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 3258 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 3259 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 3260 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 3261 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 3262 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 3263 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 3264 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 3265 {{ 1, false, 4, 0 }} }, 3266 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 3267 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 3268 {{ 1, false, 4, 0 }} }, 3269 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 3270 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 3271 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 3272 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 3273 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 3274 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 3275 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 3276 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 3277 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 3278 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 3279 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 3280 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 3281 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 3282 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 3283 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 3284 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 3285 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 3286 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 3287 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 3288 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 3289 {{ 3, false, 1, 0 }} }, 3290 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 3291 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 3292 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 3293 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 3294 {{ 3, false, 1, 0 }} }, 3295 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 3296 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 3297 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 3298 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 3299 {{ 3, false, 1, 0 }} }, 3300 }; 3301 3302 // Use a dynamically initialized static to sort the table exactly once on 3303 // first run. 3304 static const bool SortOnce = 3305 (llvm::sort(Infos, 3306 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 3307 return LHS.BuiltinID < RHS.BuiltinID; 3308 }), 3309 true); 3310 (void)SortOnce; 3311 3312 const BuiltinInfo *F = llvm::partition_point( 3313 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 3314 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 3315 return false; 3316 3317 bool Error = false; 3318 3319 for (const ArgInfo &A : F->Infos) { 3320 // Ignore empty ArgInfo elements. 3321 if (A.BitWidth == 0) 3322 continue; 3323 3324 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 3325 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 3326 if (!A.Align) { 3327 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3328 } else { 3329 unsigned M = 1 << A.Align; 3330 Min *= M; 3331 Max *= M; 3332 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3333 Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 3334 } 3335 } 3336 return Error; 3337 } 3338 3339 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 3340 CallExpr *TheCall) { 3341 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 3342 } 3343 3344 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 3345 unsigned BuiltinID, CallExpr *TheCall) { 3346 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 3347 CheckMipsBuiltinArgument(BuiltinID, TheCall); 3348 } 3349 3350 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 3351 CallExpr *TheCall) { 3352 3353 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 3354 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3355 if (!TI.hasFeature("dsp")) 3356 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3357 } 3358 3359 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3360 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3361 if (!TI.hasFeature("dspr2")) 3362 return Diag(TheCall->getBeginLoc(), 3363 diag::err_mips_builtin_requires_dspr2); 3364 } 3365 3366 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3367 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3368 if (!TI.hasFeature("msa")) 3369 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3370 } 3371 3372 return false; 3373 } 3374 3375 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3376 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3377 // ordering for DSP is unspecified. MSA is ordered by the data format used 3378 // by the underlying instruction i.e., df/m, df/n and then by size. 3379 // 3380 // FIXME: The size tests here should instead be tablegen'd along with the 3381 // definitions from include/clang/Basic/BuiltinsMips.def. 3382 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3383 // be too. 3384 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3385 unsigned i = 0, l = 0, u = 0, m = 0; 3386 switch (BuiltinID) { 3387 default: return false; 3388 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3389 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3390 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3391 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3392 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3393 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3394 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3395 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3396 // df/m field. 3397 // These intrinsics take an unsigned 3 bit immediate. 3398 case Mips::BI__builtin_msa_bclri_b: 3399 case Mips::BI__builtin_msa_bnegi_b: 3400 case Mips::BI__builtin_msa_bseti_b: 3401 case Mips::BI__builtin_msa_sat_s_b: 3402 case Mips::BI__builtin_msa_sat_u_b: 3403 case Mips::BI__builtin_msa_slli_b: 3404 case Mips::BI__builtin_msa_srai_b: 3405 case Mips::BI__builtin_msa_srari_b: 3406 case Mips::BI__builtin_msa_srli_b: 3407 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3408 case Mips::BI__builtin_msa_binsli_b: 3409 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3410 // These intrinsics take an unsigned 4 bit immediate. 3411 case Mips::BI__builtin_msa_bclri_h: 3412 case Mips::BI__builtin_msa_bnegi_h: 3413 case Mips::BI__builtin_msa_bseti_h: 3414 case Mips::BI__builtin_msa_sat_s_h: 3415 case Mips::BI__builtin_msa_sat_u_h: 3416 case Mips::BI__builtin_msa_slli_h: 3417 case Mips::BI__builtin_msa_srai_h: 3418 case Mips::BI__builtin_msa_srari_h: 3419 case Mips::BI__builtin_msa_srli_h: 3420 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3421 case Mips::BI__builtin_msa_binsli_h: 3422 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3423 // These intrinsics take an unsigned 5 bit immediate. 3424 // The first block of intrinsics actually have an unsigned 5 bit field, 3425 // not a df/n field. 3426 case Mips::BI__builtin_msa_cfcmsa: 3427 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3428 case Mips::BI__builtin_msa_clei_u_b: 3429 case Mips::BI__builtin_msa_clei_u_h: 3430 case Mips::BI__builtin_msa_clei_u_w: 3431 case Mips::BI__builtin_msa_clei_u_d: 3432 case Mips::BI__builtin_msa_clti_u_b: 3433 case Mips::BI__builtin_msa_clti_u_h: 3434 case Mips::BI__builtin_msa_clti_u_w: 3435 case Mips::BI__builtin_msa_clti_u_d: 3436 case Mips::BI__builtin_msa_maxi_u_b: 3437 case Mips::BI__builtin_msa_maxi_u_h: 3438 case Mips::BI__builtin_msa_maxi_u_w: 3439 case Mips::BI__builtin_msa_maxi_u_d: 3440 case Mips::BI__builtin_msa_mini_u_b: 3441 case Mips::BI__builtin_msa_mini_u_h: 3442 case Mips::BI__builtin_msa_mini_u_w: 3443 case Mips::BI__builtin_msa_mini_u_d: 3444 case Mips::BI__builtin_msa_addvi_b: 3445 case Mips::BI__builtin_msa_addvi_h: 3446 case Mips::BI__builtin_msa_addvi_w: 3447 case Mips::BI__builtin_msa_addvi_d: 3448 case Mips::BI__builtin_msa_bclri_w: 3449 case Mips::BI__builtin_msa_bnegi_w: 3450 case Mips::BI__builtin_msa_bseti_w: 3451 case Mips::BI__builtin_msa_sat_s_w: 3452 case Mips::BI__builtin_msa_sat_u_w: 3453 case Mips::BI__builtin_msa_slli_w: 3454 case Mips::BI__builtin_msa_srai_w: 3455 case Mips::BI__builtin_msa_srari_w: 3456 case Mips::BI__builtin_msa_srli_w: 3457 case Mips::BI__builtin_msa_srlri_w: 3458 case Mips::BI__builtin_msa_subvi_b: 3459 case Mips::BI__builtin_msa_subvi_h: 3460 case Mips::BI__builtin_msa_subvi_w: 3461 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3462 case Mips::BI__builtin_msa_binsli_w: 3463 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3464 // These intrinsics take an unsigned 6 bit immediate. 3465 case Mips::BI__builtin_msa_bclri_d: 3466 case Mips::BI__builtin_msa_bnegi_d: 3467 case Mips::BI__builtin_msa_bseti_d: 3468 case Mips::BI__builtin_msa_sat_s_d: 3469 case Mips::BI__builtin_msa_sat_u_d: 3470 case Mips::BI__builtin_msa_slli_d: 3471 case Mips::BI__builtin_msa_srai_d: 3472 case Mips::BI__builtin_msa_srari_d: 3473 case Mips::BI__builtin_msa_srli_d: 3474 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3475 case Mips::BI__builtin_msa_binsli_d: 3476 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3477 // These intrinsics take a signed 5 bit immediate. 3478 case Mips::BI__builtin_msa_ceqi_b: 3479 case Mips::BI__builtin_msa_ceqi_h: 3480 case Mips::BI__builtin_msa_ceqi_w: 3481 case Mips::BI__builtin_msa_ceqi_d: 3482 case Mips::BI__builtin_msa_clti_s_b: 3483 case Mips::BI__builtin_msa_clti_s_h: 3484 case Mips::BI__builtin_msa_clti_s_w: 3485 case Mips::BI__builtin_msa_clti_s_d: 3486 case Mips::BI__builtin_msa_clei_s_b: 3487 case Mips::BI__builtin_msa_clei_s_h: 3488 case Mips::BI__builtin_msa_clei_s_w: 3489 case Mips::BI__builtin_msa_clei_s_d: 3490 case Mips::BI__builtin_msa_maxi_s_b: 3491 case Mips::BI__builtin_msa_maxi_s_h: 3492 case Mips::BI__builtin_msa_maxi_s_w: 3493 case Mips::BI__builtin_msa_maxi_s_d: 3494 case Mips::BI__builtin_msa_mini_s_b: 3495 case Mips::BI__builtin_msa_mini_s_h: 3496 case Mips::BI__builtin_msa_mini_s_w: 3497 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3498 // These intrinsics take an unsigned 8 bit immediate. 3499 case Mips::BI__builtin_msa_andi_b: 3500 case Mips::BI__builtin_msa_nori_b: 3501 case Mips::BI__builtin_msa_ori_b: 3502 case Mips::BI__builtin_msa_shf_b: 3503 case Mips::BI__builtin_msa_shf_h: 3504 case Mips::BI__builtin_msa_shf_w: 3505 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3506 case Mips::BI__builtin_msa_bseli_b: 3507 case Mips::BI__builtin_msa_bmnzi_b: 3508 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3509 // df/n format 3510 // These intrinsics take an unsigned 4 bit immediate. 3511 case Mips::BI__builtin_msa_copy_s_b: 3512 case Mips::BI__builtin_msa_copy_u_b: 3513 case Mips::BI__builtin_msa_insve_b: 3514 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3515 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3516 // These intrinsics take an unsigned 3 bit immediate. 3517 case Mips::BI__builtin_msa_copy_s_h: 3518 case Mips::BI__builtin_msa_copy_u_h: 3519 case Mips::BI__builtin_msa_insve_h: 3520 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3521 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3522 // These intrinsics take an unsigned 2 bit immediate. 3523 case Mips::BI__builtin_msa_copy_s_w: 3524 case Mips::BI__builtin_msa_copy_u_w: 3525 case Mips::BI__builtin_msa_insve_w: 3526 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3527 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3528 // These intrinsics take an unsigned 1 bit immediate. 3529 case Mips::BI__builtin_msa_copy_s_d: 3530 case Mips::BI__builtin_msa_copy_u_d: 3531 case Mips::BI__builtin_msa_insve_d: 3532 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3533 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3534 // Memory offsets and immediate loads. 3535 // These intrinsics take a signed 10 bit immediate. 3536 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3537 case Mips::BI__builtin_msa_ldi_h: 3538 case Mips::BI__builtin_msa_ldi_w: 3539 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3540 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3541 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3542 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3543 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3544 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3545 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3546 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3547 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3548 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3549 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3550 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3551 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3552 } 3553 3554 if (!m) 3555 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3556 3557 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3558 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3559 } 3560 3561 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3562 /// advancing the pointer over the consumed characters. The decoded type is 3563 /// returned. If the decoded type represents a constant integer with a 3564 /// constraint on its value then Mask is set to that value. The type descriptors 3565 /// used in Str are specific to PPC MMA builtins and are documented in the file 3566 /// defining the PPC builtins. 3567 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3568 unsigned &Mask) { 3569 bool RequireICE = false; 3570 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3571 switch (*Str++) { 3572 case 'V': 3573 return Context.getVectorType(Context.UnsignedCharTy, 16, 3574 VectorType::VectorKind::AltiVecVector); 3575 case 'i': { 3576 char *End; 3577 unsigned size = strtoul(Str, &End, 10); 3578 assert(End != Str && "Missing constant parameter constraint"); 3579 Str = End; 3580 Mask = size; 3581 return Context.IntTy; 3582 } 3583 case 'W': { 3584 char *End; 3585 unsigned size = strtoul(Str, &End, 10); 3586 assert(End != Str && "Missing PowerPC MMA type size"); 3587 Str = End; 3588 QualType Type; 3589 switch (size) { 3590 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3591 case size: Type = Context.Id##Ty; break; 3592 #include "clang/Basic/PPCTypes.def" 3593 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3594 } 3595 bool CheckVectorArgs = false; 3596 while (!CheckVectorArgs) { 3597 switch (*Str++) { 3598 case '*': 3599 Type = Context.getPointerType(Type); 3600 break; 3601 case 'C': 3602 Type = Type.withConst(); 3603 break; 3604 default: 3605 CheckVectorArgs = true; 3606 --Str; 3607 break; 3608 } 3609 } 3610 return Type; 3611 } 3612 default: 3613 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3614 } 3615 } 3616 3617 static bool isPPC_64Builtin(unsigned BuiltinID) { 3618 // These builtins only work on PPC 64bit targets. 3619 switch (BuiltinID) { 3620 case PPC::BI__builtin_divde: 3621 case PPC::BI__builtin_divdeu: 3622 case PPC::BI__builtin_bpermd: 3623 case PPC::BI__builtin_pdepd: 3624 case PPC::BI__builtin_pextd: 3625 case PPC::BI__builtin_ppc_ldarx: 3626 case PPC::BI__builtin_ppc_stdcx: 3627 case PPC::BI__builtin_ppc_tdw: 3628 case PPC::BI__builtin_ppc_trapd: 3629 case PPC::BI__builtin_ppc_cmpeqb: 3630 case PPC::BI__builtin_ppc_setb: 3631 case PPC::BI__builtin_ppc_mulhd: 3632 case PPC::BI__builtin_ppc_mulhdu: 3633 case PPC::BI__builtin_ppc_maddhd: 3634 case PPC::BI__builtin_ppc_maddhdu: 3635 case PPC::BI__builtin_ppc_maddld: 3636 case PPC::BI__builtin_ppc_load8r: 3637 case PPC::BI__builtin_ppc_store8r: 3638 case PPC::BI__builtin_ppc_insert_exp: 3639 case PPC::BI__builtin_ppc_extract_sig: 3640 case PPC::BI__builtin_ppc_addex: 3641 case PPC::BI__builtin_darn: 3642 case PPC::BI__builtin_darn_raw: 3643 case PPC::BI__builtin_ppc_compare_and_swaplp: 3644 case PPC::BI__builtin_ppc_fetch_and_addlp: 3645 case PPC::BI__builtin_ppc_fetch_and_andlp: 3646 case PPC::BI__builtin_ppc_fetch_and_orlp: 3647 case PPC::BI__builtin_ppc_fetch_and_swaplp: 3648 return true; 3649 } 3650 return false; 3651 } 3652 3653 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3654 StringRef FeatureToCheck, unsigned DiagID, 3655 StringRef DiagArg = "") { 3656 if (S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3657 return false; 3658 3659 if (DiagArg.empty()) 3660 S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3661 else 3662 S.Diag(TheCall->getBeginLoc(), DiagID) 3663 << DiagArg << TheCall->getSourceRange(); 3664 3665 return true; 3666 } 3667 3668 /// Returns true if the argument consists of one contiguous run of 1s with any 3669 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so 3670 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, 3671 /// since all 1s are not contiguous. 3672 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { 3673 llvm::APSInt Result; 3674 // We can't check the value of a dependent argument. 3675 Expr *Arg = TheCall->getArg(ArgNum); 3676 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3677 return false; 3678 3679 // Check constant-ness first. 3680 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3681 return true; 3682 3683 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. 3684 if (Result.isShiftedMask() || (~Result).isShiftedMask()) 3685 return false; 3686 3687 return Diag(TheCall->getBeginLoc(), 3688 diag::err_argument_not_contiguous_bit_field) 3689 << ArgNum << Arg->getSourceRange(); 3690 } 3691 3692 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3693 CallExpr *TheCall) { 3694 unsigned i = 0, l = 0, u = 0; 3695 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3696 llvm::APSInt Result; 3697 3698 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3699 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3700 << TheCall->getSourceRange(); 3701 3702 switch (BuiltinID) { 3703 default: return false; 3704 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3705 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3706 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3707 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3708 case PPC::BI__builtin_altivec_dss: 3709 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3710 case PPC::BI__builtin_tbegin: 3711 case PPC::BI__builtin_tend: 3712 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 1) || 3713 SemaFeatureCheck(*this, TheCall, "htm", 3714 diag::err_ppc_builtin_requires_htm); 3715 case PPC::BI__builtin_tsr: 3716 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3717 SemaFeatureCheck(*this, TheCall, "htm", 3718 diag::err_ppc_builtin_requires_htm); 3719 case PPC::BI__builtin_tabortwc: 3720 case PPC::BI__builtin_tabortdc: 3721 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3722 SemaFeatureCheck(*this, TheCall, "htm", 3723 diag::err_ppc_builtin_requires_htm); 3724 case PPC::BI__builtin_tabortwci: 3725 case PPC::BI__builtin_tabortdci: 3726 return SemaFeatureCheck(*this, TheCall, "htm", 3727 diag::err_ppc_builtin_requires_htm) || 3728 (SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3729 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31)); 3730 case PPC::BI__builtin_tabort: 3731 case PPC::BI__builtin_tcheck: 3732 case PPC::BI__builtin_treclaim: 3733 case PPC::BI__builtin_trechkpt: 3734 case PPC::BI__builtin_tendall: 3735 case PPC::BI__builtin_tresume: 3736 case PPC::BI__builtin_tsuspend: 3737 case PPC::BI__builtin_get_texasr: 3738 case PPC::BI__builtin_get_texasru: 3739 case PPC::BI__builtin_get_tfhar: 3740 case PPC::BI__builtin_get_tfiar: 3741 case PPC::BI__builtin_set_texasr: 3742 case PPC::BI__builtin_set_texasru: 3743 case PPC::BI__builtin_set_tfhar: 3744 case PPC::BI__builtin_set_tfiar: 3745 case PPC::BI__builtin_ttest: 3746 return SemaFeatureCheck(*this, TheCall, "htm", 3747 diag::err_ppc_builtin_requires_htm); 3748 // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05', 3749 // __builtin_(un)pack_longdouble are available only if long double uses IBM 3750 // extended double representation. 3751 case PPC::BI__builtin_unpack_longdouble: 3752 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1)) 3753 return true; 3754 LLVM_FALLTHROUGH; 3755 case PPC::BI__builtin_pack_longdouble: 3756 if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble()) 3757 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi) 3758 << "ibmlongdouble"; 3759 return false; 3760 case PPC::BI__builtin_altivec_dst: 3761 case PPC::BI__builtin_altivec_dstt: 3762 case PPC::BI__builtin_altivec_dstst: 3763 case PPC::BI__builtin_altivec_dststt: 3764 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3765 case PPC::BI__builtin_vsx_xxpermdi: 3766 case PPC::BI__builtin_vsx_xxsldwi: 3767 return SemaBuiltinVSX(TheCall); 3768 case PPC::BI__builtin_divwe: 3769 case PPC::BI__builtin_divweu: 3770 case PPC::BI__builtin_divde: 3771 case PPC::BI__builtin_divdeu: 3772 return SemaFeatureCheck(*this, TheCall, "extdiv", 3773 diag::err_ppc_builtin_only_on_arch, "7"); 3774 case PPC::BI__builtin_bpermd: 3775 return SemaFeatureCheck(*this, TheCall, "bpermd", 3776 diag::err_ppc_builtin_only_on_arch, "7"); 3777 case PPC::BI__builtin_unpack_vector_int128: 3778 return SemaFeatureCheck(*this, TheCall, "vsx", 3779 diag::err_ppc_builtin_only_on_arch, "7") || 3780 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3781 case PPC::BI__builtin_pack_vector_int128: 3782 return SemaFeatureCheck(*this, TheCall, "vsx", 3783 diag::err_ppc_builtin_only_on_arch, "7"); 3784 case PPC::BI__builtin_pdepd: 3785 case PPC::BI__builtin_pextd: 3786 return SemaFeatureCheck(*this, TheCall, "isa-v31-instructions", 3787 diag::err_ppc_builtin_only_on_arch, "10"); 3788 case PPC::BI__builtin_altivec_vgnb: 3789 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3790 case PPC::BI__builtin_altivec_vec_replace_elt: 3791 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3792 QualType VecTy = TheCall->getArg(0)->getType(); 3793 QualType EltTy = TheCall->getArg(1)->getType(); 3794 unsigned Width = Context.getIntWidth(EltTy); 3795 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3796 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3797 } 3798 case PPC::BI__builtin_vsx_xxeval: 3799 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3800 case PPC::BI__builtin_altivec_vsldbi: 3801 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3802 case PPC::BI__builtin_altivec_vsrdbi: 3803 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3804 case PPC::BI__builtin_vsx_xxpermx: 3805 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3806 case PPC::BI__builtin_ppc_tw: 3807 case PPC::BI__builtin_ppc_tdw: 3808 return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31); 3809 case PPC::BI__builtin_ppc_cmpeqb: 3810 case PPC::BI__builtin_ppc_setb: 3811 case PPC::BI__builtin_ppc_maddhd: 3812 case PPC::BI__builtin_ppc_maddhdu: 3813 case PPC::BI__builtin_ppc_maddld: 3814 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3815 diag::err_ppc_builtin_only_on_arch, "9"); 3816 case PPC::BI__builtin_ppc_cmprb: 3817 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3818 diag::err_ppc_builtin_only_on_arch, "9") || 3819 SemaBuiltinConstantArgRange(TheCall, 0, 0, 1); 3820 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must 3821 // be a constant that represents a contiguous bit field. 3822 case PPC::BI__builtin_ppc_rlwnm: 3823 return SemaValueIsRunOfOnes(TheCall, 2); 3824 case PPC::BI__builtin_ppc_rlwimi: 3825 case PPC::BI__builtin_ppc_rldimi: 3826 return SemaBuiltinConstantArg(TheCall, 2, Result) || 3827 SemaValueIsRunOfOnes(TheCall, 3); 3828 case PPC::BI__builtin_ppc_extract_exp: 3829 case PPC::BI__builtin_ppc_extract_sig: 3830 case PPC::BI__builtin_ppc_insert_exp: 3831 return SemaFeatureCheck(*this, TheCall, "power9-vector", 3832 diag::err_ppc_builtin_only_on_arch, "9"); 3833 case PPC::BI__builtin_ppc_addex: { 3834 if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3835 diag::err_ppc_builtin_only_on_arch, "9") || 3836 SemaBuiltinConstantArgRange(TheCall, 2, 0, 3)) 3837 return true; 3838 // Output warning for reserved values 1 to 3. 3839 int ArgValue = 3840 TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue(); 3841 if (ArgValue != 0) 3842 Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour) 3843 << ArgValue; 3844 return false; 3845 } 3846 case PPC::BI__builtin_ppc_mtfsb0: 3847 case PPC::BI__builtin_ppc_mtfsb1: 3848 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 3849 case PPC::BI__builtin_ppc_mtfsf: 3850 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255); 3851 case PPC::BI__builtin_ppc_mtfsfi: 3852 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3853 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3854 case PPC::BI__builtin_ppc_alignx: 3855 return SemaBuiltinConstantArgPower2(TheCall, 0); 3856 case PPC::BI__builtin_ppc_rdlam: 3857 return SemaValueIsRunOfOnes(TheCall, 2); 3858 case PPC::BI__builtin_ppc_icbt: 3859 case PPC::BI__builtin_ppc_sthcx: 3860 case PPC::BI__builtin_ppc_stbcx: 3861 case PPC::BI__builtin_ppc_lharx: 3862 case PPC::BI__builtin_ppc_lbarx: 3863 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3864 diag::err_ppc_builtin_only_on_arch, "8"); 3865 case PPC::BI__builtin_vsx_ldrmb: 3866 case PPC::BI__builtin_vsx_strmb: 3867 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3868 diag::err_ppc_builtin_only_on_arch, "8") || 3869 SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 3870 case PPC::BI__builtin_altivec_vcntmbb: 3871 case PPC::BI__builtin_altivec_vcntmbh: 3872 case PPC::BI__builtin_altivec_vcntmbw: 3873 case PPC::BI__builtin_altivec_vcntmbd: 3874 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3875 case PPC::BI__builtin_darn: 3876 case PPC::BI__builtin_darn_raw: 3877 case PPC::BI__builtin_darn_32: 3878 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3879 diag::err_ppc_builtin_only_on_arch, "9"); 3880 case PPC::BI__builtin_vsx_xxgenpcvbm: 3881 case PPC::BI__builtin_vsx_xxgenpcvhm: 3882 case PPC::BI__builtin_vsx_xxgenpcvwm: 3883 case PPC::BI__builtin_vsx_xxgenpcvdm: 3884 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3885 case PPC::BI__builtin_ppc_compare_exp_uo: 3886 case PPC::BI__builtin_ppc_compare_exp_lt: 3887 case PPC::BI__builtin_ppc_compare_exp_gt: 3888 case PPC::BI__builtin_ppc_compare_exp_eq: 3889 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3890 diag::err_ppc_builtin_only_on_arch, "9") || 3891 SemaFeatureCheck(*this, TheCall, "vsx", 3892 diag::err_ppc_builtin_requires_vsx); 3893 case PPC::BI__builtin_ppc_test_data_class: { 3894 // Check if the first argument of the __builtin_ppc_test_data_class call is 3895 // valid. The argument must be either a 'float' or a 'double'. 3896 QualType ArgType = TheCall->getArg(0)->getType(); 3897 if (ArgType != QualType(Context.FloatTy) && 3898 ArgType != QualType(Context.DoubleTy)) 3899 return Diag(TheCall->getBeginLoc(), 3900 diag::err_ppc_invalid_test_data_class_type); 3901 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3902 diag::err_ppc_builtin_only_on_arch, "9") || 3903 SemaFeatureCheck(*this, TheCall, "vsx", 3904 diag::err_ppc_builtin_requires_vsx) || 3905 SemaBuiltinConstantArgRange(TheCall, 1, 0, 127); 3906 } 3907 case PPC::BI__builtin_ppc_load8r: 3908 case PPC::BI__builtin_ppc_store8r: 3909 return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions", 3910 diag::err_ppc_builtin_only_on_arch, "7"); 3911 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3912 case PPC::BI__builtin_##Name: \ 3913 return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types); 3914 #include "clang/Basic/BuiltinsPPC.def" 3915 } 3916 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3917 } 3918 3919 // Check if the given type is a non-pointer PPC MMA type. This function is used 3920 // in Sema to prevent invalid uses of restricted PPC MMA types. 3921 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3922 if (Type->isPointerType() || Type->isArrayType()) 3923 return false; 3924 3925 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3926 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3927 if (false 3928 #include "clang/Basic/PPCTypes.def" 3929 ) { 3930 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3931 return true; 3932 } 3933 return false; 3934 } 3935 3936 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3937 CallExpr *TheCall) { 3938 // position of memory order and scope arguments in the builtin 3939 unsigned OrderIndex, ScopeIndex; 3940 switch (BuiltinID) { 3941 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3942 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3943 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3944 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3945 OrderIndex = 2; 3946 ScopeIndex = 3; 3947 break; 3948 case AMDGPU::BI__builtin_amdgcn_fence: 3949 OrderIndex = 0; 3950 ScopeIndex = 1; 3951 break; 3952 default: 3953 return false; 3954 } 3955 3956 ExprResult Arg = TheCall->getArg(OrderIndex); 3957 auto ArgExpr = Arg.get(); 3958 Expr::EvalResult ArgResult; 3959 3960 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3961 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3962 << ArgExpr->getType(); 3963 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3964 3965 // Check validity of memory ordering as per C11 / C++11's memody model. 3966 // Only fence needs check. Atomic dec/inc allow all memory orders. 3967 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3968 return Diag(ArgExpr->getBeginLoc(), 3969 diag::warn_atomic_op_has_invalid_memory_order) 3970 << ArgExpr->getSourceRange(); 3971 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3972 case llvm::AtomicOrderingCABI::relaxed: 3973 case llvm::AtomicOrderingCABI::consume: 3974 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3975 return Diag(ArgExpr->getBeginLoc(), 3976 diag::warn_atomic_op_has_invalid_memory_order) 3977 << ArgExpr->getSourceRange(); 3978 break; 3979 case llvm::AtomicOrderingCABI::acquire: 3980 case llvm::AtomicOrderingCABI::release: 3981 case llvm::AtomicOrderingCABI::acq_rel: 3982 case llvm::AtomicOrderingCABI::seq_cst: 3983 break; 3984 } 3985 3986 Arg = TheCall->getArg(ScopeIndex); 3987 ArgExpr = Arg.get(); 3988 Expr::EvalResult ArgResult1; 3989 // Check that sync scope is a constant literal 3990 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3991 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3992 << ArgExpr->getType(); 3993 3994 return false; 3995 } 3996 3997 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 3998 llvm::APSInt Result; 3999 4000 // We can't check the value of a dependent argument. 4001 Expr *Arg = TheCall->getArg(ArgNum); 4002 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4003 return false; 4004 4005 // Check constant-ness first. 4006 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4007 return true; 4008 4009 int64_t Val = Result.getSExtValue(); 4010 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 4011 return false; 4012 4013 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 4014 << Arg->getSourceRange(); 4015 } 4016 4017 static bool isRISCV32Builtin(unsigned BuiltinID) { 4018 // These builtins only work on riscv32 targets. 4019 switch (BuiltinID) { 4020 case RISCV::BI__builtin_riscv_zip_32: 4021 case RISCV::BI__builtin_riscv_unzip_32: 4022 case RISCV::BI__builtin_riscv_aes32dsi_32: 4023 case RISCV::BI__builtin_riscv_aes32dsmi_32: 4024 case RISCV::BI__builtin_riscv_aes32esi_32: 4025 case RISCV::BI__builtin_riscv_aes32esmi_32: 4026 case RISCV::BI__builtin_riscv_sha512sig0h_32: 4027 case RISCV::BI__builtin_riscv_sha512sig0l_32: 4028 case RISCV::BI__builtin_riscv_sha512sig1h_32: 4029 case RISCV::BI__builtin_riscv_sha512sig1l_32: 4030 case RISCV::BI__builtin_riscv_sha512sum0r_32: 4031 case RISCV::BI__builtin_riscv_sha512sum1r_32: 4032 return true; 4033 } 4034 4035 return false; 4036 } 4037 4038 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 4039 unsigned BuiltinID, 4040 CallExpr *TheCall) { 4041 // CodeGenFunction can also detect this, but this gives a better error 4042 // message. 4043 bool FeatureMissing = false; 4044 SmallVector<StringRef> ReqFeatures; 4045 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 4046 Features.split(ReqFeatures, ','); 4047 4048 // Check for 32-bit only builtins on a 64-bit target. 4049 const llvm::Triple &TT = TI.getTriple(); 4050 if (TT.getArch() != llvm::Triple::riscv32 && isRISCV32Builtin(BuiltinID)) 4051 return Diag(TheCall->getCallee()->getBeginLoc(), 4052 diag::err_32_bit_builtin_64_bit_tgt); 4053 4054 // Check if each required feature is included 4055 for (StringRef F : ReqFeatures) { 4056 SmallVector<StringRef> ReqOpFeatures; 4057 F.split(ReqOpFeatures, '|'); 4058 bool HasFeature = false; 4059 for (StringRef OF : ReqOpFeatures) { 4060 if (TI.hasFeature(OF)) { 4061 HasFeature = true; 4062 continue; 4063 } 4064 } 4065 4066 if (!HasFeature) { 4067 std::string FeatureStrs; 4068 for (StringRef OF : ReqOpFeatures) { 4069 // If the feature is 64bit, alter the string so it will print better in 4070 // the diagnostic. 4071 if (OF == "64bit") 4072 OF = "RV64"; 4073 4074 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 4075 OF.consume_front("experimental-"); 4076 std::string FeatureStr = OF.str(); 4077 FeatureStr[0] = std::toupper(FeatureStr[0]); 4078 // Combine strings. 4079 FeatureStrs += FeatureStrs == "" ? "" : ", "; 4080 FeatureStrs += "'"; 4081 FeatureStrs += FeatureStr; 4082 FeatureStrs += "'"; 4083 } 4084 // Error message 4085 FeatureMissing = true; 4086 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 4087 << TheCall->getSourceRange() << StringRef(FeatureStrs); 4088 } 4089 } 4090 4091 if (FeatureMissing) 4092 return true; 4093 4094 switch (BuiltinID) { 4095 case RISCVVector::BI__builtin_rvv_vsetvli: 4096 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 4097 CheckRISCVLMUL(TheCall, 2); 4098 case RISCVVector::BI__builtin_rvv_vsetvlimax: 4099 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 4100 CheckRISCVLMUL(TheCall, 1); 4101 case RISCVVector::BI__builtin_rvv_vget_v: { 4102 ASTContext::BuiltinVectorTypeInfo ResVecInfo = 4103 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>( 4104 TheCall->getType().getCanonicalType().getTypePtr())); 4105 ASTContext::BuiltinVectorTypeInfo VecInfo = 4106 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>( 4107 TheCall->getArg(0)->getType().getCanonicalType().getTypePtr())); 4108 unsigned MaxIndex = 4109 (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors) / 4110 (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors); 4111 return SemaBuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1); 4112 } 4113 case RISCVVector::BI__builtin_rvv_vset_v: { 4114 ASTContext::BuiltinVectorTypeInfo ResVecInfo = 4115 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>( 4116 TheCall->getType().getCanonicalType().getTypePtr())); 4117 ASTContext::BuiltinVectorTypeInfo VecInfo = 4118 Context.getBuiltinVectorTypeInfo(cast<BuiltinType>( 4119 TheCall->getArg(2)->getType().getCanonicalType().getTypePtr())); 4120 unsigned MaxIndex = 4121 (ResVecInfo.EC.getKnownMinValue() * ResVecInfo.NumVectors) / 4122 (VecInfo.EC.getKnownMinValue() * VecInfo.NumVectors); 4123 return SemaBuiltinConstantArgRange(TheCall, 1, 0, MaxIndex - 1); 4124 } 4125 // Check if byteselect is in [0, 3] 4126 case RISCV::BI__builtin_riscv_aes32dsi_32: 4127 case RISCV::BI__builtin_riscv_aes32dsmi_32: 4128 case RISCV::BI__builtin_riscv_aes32esi_32: 4129 case RISCV::BI__builtin_riscv_aes32esmi_32: 4130 case RISCV::BI__builtin_riscv_sm4ks: 4131 case RISCV::BI__builtin_riscv_sm4ed: 4132 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 4133 // Check if rnum is in [0, 10] 4134 case RISCV::BI__builtin_riscv_aes64ks1i_64: 4135 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 10); 4136 } 4137 4138 return false; 4139 } 4140 4141 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 4142 CallExpr *TheCall) { 4143 if (BuiltinID == SystemZ::BI__builtin_tabort) { 4144 Expr *Arg = TheCall->getArg(0); 4145 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 4146 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 4147 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 4148 << Arg->getSourceRange(); 4149 } 4150 4151 // For intrinsics which take an immediate value as part of the instruction, 4152 // range check them here. 4153 unsigned i = 0, l = 0, u = 0; 4154 switch (BuiltinID) { 4155 default: return false; 4156 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 4157 case SystemZ::BI__builtin_s390_verimb: 4158 case SystemZ::BI__builtin_s390_verimh: 4159 case SystemZ::BI__builtin_s390_verimf: 4160 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 4161 case SystemZ::BI__builtin_s390_vfaeb: 4162 case SystemZ::BI__builtin_s390_vfaeh: 4163 case SystemZ::BI__builtin_s390_vfaef: 4164 case SystemZ::BI__builtin_s390_vfaebs: 4165 case SystemZ::BI__builtin_s390_vfaehs: 4166 case SystemZ::BI__builtin_s390_vfaefs: 4167 case SystemZ::BI__builtin_s390_vfaezb: 4168 case SystemZ::BI__builtin_s390_vfaezh: 4169 case SystemZ::BI__builtin_s390_vfaezf: 4170 case SystemZ::BI__builtin_s390_vfaezbs: 4171 case SystemZ::BI__builtin_s390_vfaezhs: 4172 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 4173 case SystemZ::BI__builtin_s390_vfisb: 4174 case SystemZ::BI__builtin_s390_vfidb: 4175 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 4176 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 4177 case SystemZ::BI__builtin_s390_vftcisb: 4178 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 4179 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 4180 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 4181 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 4182 case SystemZ::BI__builtin_s390_vstrcb: 4183 case SystemZ::BI__builtin_s390_vstrch: 4184 case SystemZ::BI__builtin_s390_vstrcf: 4185 case SystemZ::BI__builtin_s390_vstrczb: 4186 case SystemZ::BI__builtin_s390_vstrczh: 4187 case SystemZ::BI__builtin_s390_vstrczf: 4188 case SystemZ::BI__builtin_s390_vstrcbs: 4189 case SystemZ::BI__builtin_s390_vstrchs: 4190 case SystemZ::BI__builtin_s390_vstrcfs: 4191 case SystemZ::BI__builtin_s390_vstrczbs: 4192 case SystemZ::BI__builtin_s390_vstrczhs: 4193 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 4194 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 4195 case SystemZ::BI__builtin_s390_vfminsb: 4196 case SystemZ::BI__builtin_s390_vfmaxsb: 4197 case SystemZ::BI__builtin_s390_vfmindb: 4198 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 4199 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 4200 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 4201 case SystemZ::BI__builtin_s390_vclfnhs: 4202 case SystemZ::BI__builtin_s390_vclfnls: 4203 case SystemZ::BI__builtin_s390_vcfn: 4204 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break; 4205 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break; 4206 } 4207 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 4208 } 4209 4210 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 4211 /// This checks that the target supports __builtin_cpu_supports and 4212 /// that the string argument is constant and valid. 4213 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 4214 CallExpr *TheCall) { 4215 Expr *Arg = TheCall->getArg(0); 4216 4217 // Check if the argument is a string literal. 4218 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4219 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 4220 << Arg->getSourceRange(); 4221 4222 // Check the contents of the string. 4223 StringRef Feature = 4224 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4225 if (!TI.validateCpuSupports(Feature)) 4226 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 4227 << Arg->getSourceRange(); 4228 return false; 4229 } 4230 4231 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 4232 /// This checks that the target supports __builtin_cpu_is and 4233 /// that the string argument is constant and valid. 4234 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 4235 Expr *Arg = TheCall->getArg(0); 4236 4237 // Check if the argument is a string literal. 4238 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4239 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 4240 << Arg->getSourceRange(); 4241 4242 // Check the contents of the string. 4243 StringRef Feature = 4244 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4245 if (!TI.validateCpuIs(Feature)) 4246 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 4247 << Arg->getSourceRange(); 4248 return false; 4249 } 4250 4251 // Check if the rounding mode is legal. 4252 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 4253 // Indicates if this instruction has rounding control or just SAE. 4254 bool HasRC = false; 4255 4256 unsigned ArgNum = 0; 4257 switch (BuiltinID) { 4258 default: 4259 return false; 4260 case X86::BI__builtin_ia32_vcvttsd2si32: 4261 case X86::BI__builtin_ia32_vcvttsd2si64: 4262 case X86::BI__builtin_ia32_vcvttsd2usi32: 4263 case X86::BI__builtin_ia32_vcvttsd2usi64: 4264 case X86::BI__builtin_ia32_vcvttss2si32: 4265 case X86::BI__builtin_ia32_vcvttss2si64: 4266 case X86::BI__builtin_ia32_vcvttss2usi32: 4267 case X86::BI__builtin_ia32_vcvttss2usi64: 4268 case X86::BI__builtin_ia32_vcvttsh2si32: 4269 case X86::BI__builtin_ia32_vcvttsh2si64: 4270 case X86::BI__builtin_ia32_vcvttsh2usi32: 4271 case X86::BI__builtin_ia32_vcvttsh2usi64: 4272 ArgNum = 1; 4273 break; 4274 case X86::BI__builtin_ia32_maxpd512: 4275 case X86::BI__builtin_ia32_maxps512: 4276 case X86::BI__builtin_ia32_minpd512: 4277 case X86::BI__builtin_ia32_minps512: 4278 case X86::BI__builtin_ia32_maxph512: 4279 case X86::BI__builtin_ia32_minph512: 4280 ArgNum = 2; 4281 break; 4282 case X86::BI__builtin_ia32_vcvtph2pd512_mask: 4283 case X86::BI__builtin_ia32_vcvtph2psx512_mask: 4284 case X86::BI__builtin_ia32_cvtps2pd512_mask: 4285 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 4286 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 4287 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 4288 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 4289 case X86::BI__builtin_ia32_cvttps2dq512_mask: 4290 case X86::BI__builtin_ia32_cvttps2qq512_mask: 4291 case X86::BI__builtin_ia32_cvttps2udq512_mask: 4292 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 4293 case X86::BI__builtin_ia32_vcvttph2w512_mask: 4294 case X86::BI__builtin_ia32_vcvttph2uw512_mask: 4295 case X86::BI__builtin_ia32_vcvttph2dq512_mask: 4296 case X86::BI__builtin_ia32_vcvttph2udq512_mask: 4297 case X86::BI__builtin_ia32_vcvttph2qq512_mask: 4298 case X86::BI__builtin_ia32_vcvttph2uqq512_mask: 4299 case X86::BI__builtin_ia32_exp2pd_mask: 4300 case X86::BI__builtin_ia32_exp2ps_mask: 4301 case X86::BI__builtin_ia32_getexppd512_mask: 4302 case X86::BI__builtin_ia32_getexpps512_mask: 4303 case X86::BI__builtin_ia32_getexpph512_mask: 4304 case X86::BI__builtin_ia32_rcp28pd_mask: 4305 case X86::BI__builtin_ia32_rcp28ps_mask: 4306 case X86::BI__builtin_ia32_rsqrt28pd_mask: 4307 case X86::BI__builtin_ia32_rsqrt28ps_mask: 4308 case X86::BI__builtin_ia32_vcomisd: 4309 case X86::BI__builtin_ia32_vcomiss: 4310 case X86::BI__builtin_ia32_vcomish: 4311 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 4312 ArgNum = 3; 4313 break; 4314 case X86::BI__builtin_ia32_cmppd512_mask: 4315 case X86::BI__builtin_ia32_cmpps512_mask: 4316 case X86::BI__builtin_ia32_cmpsd_mask: 4317 case X86::BI__builtin_ia32_cmpss_mask: 4318 case X86::BI__builtin_ia32_cmpsh_mask: 4319 case X86::BI__builtin_ia32_vcvtsh2sd_round_mask: 4320 case X86::BI__builtin_ia32_vcvtsh2ss_round_mask: 4321 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 4322 case X86::BI__builtin_ia32_getexpsd128_round_mask: 4323 case X86::BI__builtin_ia32_getexpss128_round_mask: 4324 case X86::BI__builtin_ia32_getexpsh128_round_mask: 4325 case X86::BI__builtin_ia32_getmantpd512_mask: 4326 case X86::BI__builtin_ia32_getmantps512_mask: 4327 case X86::BI__builtin_ia32_getmantph512_mask: 4328 case X86::BI__builtin_ia32_maxsd_round_mask: 4329 case X86::BI__builtin_ia32_maxss_round_mask: 4330 case X86::BI__builtin_ia32_maxsh_round_mask: 4331 case X86::BI__builtin_ia32_minsd_round_mask: 4332 case X86::BI__builtin_ia32_minss_round_mask: 4333 case X86::BI__builtin_ia32_minsh_round_mask: 4334 case X86::BI__builtin_ia32_rcp28sd_round_mask: 4335 case X86::BI__builtin_ia32_rcp28ss_round_mask: 4336 case X86::BI__builtin_ia32_reducepd512_mask: 4337 case X86::BI__builtin_ia32_reduceps512_mask: 4338 case X86::BI__builtin_ia32_reduceph512_mask: 4339 case X86::BI__builtin_ia32_rndscalepd_mask: 4340 case X86::BI__builtin_ia32_rndscaleps_mask: 4341 case X86::BI__builtin_ia32_rndscaleph_mask: 4342 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 4343 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 4344 ArgNum = 4; 4345 break; 4346 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4347 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4348 case X86::BI__builtin_ia32_fixupimmps512_mask: 4349 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4350 case X86::BI__builtin_ia32_fixupimmsd_mask: 4351 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4352 case X86::BI__builtin_ia32_fixupimmss_mask: 4353 case X86::BI__builtin_ia32_fixupimmss_maskz: 4354 case X86::BI__builtin_ia32_getmantsd_round_mask: 4355 case X86::BI__builtin_ia32_getmantss_round_mask: 4356 case X86::BI__builtin_ia32_getmantsh_round_mask: 4357 case X86::BI__builtin_ia32_rangepd512_mask: 4358 case X86::BI__builtin_ia32_rangeps512_mask: 4359 case X86::BI__builtin_ia32_rangesd128_round_mask: 4360 case X86::BI__builtin_ia32_rangess128_round_mask: 4361 case X86::BI__builtin_ia32_reducesd_mask: 4362 case X86::BI__builtin_ia32_reducess_mask: 4363 case X86::BI__builtin_ia32_reducesh_mask: 4364 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4365 case X86::BI__builtin_ia32_rndscaless_round_mask: 4366 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4367 ArgNum = 5; 4368 break; 4369 case X86::BI__builtin_ia32_vcvtsd2si64: 4370 case X86::BI__builtin_ia32_vcvtsd2si32: 4371 case X86::BI__builtin_ia32_vcvtsd2usi32: 4372 case X86::BI__builtin_ia32_vcvtsd2usi64: 4373 case X86::BI__builtin_ia32_vcvtss2si32: 4374 case X86::BI__builtin_ia32_vcvtss2si64: 4375 case X86::BI__builtin_ia32_vcvtss2usi32: 4376 case X86::BI__builtin_ia32_vcvtss2usi64: 4377 case X86::BI__builtin_ia32_vcvtsh2si32: 4378 case X86::BI__builtin_ia32_vcvtsh2si64: 4379 case X86::BI__builtin_ia32_vcvtsh2usi32: 4380 case X86::BI__builtin_ia32_vcvtsh2usi64: 4381 case X86::BI__builtin_ia32_sqrtpd512: 4382 case X86::BI__builtin_ia32_sqrtps512: 4383 case X86::BI__builtin_ia32_sqrtph512: 4384 ArgNum = 1; 4385 HasRC = true; 4386 break; 4387 case X86::BI__builtin_ia32_addph512: 4388 case X86::BI__builtin_ia32_divph512: 4389 case X86::BI__builtin_ia32_mulph512: 4390 case X86::BI__builtin_ia32_subph512: 4391 case X86::BI__builtin_ia32_addpd512: 4392 case X86::BI__builtin_ia32_addps512: 4393 case X86::BI__builtin_ia32_divpd512: 4394 case X86::BI__builtin_ia32_divps512: 4395 case X86::BI__builtin_ia32_mulpd512: 4396 case X86::BI__builtin_ia32_mulps512: 4397 case X86::BI__builtin_ia32_subpd512: 4398 case X86::BI__builtin_ia32_subps512: 4399 case X86::BI__builtin_ia32_cvtsi2sd64: 4400 case X86::BI__builtin_ia32_cvtsi2ss32: 4401 case X86::BI__builtin_ia32_cvtsi2ss64: 4402 case X86::BI__builtin_ia32_cvtusi2sd64: 4403 case X86::BI__builtin_ia32_cvtusi2ss32: 4404 case X86::BI__builtin_ia32_cvtusi2ss64: 4405 case X86::BI__builtin_ia32_vcvtusi2sh: 4406 case X86::BI__builtin_ia32_vcvtusi642sh: 4407 case X86::BI__builtin_ia32_vcvtsi2sh: 4408 case X86::BI__builtin_ia32_vcvtsi642sh: 4409 ArgNum = 2; 4410 HasRC = true; 4411 break; 4412 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 4413 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 4414 case X86::BI__builtin_ia32_vcvtpd2ph512_mask: 4415 case X86::BI__builtin_ia32_vcvtps2phx512_mask: 4416 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 4417 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 4418 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 4419 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 4420 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 4421 case X86::BI__builtin_ia32_cvtps2dq512_mask: 4422 case X86::BI__builtin_ia32_cvtps2qq512_mask: 4423 case X86::BI__builtin_ia32_cvtps2udq512_mask: 4424 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 4425 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 4426 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 4427 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 4428 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 4429 case X86::BI__builtin_ia32_vcvtdq2ph512_mask: 4430 case X86::BI__builtin_ia32_vcvtudq2ph512_mask: 4431 case X86::BI__builtin_ia32_vcvtw2ph512_mask: 4432 case X86::BI__builtin_ia32_vcvtuw2ph512_mask: 4433 case X86::BI__builtin_ia32_vcvtph2w512_mask: 4434 case X86::BI__builtin_ia32_vcvtph2uw512_mask: 4435 case X86::BI__builtin_ia32_vcvtph2dq512_mask: 4436 case X86::BI__builtin_ia32_vcvtph2udq512_mask: 4437 case X86::BI__builtin_ia32_vcvtph2qq512_mask: 4438 case X86::BI__builtin_ia32_vcvtph2uqq512_mask: 4439 case X86::BI__builtin_ia32_vcvtqq2ph512_mask: 4440 case X86::BI__builtin_ia32_vcvtuqq2ph512_mask: 4441 ArgNum = 3; 4442 HasRC = true; 4443 break; 4444 case X86::BI__builtin_ia32_addsh_round_mask: 4445 case X86::BI__builtin_ia32_addss_round_mask: 4446 case X86::BI__builtin_ia32_addsd_round_mask: 4447 case X86::BI__builtin_ia32_divsh_round_mask: 4448 case X86::BI__builtin_ia32_divss_round_mask: 4449 case X86::BI__builtin_ia32_divsd_round_mask: 4450 case X86::BI__builtin_ia32_mulsh_round_mask: 4451 case X86::BI__builtin_ia32_mulss_round_mask: 4452 case X86::BI__builtin_ia32_mulsd_round_mask: 4453 case X86::BI__builtin_ia32_subsh_round_mask: 4454 case X86::BI__builtin_ia32_subss_round_mask: 4455 case X86::BI__builtin_ia32_subsd_round_mask: 4456 case X86::BI__builtin_ia32_scalefph512_mask: 4457 case X86::BI__builtin_ia32_scalefpd512_mask: 4458 case X86::BI__builtin_ia32_scalefps512_mask: 4459 case X86::BI__builtin_ia32_scalefsd_round_mask: 4460 case X86::BI__builtin_ia32_scalefss_round_mask: 4461 case X86::BI__builtin_ia32_scalefsh_round_mask: 4462 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 4463 case X86::BI__builtin_ia32_vcvtss2sh_round_mask: 4464 case X86::BI__builtin_ia32_vcvtsd2sh_round_mask: 4465 case X86::BI__builtin_ia32_sqrtsd_round_mask: 4466 case X86::BI__builtin_ia32_sqrtss_round_mask: 4467 case X86::BI__builtin_ia32_sqrtsh_round_mask: 4468 case X86::BI__builtin_ia32_vfmaddsd3_mask: 4469 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 4470 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 4471 case X86::BI__builtin_ia32_vfmaddss3_mask: 4472 case X86::BI__builtin_ia32_vfmaddss3_maskz: 4473 case X86::BI__builtin_ia32_vfmaddss3_mask3: 4474 case X86::BI__builtin_ia32_vfmaddsh3_mask: 4475 case X86::BI__builtin_ia32_vfmaddsh3_maskz: 4476 case X86::BI__builtin_ia32_vfmaddsh3_mask3: 4477 case X86::BI__builtin_ia32_vfmaddpd512_mask: 4478 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 4479 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 4480 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 4481 case X86::BI__builtin_ia32_vfmaddps512_mask: 4482 case X86::BI__builtin_ia32_vfmaddps512_maskz: 4483 case X86::BI__builtin_ia32_vfmaddps512_mask3: 4484 case X86::BI__builtin_ia32_vfmsubps512_mask3: 4485 case X86::BI__builtin_ia32_vfmaddph512_mask: 4486 case X86::BI__builtin_ia32_vfmaddph512_maskz: 4487 case X86::BI__builtin_ia32_vfmaddph512_mask3: 4488 case X86::BI__builtin_ia32_vfmsubph512_mask3: 4489 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 4490 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 4491 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 4492 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 4493 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 4494 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 4495 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 4496 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 4497 case X86::BI__builtin_ia32_vfmaddsubph512_mask: 4498 case X86::BI__builtin_ia32_vfmaddsubph512_maskz: 4499 case X86::BI__builtin_ia32_vfmaddsubph512_mask3: 4500 case X86::BI__builtin_ia32_vfmsubaddph512_mask3: 4501 case X86::BI__builtin_ia32_vfmaddcsh_mask: 4502 case X86::BI__builtin_ia32_vfmaddcsh_round_mask: 4503 case X86::BI__builtin_ia32_vfmaddcsh_round_mask3: 4504 case X86::BI__builtin_ia32_vfmaddcph512_mask: 4505 case X86::BI__builtin_ia32_vfmaddcph512_maskz: 4506 case X86::BI__builtin_ia32_vfmaddcph512_mask3: 4507 case X86::BI__builtin_ia32_vfcmaddcsh_mask: 4508 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask: 4509 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3: 4510 case X86::BI__builtin_ia32_vfcmaddcph512_mask: 4511 case X86::BI__builtin_ia32_vfcmaddcph512_maskz: 4512 case X86::BI__builtin_ia32_vfcmaddcph512_mask3: 4513 case X86::BI__builtin_ia32_vfmulcsh_mask: 4514 case X86::BI__builtin_ia32_vfmulcph512_mask: 4515 case X86::BI__builtin_ia32_vfcmulcsh_mask: 4516 case X86::BI__builtin_ia32_vfcmulcph512_mask: 4517 ArgNum = 4; 4518 HasRC = true; 4519 break; 4520 } 4521 4522 llvm::APSInt Result; 4523 4524 // We can't check the value of a dependent argument. 4525 Expr *Arg = TheCall->getArg(ArgNum); 4526 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4527 return false; 4528 4529 // Check constant-ness first. 4530 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4531 return true; 4532 4533 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 4534 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 4535 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 4536 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 4537 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 4538 Result == 8/*ROUND_NO_EXC*/ || 4539 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 4540 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 4541 return false; 4542 4543 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 4544 << Arg->getSourceRange(); 4545 } 4546 4547 // Check if the gather/scatter scale is legal. 4548 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 4549 CallExpr *TheCall) { 4550 unsigned ArgNum = 0; 4551 switch (BuiltinID) { 4552 default: 4553 return false; 4554 case X86::BI__builtin_ia32_gatherpfdpd: 4555 case X86::BI__builtin_ia32_gatherpfdps: 4556 case X86::BI__builtin_ia32_gatherpfqpd: 4557 case X86::BI__builtin_ia32_gatherpfqps: 4558 case X86::BI__builtin_ia32_scatterpfdpd: 4559 case X86::BI__builtin_ia32_scatterpfdps: 4560 case X86::BI__builtin_ia32_scatterpfqpd: 4561 case X86::BI__builtin_ia32_scatterpfqps: 4562 ArgNum = 3; 4563 break; 4564 case X86::BI__builtin_ia32_gatherd_pd: 4565 case X86::BI__builtin_ia32_gatherd_pd256: 4566 case X86::BI__builtin_ia32_gatherq_pd: 4567 case X86::BI__builtin_ia32_gatherq_pd256: 4568 case X86::BI__builtin_ia32_gatherd_ps: 4569 case X86::BI__builtin_ia32_gatherd_ps256: 4570 case X86::BI__builtin_ia32_gatherq_ps: 4571 case X86::BI__builtin_ia32_gatherq_ps256: 4572 case X86::BI__builtin_ia32_gatherd_q: 4573 case X86::BI__builtin_ia32_gatherd_q256: 4574 case X86::BI__builtin_ia32_gatherq_q: 4575 case X86::BI__builtin_ia32_gatherq_q256: 4576 case X86::BI__builtin_ia32_gatherd_d: 4577 case X86::BI__builtin_ia32_gatherd_d256: 4578 case X86::BI__builtin_ia32_gatherq_d: 4579 case X86::BI__builtin_ia32_gatherq_d256: 4580 case X86::BI__builtin_ia32_gather3div2df: 4581 case X86::BI__builtin_ia32_gather3div2di: 4582 case X86::BI__builtin_ia32_gather3div4df: 4583 case X86::BI__builtin_ia32_gather3div4di: 4584 case X86::BI__builtin_ia32_gather3div4sf: 4585 case X86::BI__builtin_ia32_gather3div4si: 4586 case X86::BI__builtin_ia32_gather3div8sf: 4587 case X86::BI__builtin_ia32_gather3div8si: 4588 case X86::BI__builtin_ia32_gather3siv2df: 4589 case X86::BI__builtin_ia32_gather3siv2di: 4590 case X86::BI__builtin_ia32_gather3siv4df: 4591 case X86::BI__builtin_ia32_gather3siv4di: 4592 case X86::BI__builtin_ia32_gather3siv4sf: 4593 case X86::BI__builtin_ia32_gather3siv4si: 4594 case X86::BI__builtin_ia32_gather3siv8sf: 4595 case X86::BI__builtin_ia32_gather3siv8si: 4596 case X86::BI__builtin_ia32_gathersiv8df: 4597 case X86::BI__builtin_ia32_gathersiv16sf: 4598 case X86::BI__builtin_ia32_gatherdiv8df: 4599 case X86::BI__builtin_ia32_gatherdiv16sf: 4600 case X86::BI__builtin_ia32_gathersiv8di: 4601 case X86::BI__builtin_ia32_gathersiv16si: 4602 case X86::BI__builtin_ia32_gatherdiv8di: 4603 case X86::BI__builtin_ia32_gatherdiv16si: 4604 case X86::BI__builtin_ia32_scatterdiv2df: 4605 case X86::BI__builtin_ia32_scatterdiv2di: 4606 case X86::BI__builtin_ia32_scatterdiv4df: 4607 case X86::BI__builtin_ia32_scatterdiv4di: 4608 case X86::BI__builtin_ia32_scatterdiv4sf: 4609 case X86::BI__builtin_ia32_scatterdiv4si: 4610 case X86::BI__builtin_ia32_scatterdiv8sf: 4611 case X86::BI__builtin_ia32_scatterdiv8si: 4612 case X86::BI__builtin_ia32_scattersiv2df: 4613 case X86::BI__builtin_ia32_scattersiv2di: 4614 case X86::BI__builtin_ia32_scattersiv4df: 4615 case X86::BI__builtin_ia32_scattersiv4di: 4616 case X86::BI__builtin_ia32_scattersiv4sf: 4617 case X86::BI__builtin_ia32_scattersiv4si: 4618 case X86::BI__builtin_ia32_scattersiv8sf: 4619 case X86::BI__builtin_ia32_scattersiv8si: 4620 case X86::BI__builtin_ia32_scattersiv8df: 4621 case X86::BI__builtin_ia32_scattersiv16sf: 4622 case X86::BI__builtin_ia32_scatterdiv8df: 4623 case X86::BI__builtin_ia32_scatterdiv16sf: 4624 case X86::BI__builtin_ia32_scattersiv8di: 4625 case X86::BI__builtin_ia32_scattersiv16si: 4626 case X86::BI__builtin_ia32_scatterdiv8di: 4627 case X86::BI__builtin_ia32_scatterdiv16si: 4628 ArgNum = 4; 4629 break; 4630 } 4631 4632 llvm::APSInt Result; 4633 4634 // We can't check the value of a dependent argument. 4635 Expr *Arg = TheCall->getArg(ArgNum); 4636 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4637 return false; 4638 4639 // Check constant-ness first. 4640 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4641 return true; 4642 4643 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4644 return false; 4645 4646 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4647 << Arg->getSourceRange(); 4648 } 4649 4650 enum { TileRegLow = 0, TileRegHigh = 7 }; 4651 4652 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4653 ArrayRef<int> ArgNums) { 4654 for (int ArgNum : ArgNums) { 4655 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4656 return true; 4657 } 4658 return false; 4659 } 4660 4661 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4662 ArrayRef<int> ArgNums) { 4663 // Because the max number of tile register is TileRegHigh + 1, so here we use 4664 // each bit to represent the usage of them in bitset. 4665 std::bitset<TileRegHigh + 1> ArgValues; 4666 for (int ArgNum : ArgNums) { 4667 Expr *Arg = TheCall->getArg(ArgNum); 4668 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4669 continue; 4670 4671 llvm::APSInt Result; 4672 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4673 return true; 4674 int ArgExtValue = Result.getExtValue(); 4675 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4676 "Incorrect tile register num."); 4677 if (ArgValues.test(ArgExtValue)) 4678 return Diag(TheCall->getBeginLoc(), 4679 diag::err_x86_builtin_tile_arg_duplicate) 4680 << TheCall->getArg(ArgNum)->getSourceRange(); 4681 ArgValues.set(ArgExtValue); 4682 } 4683 return false; 4684 } 4685 4686 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 4687 ArrayRef<int> ArgNums) { 4688 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 4689 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 4690 } 4691 4692 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 4693 switch (BuiltinID) { 4694 default: 4695 return false; 4696 case X86::BI__builtin_ia32_tileloadd64: 4697 case X86::BI__builtin_ia32_tileloaddt164: 4698 case X86::BI__builtin_ia32_tilestored64: 4699 case X86::BI__builtin_ia32_tilezero: 4700 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 4701 case X86::BI__builtin_ia32_tdpbssd: 4702 case X86::BI__builtin_ia32_tdpbsud: 4703 case X86::BI__builtin_ia32_tdpbusd: 4704 case X86::BI__builtin_ia32_tdpbuud: 4705 case X86::BI__builtin_ia32_tdpbf16ps: 4706 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 4707 } 4708 } 4709 static bool isX86_32Builtin(unsigned BuiltinID) { 4710 // These builtins only work on x86-32 targets. 4711 switch (BuiltinID) { 4712 case X86::BI__builtin_ia32_readeflags_u32: 4713 case X86::BI__builtin_ia32_writeeflags_u32: 4714 return true; 4715 } 4716 4717 return false; 4718 } 4719 4720 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 4721 CallExpr *TheCall) { 4722 if (BuiltinID == X86::BI__builtin_cpu_supports) 4723 return SemaBuiltinCpuSupports(*this, TI, TheCall); 4724 4725 if (BuiltinID == X86::BI__builtin_cpu_is) 4726 return SemaBuiltinCpuIs(*this, TI, TheCall); 4727 4728 // Check for 32-bit only builtins on a 64-bit target. 4729 const llvm::Triple &TT = TI.getTriple(); 4730 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 4731 return Diag(TheCall->getCallee()->getBeginLoc(), 4732 diag::err_32_bit_builtin_64_bit_tgt); 4733 4734 // If the intrinsic has rounding or SAE make sure its valid. 4735 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 4736 return true; 4737 4738 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 4739 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 4740 return true; 4741 4742 // If the intrinsic has a tile arguments, make sure they are valid. 4743 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4744 return true; 4745 4746 // For intrinsics which take an immediate value as part of the instruction, 4747 // range check them here. 4748 int i = 0, l = 0, u = 0; 4749 switch (BuiltinID) { 4750 default: 4751 return false; 4752 case X86::BI__builtin_ia32_vec_ext_v2si: 4753 case X86::BI__builtin_ia32_vec_ext_v2di: 4754 case X86::BI__builtin_ia32_vextractf128_pd256: 4755 case X86::BI__builtin_ia32_vextractf128_ps256: 4756 case X86::BI__builtin_ia32_vextractf128_si256: 4757 case X86::BI__builtin_ia32_extract128i256: 4758 case X86::BI__builtin_ia32_extractf64x4_mask: 4759 case X86::BI__builtin_ia32_extracti64x4_mask: 4760 case X86::BI__builtin_ia32_extractf32x8_mask: 4761 case X86::BI__builtin_ia32_extracti32x8_mask: 4762 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4763 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4764 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4765 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4766 i = 1; l = 0; u = 1; 4767 break; 4768 case X86::BI__builtin_ia32_vec_set_v2di: 4769 case X86::BI__builtin_ia32_vinsertf128_pd256: 4770 case X86::BI__builtin_ia32_vinsertf128_ps256: 4771 case X86::BI__builtin_ia32_vinsertf128_si256: 4772 case X86::BI__builtin_ia32_insert128i256: 4773 case X86::BI__builtin_ia32_insertf32x8: 4774 case X86::BI__builtin_ia32_inserti32x8: 4775 case X86::BI__builtin_ia32_insertf64x4: 4776 case X86::BI__builtin_ia32_inserti64x4: 4777 case X86::BI__builtin_ia32_insertf64x2_256: 4778 case X86::BI__builtin_ia32_inserti64x2_256: 4779 case X86::BI__builtin_ia32_insertf32x4_256: 4780 case X86::BI__builtin_ia32_inserti32x4_256: 4781 i = 2; l = 0; u = 1; 4782 break; 4783 case X86::BI__builtin_ia32_vpermilpd: 4784 case X86::BI__builtin_ia32_vec_ext_v4hi: 4785 case X86::BI__builtin_ia32_vec_ext_v4si: 4786 case X86::BI__builtin_ia32_vec_ext_v4sf: 4787 case X86::BI__builtin_ia32_vec_ext_v4di: 4788 case X86::BI__builtin_ia32_extractf32x4_mask: 4789 case X86::BI__builtin_ia32_extracti32x4_mask: 4790 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4791 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4792 i = 1; l = 0; u = 3; 4793 break; 4794 case X86::BI_mm_prefetch: 4795 case X86::BI__builtin_ia32_vec_ext_v8hi: 4796 case X86::BI__builtin_ia32_vec_ext_v8si: 4797 i = 1; l = 0; u = 7; 4798 break; 4799 case X86::BI__builtin_ia32_sha1rnds4: 4800 case X86::BI__builtin_ia32_blendpd: 4801 case X86::BI__builtin_ia32_shufpd: 4802 case X86::BI__builtin_ia32_vec_set_v4hi: 4803 case X86::BI__builtin_ia32_vec_set_v4si: 4804 case X86::BI__builtin_ia32_vec_set_v4di: 4805 case X86::BI__builtin_ia32_shuf_f32x4_256: 4806 case X86::BI__builtin_ia32_shuf_f64x2_256: 4807 case X86::BI__builtin_ia32_shuf_i32x4_256: 4808 case X86::BI__builtin_ia32_shuf_i64x2_256: 4809 case X86::BI__builtin_ia32_insertf64x2_512: 4810 case X86::BI__builtin_ia32_inserti64x2_512: 4811 case X86::BI__builtin_ia32_insertf32x4: 4812 case X86::BI__builtin_ia32_inserti32x4: 4813 i = 2; l = 0; u = 3; 4814 break; 4815 case X86::BI__builtin_ia32_vpermil2pd: 4816 case X86::BI__builtin_ia32_vpermil2pd256: 4817 case X86::BI__builtin_ia32_vpermil2ps: 4818 case X86::BI__builtin_ia32_vpermil2ps256: 4819 i = 3; l = 0; u = 3; 4820 break; 4821 case X86::BI__builtin_ia32_cmpb128_mask: 4822 case X86::BI__builtin_ia32_cmpw128_mask: 4823 case X86::BI__builtin_ia32_cmpd128_mask: 4824 case X86::BI__builtin_ia32_cmpq128_mask: 4825 case X86::BI__builtin_ia32_cmpb256_mask: 4826 case X86::BI__builtin_ia32_cmpw256_mask: 4827 case X86::BI__builtin_ia32_cmpd256_mask: 4828 case X86::BI__builtin_ia32_cmpq256_mask: 4829 case X86::BI__builtin_ia32_cmpb512_mask: 4830 case X86::BI__builtin_ia32_cmpw512_mask: 4831 case X86::BI__builtin_ia32_cmpd512_mask: 4832 case X86::BI__builtin_ia32_cmpq512_mask: 4833 case X86::BI__builtin_ia32_ucmpb128_mask: 4834 case X86::BI__builtin_ia32_ucmpw128_mask: 4835 case X86::BI__builtin_ia32_ucmpd128_mask: 4836 case X86::BI__builtin_ia32_ucmpq128_mask: 4837 case X86::BI__builtin_ia32_ucmpb256_mask: 4838 case X86::BI__builtin_ia32_ucmpw256_mask: 4839 case X86::BI__builtin_ia32_ucmpd256_mask: 4840 case X86::BI__builtin_ia32_ucmpq256_mask: 4841 case X86::BI__builtin_ia32_ucmpb512_mask: 4842 case X86::BI__builtin_ia32_ucmpw512_mask: 4843 case X86::BI__builtin_ia32_ucmpd512_mask: 4844 case X86::BI__builtin_ia32_ucmpq512_mask: 4845 case X86::BI__builtin_ia32_vpcomub: 4846 case X86::BI__builtin_ia32_vpcomuw: 4847 case X86::BI__builtin_ia32_vpcomud: 4848 case X86::BI__builtin_ia32_vpcomuq: 4849 case X86::BI__builtin_ia32_vpcomb: 4850 case X86::BI__builtin_ia32_vpcomw: 4851 case X86::BI__builtin_ia32_vpcomd: 4852 case X86::BI__builtin_ia32_vpcomq: 4853 case X86::BI__builtin_ia32_vec_set_v8hi: 4854 case X86::BI__builtin_ia32_vec_set_v8si: 4855 i = 2; l = 0; u = 7; 4856 break; 4857 case X86::BI__builtin_ia32_vpermilpd256: 4858 case X86::BI__builtin_ia32_roundps: 4859 case X86::BI__builtin_ia32_roundpd: 4860 case X86::BI__builtin_ia32_roundps256: 4861 case X86::BI__builtin_ia32_roundpd256: 4862 case X86::BI__builtin_ia32_getmantpd128_mask: 4863 case X86::BI__builtin_ia32_getmantpd256_mask: 4864 case X86::BI__builtin_ia32_getmantps128_mask: 4865 case X86::BI__builtin_ia32_getmantps256_mask: 4866 case X86::BI__builtin_ia32_getmantpd512_mask: 4867 case X86::BI__builtin_ia32_getmantps512_mask: 4868 case X86::BI__builtin_ia32_getmantph128_mask: 4869 case X86::BI__builtin_ia32_getmantph256_mask: 4870 case X86::BI__builtin_ia32_getmantph512_mask: 4871 case X86::BI__builtin_ia32_vec_ext_v16qi: 4872 case X86::BI__builtin_ia32_vec_ext_v16hi: 4873 i = 1; l = 0; u = 15; 4874 break; 4875 case X86::BI__builtin_ia32_pblendd128: 4876 case X86::BI__builtin_ia32_blendps: 4877 case X86::BI__builtin_ia32_blendpd256: 4878 case X86::BI__builtin_ia32_shufpd256: 4879 case X86::BI__builtin_ia32_roundss: 4880 case X86::BI__builtin_ia32_roundsd: 4881 case X86::BI__builtin_ia32_rangepd128_mask: 4882 case X86::BI__builtin_ia32_rangepd256_mask: 4883 case X86::BI__builtin_ia32_rangepd512_mask: 4884 case X86::BI__builtin_ia32_rangeps128_mask: 4885 case X86::BI__builtin_ia32_rangeps256_mask: 4886 case X86::BI__builtin_ia32_rangeps512_mask: 4887 case X86::BI__builtin_ia32_getmantsd_round_mask: 4888 case X86::BI__builtin_ia32_getmantss_round_mask: 4889 case X86::BI__builtin_ia32_getmantsh_round_mask: 4890 case X86::BI__builtin_ia32_vec_set_v16qi: 4891 case X86::BI__builtin_ia32_vec_set_v16hi: 4892 i = 2; l = 0; u = 15; 4893 break; 4894 case X86::BI__builtin_ia32_vec_ext_v32qi: 4895 i = 1; l = 0; u = 31; 4896 break; 4897 case X86::BI__builtin_ia32_cmpps: 4898 case X86::BI__builtin_ia32_cmpss: 4899 case X86::BI__builtin_ia32_cmppd: 4900 case X86::BI__builtin_ia32_cmpsd: 4901 case X86::BI__builtin_ia32_cmpps256: 4902 case X86::BI__builtin_ia32_cmppd256: 4903 case X86::BI__builtin_ia32_cmpps128_mask: 4904 case X86::BI__builtin_ia32_cmppd128_mask: 4905 case X86::BI__builtin_ia32_cmpps256_mask: 4906 case X86::BI__builtin_ia32_cmppd256_mask: 4907 case X86::BI__builtin_ia32_cmpps512_mask: 4908 case X86::BI__builtin_ia32_cmppd512_mask: 4909 case X86::BI__builtin_ia32_cmpsd_mask: 4910 case X86::BI__builtin_ia32_cmpss_mask: 4911 case X86::BI__builtin_ia32_vec_set_v32qi: 4912 i = 2; l = 0; u = 31; 4913 break; 4914 case X86::BI__builtin_ia32_permdf256: 4915 case X86::BI__builtin_ia32_permdi256: 4916 case X86::BI__builtin_ia32_permdf512: 4917 case X86::BI__builtin_ia32_permdi512: 4918 case X86::BI__builtin_ia32_vpermilps: 4919 case X86::BI__builtin_ia32_vpermilps256: 4920 case X86::BI__builtin_ia32_vpermilpd512: 4921 case X86::BI__builtin_ia32_vpermilps512: 4922 case X86::BI__builtin_ia32_pshufd: 4923 case X86::BI__builtin_ia32_pshufd256: 4924 case X86::BI__builtin_ia32_pshufd512: 4925 case X86::BI__builtin_ia32_pshufhw: 4926 case X86::BI__builtin_ia32_pshufhw256: 4927 case X86::BI__builtin_ia32_pshufhw512: 4928 case X86::BI__builtin_ia32_pshuflw: 4929 case X86::BI__builtin_ia32_pshuflw256: 4930 case X86::BI__builtin_ia32_pshuflw512: 4931 case X86::BI__builtin_ia32_vcvtps2ph: 4932 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4933 case X86::BI__builtin_ia32_vcvtps2ph256: 4934 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4935 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4936 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4937 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4938 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4939 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4940 case X86::BI__builtin_ia32_rndscaleps_mask: 4941 case X86::BI__builtin_ia32_rndscalepd_mask: 4942 case X86::BI__builtin_ia32_rndscaleph_mask: 4943 case X86::BI__builtin_ia32_reducepd128_mask: 4944 case X86::BI__builtin_ia32_reducepd256_mask: 4945 case X86::BI__builtin_ia32_reducepd512_mask: 4946 case X86::BI__builtin_ia32_reduceps128_mask: 4947 case X86::BI__builtin_ia32_reduceps256_mask: 4948 case X86::BI__builtin_ia32_reduceps512_mask: 4949 case X86::BI__builtin_ia32_reduceph128_mask: 4950 case X86::BI__builtin_ia32_reduceph256_mask: 4951 case X86::BI__builtin_ia32_reduceph512_mask: 4952 case X86::BI__builtin_ia32_prold512: 4953 case X86::BI__builtin_ia32_prolq512: 4954 case X86::BI__builtin_ia32_prold128: 4955 case X86::BI__builtin_ia32_prold256: 4956 case X86::BI__builtin_ia32_prolq128: 4957 case X86::BI__builtin_ia32_prolq256: 4958 case X86::BI__builtin_ia32_prord512: 4959 case X86::BI__builtin_ia32_prorq512: 4960 case X86::BI__builtin_ia32_prord128: 4961 case X86::BI__builtin_ia32_prord256: 4962 case X86::BI__builtin_ia32_prorq128: 4963 case X86::BI__builtin_ia32_prorq256: 4964 case X86::BI__builtin_ia32_fpclasspd128_mask: 4965 case X86::BI__builtin_ia32_fpclasspd256_mask: 4966 case X86::BI__builtin_ia32_fpclassps128_mask: 4967 case X86::BI__builtin_ia32_fpclassps256_mask: 4968 case X86::BI__builtin_ia32_fpclassps512_mask: 4969 case X86::BI__builtin_ia32_fpclasspd512_mask: 4970 case X86::BI__builtin_ia32_fpclassph128_mask: 4971 case X86::BI__builtin_ia32_fpclassph256_mask: 4972 case X86::BI__builtin_ia32_fpclassph512_mask: 4973 case X86::BI__builtin_ia32_fpclasssd_mask: 4974 case X86::BI__builtin_ia32_fpclassss_mask: 4975 case X86::BI__builtin_ia32_fpclasssh_mask: 4976 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4977 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4978 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4979 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4980 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4981 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4982 case X86::BI__builtin_ia32_kshiftliqi: 4983 case X86::BI__builtin_ia32_kshiftlihi: 4984 case X86::BI__builtin_ia32_kshiftlisi: 4985 case X86::BI__builtin_ia32_kshiftlidi: 4986 case X86::BI__builtin_ia32_kshiftriqi: 4987 case X86::BI__builtin_ia32_kshiftrihi: 4988 case X86::BI__builtin_ia32_kshiftrisi: 4989 case X86::BI__builtin_ia32_kshiftridi: 4990 i = 1; l = 0; u = 255; 4991 break; 4992 case X86::BI__builtin_ia32_vperm2f128_pd256: 4993 case X86::BI__builtin_ia32_vperm2f128_ps256: 4994 case X86::BI__builtin_ia32_vperm2f128_si256: 4995 case X86::BI__builtin_ia32_permti256: 4996 case X86::BI__builtin_ia32_pblendw128: 4997 case X86::BI__builtin_ia32_pblendw256: 4998 case X86::BI__builtin_ia32_blendps256: 4999 case X86::BI__builtin_ia32_pblendd256: 5000 case X86::BI__builtin_ia32_palignr128: 5001 case X86::BI__builtin_ia32_palignr256: 5002 case X86::BI__builtin_ia32_palignr512: 5003 case X86::BI__builtin_ia32_alignq512: 5004 case X86::BI__builtin_ia32_alignd512: 5005 case X86::BI__builtin_ia32_alignd128: 5006 case X86::BI__builtin_ia32_alignd256: 5007 case X86::BI__builtin_ia32_alignq128: 5008 case X86::BI__builtin_ia32_alignq256: 5009 case X86::BI__builtin_ia32_vcomisd: 5010 case X86::BI__builtin_ia32_vcomiss: 5011 case X86::BI__builtin_ia32_shuf_f32x4: 5012 case X86::BI__builtin_ia32_shuf_f64x2: 5013 case X86::BI__builtin_ia32_shuf_i32x4: 5014 case X86::BI__builtin_ia32_shuf_i64x2: 5015 case X86::BI__builtin_ia32_shufpd512: 5016 case X86::BI__builtin_ia32_shufps: 5017 case X86::BI__builtin_ia32_shufps256: 5018 case X86::BI__builtin_ia32_shufps512: 5019 case X86::BI__builtin_ia32_dbpsadbw128: 5020 case X86::BI__builtin_ia32_dbpsadbw256: 5021 case X86::BI__builtin_ia32_dbpsadbw512: 5022 case X86::BI__builtin_ia32_vpshldd128: 5023 case X86::BI__builtin_ia32_vpshldd256: 5024 case X86::BI__builtin_ia32_vpshldd512: 5025 case X86::BI__builtin_ia32_vpshldq128: 5026 case X86::BI__builtin_ia32_vpshldq256: 5027 case X86::BI__builtin_ia32_vpshldq512: 5028 case X86::BI__builtin_ia32_vpshldw128: 5029 case X86::BI__builtin_ia32_vpshldw256: 5030 case X86::BI__builtin_ia32_vpshldw512: 5031 case X86::BI__builtin_ia32_vpshrdd128: 5032 case X86::BI__builtin_ia32_vpshrdd256: 5033 case X86::BI__builtin_ia32_vpshrdd512: 5034 case X86::BI__builtin_ia32_vpshrdq128: 5035 case X86::BI__builtin_ia32_vpshrdq256: 5036 case X86::BI__builtin_ia32_vpshrdq512: 5037 case X86::BI__builtin_ia32_vpshrdw128: 5038 case X86::BI__builtin_ia32_vpshrdw256: 5039 case X86::BI__builtin_ia32_vpshrdw512: 5040 i = 2; l = 0; u = 255; 5041 break; 5042 case X86::BI__builtin_ia32_fixupimmpd512_mask: 5043 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 5044 case X86::BI__builtin_ia32_fixupimmps512_mask: 5045 case X86::BI__builtin_ia32_fixupimmps512_maskz: 5046 case X86::BI__builtin_ia32_fixupimmsd_mask: 5047 case X86::BI__builtin_ia32_fixupimmsd_maskz: 5048 case X86::BI__builtin_ia32_fixupimmss_mask: 5049 case X86::BI__builtin_ia32_fixupimmss_maskz: 5050 case X86::BI__builtin_ia32_fixupimmpd128_mask: 5051 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 5052 case X86::BI__builtin_ia32_fixupimmpd256_mask: 5053 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 5054 case X86::BI__builtin_ia32_fixupimmps128_mask: 5055 case X86::BI__builtin_ia32_fixupimmps128_maskz: 5056 case X86::BI__builtin_ia32_fixupimmps256_mask: 5057 case X86::BI__builtin_ia32_fixupimmps256_maskz: 5058 case X86::BI__builtin_ia32_pternlogd512_mask: 5059 case X86::BI__builtin_ia32_pternlogd512_maskz: 5060 case X86::BI__builtin_ia32_pternlogq512_mask: 5061 case X86::BI__builtin_ia32_pternlogq512_maskz: 5062 case X86::BI__builtin_ia32_pternlogd128_mask: 5063 case X86::BI__builtin_ia32_pternlogd128_maskz: 5064 case X86::BI__builtin_ia32_pternlogd256_mask: 5065 case X86::BI__builtin_ia32_pternlogd256_maskz: 5066 case X86::BI__builtin_ia32_pternlogq128_mask: 5067 case X86::BI__builtin_ia32_pternlogq128_maskz: 5068 case X86::BI__builtin_ia32_pternlogq256_mask: 5069 case X86::BI__builtin_ia32_pternlogq256_maskz: 5070 i = 3; l = 0; u = 255; 5071 break; 5072 case X86::BI__builtin_ia32_gatherpfdpd: 5073 case X86::BI__builtin_ia32_gatherpfdps: 5074 case X86::BI__builtin_ia32_gatherpfqpd: 5075 case X86::BI__builtin_ia32_gatherpfqps: 5076 case X86::BI__builtin_ia32_scatterpfdpd: 5077 case X86::BI__builtin_ia32_scatterpfdps: 5078 case X86::BI__builtin_ia32_scatterpfqpd: 5079 case X86::BI__builtin_ia32_scatterpfqps: 5080 i = 4; l = 2; u = 3; 5081 break; 5082 case X86::BI__builtin_ia32_reducesd_mask: 5083 case X86::BI__builtin_ia32_reducess_mask: 5084 case X86::BI__builtin_ia32_rndscalesd_round_mask: 5085 case X86::BI__builtin_ia32_rndscaless_round_mask: 5086 case X86::BI__builtin_ia32_rndscalesh_round_mask: 5087 case X86::BI__builtin_ia32_reducesh_mask: 5088 i = 4; l = 0; u = 255; 5089 break; 5090 } 5091 5092 // Note that we don't force a hard error on the range check here, allowing 5093 // template-generated or macro-generated dead code to potentially have out-of- 5094 // range values. These need to code generate, but don't need to necessarily 5095 // make any sense. We use a warning that defaults to an error. 5096 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 5097 } 5098 5099 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 5100 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 5101 /// Returns true when the format fits the function and the FormatStringInfo has 5102 /// been populated. 5103 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 5104 FormatStringInfo *FSI) { 5105 FSI->HasVAListArg = Format->getFirstArg() == 0; 5106 FSI->FormatIdx = Format->getFormatIdx() - 1; 5107 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 5108 5109 // The way the format attribute works in GCC, the implicit this argument 5110 // of member functions is counted. However, it doesn't appear in our own 5111 // lists, so decrement format_idx in that case. 5112 if (IsCXXMember) { 5113 if(FSI->FormatIdx == 0) 5114 return false; 5115 --FSI->FormatIdx; 5116 if (FSI->FirstDataArg != 0) 5117 --FSI->FirstDataArg; 5118 } 5119 return true; 5120 } 5121 5122 /// Checks if a the given expression evaluates to null. 5123 /// 5124 /// Returns true if the value evaluates to null. 5125 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 5126 // If the expression has non-null type, it doesn't evaluate to null. 5127 if (auto nullability 5128 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 5129 if (*nullability == NullabilityKind::NonNull) 5130 return false; 5131 } 5132 5133 // As a special case, transparent unions initialized with zero are 5134 // considered null for the purposes of the nonnull attribute. 5135 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 5136 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 5137 if (const CompoundLiteralExpr *CLE = 5138 dyn_cast<CompoundLiteralExpr>(Expr)) 5139 if (const InitListExpr *ILE = 5140 dyn_cast<InitListExpr>(CLE->getInitializer())) 5141 Expr = ILE->getInit(0); 5142 } 5143 5144 bool Result; 5145 return (!Expr->isValueDependent() && 5146 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 5147 !Result); 5148 } 5149 5150 static void CheckNonNullArgument(Sema &S, 5151 const Expr *ArgExpr, 5152 SourceLocation CallSiteLoc) { 5153 if (CheckNonNullExpr(S, ArgExpr)) 5154 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 5155 S.PDiag(diag::warn_null_arg) 5156 << ArgExpr->getSourceRange()); 5157 } 5158 5159 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 5160 FormatStringInfo FSI; 5161 if ((GetFormatStringType(Format) == FST_NSString) && 5162 getFormatStringInfo(Format, false, &FSI)) { 5163 Idx = FSI.FormatIdx; 5164 return true; 5165 } 5166 return false; 5167 } 5168 5169 /// Diagnose use of %s directive in an NSString which is being passed 5170 /// as formatting string to formatting method. 5171 static void 5172 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 5173 const NamedDecl *FDecl, 5174 Expr **Args, 5175 unsigned NumArgs) { 5176 unsigned Idx = 0; 5177 bool Format = false; 5178 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 5179 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 5180 Idx = 2; 5181 Format = true; 5182 } 5183 else 5184 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 5185 if (S.GetFormatNSStringIdx(I, Idx)) { 5186 Format = true; 5187 break; 5188 } 5189 } 5190 if (!Format || NumArgs <= Idx) 5191 return; 5192 const Expr *FormatExpr = Args[Idx]; 5193 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 5194 FormatExpr = CSCE->getSubExpr(); 5195 const StringLiteral *FormatString; 5196 if (const ObjCStringLiteral *OSL = 5197 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 5198 FormatString = OSL->getString(); 5199 else 5200 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 5201 if (!FormatString) 5202 return; 5203 if (S.FormatStringHasSArg(FormatString)) { 5204 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 5205 << "%s" << 1 << 1; 5206 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 5207 << FDecl->getDeclName(); 5208 } 5209 } 5210 5211 /// Determine whether the given type has a non-null nullability annotation. 5212 static bool isNonNullType(ASTContext &ctx, QualType type) { 5213 if (auto nullability = type->getNullability(ctx)) 5214 return *nullability == NullabilityKind::NonNull; 5215 5216 return false; 5217 } 5218 5219 static void CheckNonNullArguments(Sema &S, 5220 const NamedDecl *FDecl, 5221 const FunctionProtoType *Proto, 5222 ArrayRef<const Expr *> Args, 5223 SourceLocation CallSiteLoc) { 5224 assert((FDecl || Proto) && "Need a function declaration or prototype"); 5225 5226 // Already checked by by constant evaluator. 5227 if (S.isConstantEvaluated()) 5228 return; 5229 // Check the attributes attached to the method/function itself. 5230 llvm::SmallBitVector NonNullArgs; 5231 if (FDecl) { 5232 // Handle the nonnull attribute on the function/method declaration itself. 5233 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 5234 if (!NonNull->args_size()) { 5235 // Easy case: all pointer arguments are nonnull. 5236 for (const auto *Arg : Args) 5237 if (S.isValidPointerAttrType(Arg->getType())) 5238 CheckNonNullArgument(S, Arg, CallSiteLoc); 5239 return; 5240 } 5241 5242 for (const ParamIdx &Idx : NonNull->args()) { 5243 unsigned IdxAST = Idx.getASTIndex(); 5244 if (IdxAST >= Args.size()) 5245 continue; 5246 if (NonNullArgs.empty()) 5247 NonNullArgs.resize(Args.size()); 5248 NonNullArgs.set(IdxAST); 5249 } 5250 } 5251 } 5252 5253 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 5254 // Handle the nonnull attribute on the parameters of the 5255 // function/method. 5256 ArrayRef<ParmVarDecl*> parms; 5257 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 5258 parms = FD->parameters(); 5259 else 5260 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 5261 5262 unsigned ParamIndex = 0; 5263 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 5264 I != E; ++I, ++ParamIndex) { 5265 const ParmVarDecl *PVD = *I; 5266 if (PVD->hasAttr<NonNullAttr>() || 5267 isNonNullType(S.Context, PVD->getType())) { 5268 if (NonNullArgs.empty()) 5269 NonNullArgs.resize(Args.size()); 5270 5271 NonNullArgs.set(ParamIndex); 5272 } 5273 } 5274 } else { 5275 // If we have a non-function, non-method declaration but no 5276 // function prototype, try to dig out the function prototype. 5277 if (!Proto) { 5278 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 5279 QualType type = VD->getType().getNonReferenceType(); 5280 if (auto pointerType = type->getAs<PointerType>()) 5281 type = pointerType->getPointeeType(); 5282 else if (auto blockType = type->getAs<BlockPointerType>()) 5283 type = blockType->getPointeeType(); 5284 // FIXME: data member pointers? 5285 5286 // Dig out the function prototype, if there is one. 5287 Proto = type->getAs<FunctionProtoType>(); 5288 } 5289 } 5290 5291 // Fill in non-null argument information from the nullability 5292 // information on the parameter types (if we have them). 5293 if (Proto) { 5294 unsigned Index = 0; 5295 for (auto paramType : Proto->getParamTypes()) { 5296 if (isNonNullType(S.Context, paramType)) { 5297 if (NonNullArgs.empty()) 5298 NonNullArgs.resize(Args.size()); 5299 5300 NonNullArgs.set(Index); 5301 } 5302 5303 ++Index; 5304 } 5305 } 5306 } 5307 5308 // Check for non-null arguments. 5309 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 5310 ArgIndex != ArgIndexEnd; ++ArgIndex) { 5311 if (NonNullArgs[ArgIndex]) 5312 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 5313 } 5314 } 5315 5316 /// Warn if a pointer or reference argument passed to a function points to an 5317 /// object that is less aligned than the parameter. This can happen when 5318 /// creating a typedef with a lower alignment than the original type and then 5319 /// calling functions defined in terms of the original type. 5320 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 5321 StringRef ParamName, QualType ArgTy, 5322 QualType ParamTy) { 5323 5324 // If a function accepts a pointer or reference type 5325 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 5326 return; 5327 5328 // If the parameter is a pointer type, get the pointee type for the 5329 // argument too. If the parameter is a reference type, don't try to get 5330 // the pointee type for the argument. 5331 if (ParamTy->isPointerType()) 5332 ArgTy = ArgTy->getPointeeType(); 5333 5334 // Remove reference or pointer 5335 ParamTy = ParamTy->getPointeeType(); 5336 5337 // Find expected alignment, and the actual alignment of the passed object. 5338 // getTypeAlignInChars requires complete types 5339 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 5340 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 5341 ArgTy->isUndeducedType()) 5342 return; 5343 5344 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 5345 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 5346 5347 // If the argument is less aligned than the parameter, there is a 5348 // potential alignment issue. 5349 if (ArgAlign < ParamAlign) 5350 Diag(Loc, diag::warn_param_mismatched_alignment) 5351 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 5352 << ParamName << (FDecl != nullptr) << FDecl; 5353 } 5354 5355 /// Handles the checks for format strings, non-POD arguments to vararg 5356 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 5357 /// attributes. 5358 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 5359 const Expr *ThisArg, ArrayRef<const Expr *> Args, 5360 bool IsMemberFunction, SourceLocation Loc, 5361 SourceRange Range, VariadicCallType CallType) { 5362 // FIXME: We should check as much as we can in the template definition. 5363 if (CurContext->isDependentContext()) 5364 return; 5365 5366 // Printf and scanf checking. 5367 llvm::SmallBitVector CheckedVarArgs; 5368 if (FDecl) { 5369 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 5370 // Only create vector if there are format attributes. 5371 CheckedVarArgs.resize(Args.size()); 5372 5373 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 5374 CheckedVarArgs); 5375 } 5376 } 5377 5378 // Refuse POD arguments that weren't caught by the format string 5379 // checks above. 5380 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 5381 if (CallType != VariadicDoesNotApply && 5382 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 5383 unsigned NumParams = Proto ? Proto->getNumParams() 5384 : FDecl && isa<FunctionDecl>(FDecl) 5385 ? cast<FunctionDecl>(FDecl)->getNumParams() 5386 : FDecl && isa<ObjCMethodDecl>(FDecl) 5387 ? cast<ObjCMethodDecl>(FDecl)->param_size() 5388 : 0; 5389 5390 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 5391 // Args[ArgIdx] can be null in malformed code. 5392 if (const Expr *Arg = Args[ArgIdx]) { 5393 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 5394 checkVariadicArgument(Arg, CallType); 5395 } 5396 } 5397 } 5398 5399 if (FDecl || Proto) { 5400 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 5401 5402 // Type safety checking. 5403 if (FDecl) { 5404 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 5405 CheckArgumentWithTypeTag(I, Args, Loc); 5406 } 5407 } 5408 5409 // Check that passed arguments match the alignment of original arguments. 5410 // Try to get the missing prototype from the declaration. 5411 if (!Proto && FDecl) { 5412 const auto *FT = FDecl->getFunctionType(); 5413 if (isa_and_nonnull<FunctionProtoType>(FT)) 5414 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 5415 } 5416 if (Proto) { 5417 // For variadic functions, we may have more args than parameters. 5418 // For some K&R functions, we may have less args than parameters. 5419 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 5420 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 5421 // Args[ArgIdx] can be null in malformed code. 5422 if (const Expr *Arg = Args[ArgIdx]) { 5423 if (Arg->containsErrors()) 5424 continue; 5425 5426 QualType ParamTy = Proto->getParamType(ArgIdx); 5427 QualType ArgTy = Arg->getType(); 5428 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 5429 ArgTy, ParamTy); 5430 } 5431 } 5432 } 5433 5434 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 5435 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 5436 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 5437 if (!Arg->isValueDependent()) { 5438 Expr::EvalResult Align; 5439 if (Arg->EvaluateAsInt(Align, Context)) { 5440 const llvm::APSInt &I = Align.Val.getInt(); 5441 if (!I.isPowerOf2()) 5442 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 5443 << Arg->getSourceRange(); 5444 5445 if (I > Sema::MaximumAlignment) 5446 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 5447 << Arg->getSourceRange() << Sema::MaximumAlignment; 5448 } 5449 } 5450 } 5451 5452 if (FD) 5453 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 5454 } 5455 5456 /// CheckConstructorCall - Check a constructor call for correctness and safety 5457 /// properties not enforced by the C type system. 5458 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 5459 ArrayRef<const Expr *> Args, 5460 const FunctionProtoType *Proto, 5461 SourceLocation Loc) { 5462 VariadicCallType CallType = 5463 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 5464 5465 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 5466 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 5467 Context.getPointerType(Ctor->getThisObjectType())); 5468 5469 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 5470 Loc, SourceRange(), CallType); 5471 } 5472 5473 /// CheckFunctionCall - Check a direct function call for various correctness 5474 /// and safety properties not strictly enforced by the C type system. 5475 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 5476 const FunctionProtoType *Proto) { 5477 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 5478 isa<CXXMethodDecl>(FDecl); 5479 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 5480 IsMemberOperatorCall; 5481 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 5482 TheCall->getCallee()); 5483 Expr** Args = TheCall->getArgs(); 5484 unsigned NumArgs = TheCall->getNumArgs(); 5485 5486 Expr *ImplicitThis = nullptr; 5487 if (IsMemberOperatorCall) { 5488 // If this is a call to a member operator, hide the first argument 5489 // from checkCall. 5490 // FIXME: Our choice of AST representation here is less than ideal. 5491 ImplicitThis = Args[0]; 5492 ++Args; 5493 --NumArgs; 5494 } else if (IsMemberFunction) 5495 ImplicitThis = 5496 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 5497 5498 if (ImplicitThis) { 5499 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 5500 // used. 5501 QualType ThisType = ImplicitThis->getType(); 5502 if (!ThisType->isPointerType()) { 5503 assert(!ThisType->isReferenceType()); 5504 ThisType = Context.getPointerType(ThisType); 5505 } 5506 5507 QualType ThisTypeFromDecl = 5508 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 5509 5510 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 5511 ThisTypeFromDecl); 5512 } 5513 5514 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 5515 IsMemberFunction, TheCall->getRParenLoc(), 5516 TheCall->getCallee()->getSourceRange(), CallType); 5517 5518 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5519 // None of the checks below are needed for functions that don't have 5520 // simple names (e.g., C++ conversion functions). 5521 if (!FnInfo) 5522 return false; 5523 5524 // Enforce TCB except for builtin calls, which are always allowed. 5525 if (FDecl->getBuiltinID() == 0) 5526 CheckTCBEnforcement(TheCall->getExprLoc(), FDecl); 5527 5528 CheckAbsoluteValueFunction(TheCall, FDecl); 5529 CheckMaxUnsignedZero(TheCall, FDecl); 5530 5531 if (getLangOpts().ObjC) 5532 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 5533 5534 unsigned CMId = FDecl->getMemoryFunctionKind(); 5535 5536 // Handle memory setting and copying functions. 5537 switch (CMId) { 5538 case 0: 5539 return false; 5540 case Builtin::BIstrlcpy: // fallthrough 5541 case Builtin::BIstrlcat: 5542 CheckStrlcpycatArguments(TheCall, FnInfo); 5543 break; 5544 case Builtin::BIstrncat: 5545 CheckStrncatArguments(TheCall, FnInfo); 5546 break; 5547 case Builtin::BIfree: 5548 CheckFreeArguments(TheCall); 5549 break; 5550 default: 5551 CheckMemaccessArguments(TheCall, CMId, FnInfo); 5552 } 5553 5554 return false; 5555 } 5556 5557 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 5558 ArrayRef<const Expr *> Args) { 5559 VariadicCallType CallType = 5560 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 5561 5562 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 5563 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 5564 CallType); 5565 5566 CheckTCBEnforcement(lbrac, Method); 5567 5568 return false; 5569 } 5570 5571 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 5572 const FunctionProtoType *Proto) { 5573 QualType Ty; 5574 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 5575 Ty = V->getType().getNonReferenceType(); 5576 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 5577 Ty = F->getType().getNonReferenceType(); 5578 else 5579 return false; 5580 5581 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 5582 !Ty->isFunctionProtoType()) 5583 return false; 5584 5585 VariadicCallType CallType; 5586 if (!Proto || !Proto->isVariadic()) { 5587 CallType = VariadicDoesNotApply; 5588 } else if (Ty->isBlockPointerType()) { 5589 CallType = VariadicBlock; 5590 } else { // Ty->isFunctionPointerType() 5591 CallType = VariadicFunction; 5592 } 5593 5594 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 5595 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5596 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5597 TheCall->getCallee()->getSourceRange(), CallType); 5598 5599 return false; 5600 } 5601 5602 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 5603 /// such as function pointers returned from functions. 5604 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 5605 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 5606 TheCall->getCallee()); 5607 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 5608 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5609 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5610 TheCall->getCallee()->getSourceRange(), CallType); 5611 5612 return false; 5613 } 5614 5615 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 5616 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 5617 return false; 5618 5619 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 5620 switch (Op) { 5621 case AtomicExpr::AO__c11_atomic_init: 5622 case AtomicExpr::AO__opencl_atomic_init: 5623 llvm_unreachable("There is no ordering argument for an init"); 5624 5625 case AtomicExpr::AO__c11_atomic_load: 5626 case AtomicExpr::AO__opencl_atomic_load: 5627 case AtomicExpr::AO__hip_atomic_load: 5628 case AtomicExpr::AO__atomic_load_n: 5629 case AtomicExpr::AO__atomic_load: 5630 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5631 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5632 5633 case AtomicExpr::AO__c11_atomic_store: 5634 case AtomicExpr::AO__opencl_atomic_store: 5635 case AtomicExpr::AO__hip_atomic_store: 5636 case AtomicExpr::AO__atomic_store: 5637 case AtomicExpr::AO__atomic_store_n: 5638 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5639 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5640 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5641 5642 default: 5643 return true; 5644 } 5645 } 5646 5647 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5648 AtomicExpr::AtomicOp Op) { 5649 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5650 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5651 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5652 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5653 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5654 Op); 5655 } 5656 5657 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5658 SourceLocation RParenLoc, MultiExprArg Args, 5659 AtomicExpr::AtomicOp Op, 5660 AtomicArgumentOrder ArgOrder) { 5661 // All the non-OpenCL operations take one of the following forms. 5662 // The OpenCL operations take the __c11 forms with one extra argument for 5663 // synchronization scope. 5664 enum { 5665 // C __c11_atomic_init(A *, C) 5666 Init, 5667 5668 // C __c11_atomic_load(A *, int) 5669 Load, 5670 5671 // void __atomic_load(A *, CP, int) 5672 LoadCopy, 5673 5674 // void __atomic_store(A *, CP, int) 5675 Copy, 5676 5677 // C __c11_atomic_add(A *, M, int) 5678 Arithmetic, 5679 5680 // C __atomic_exchange_n(A *, CP, int) 5681 Xchg, 5682 5683 // void __atomic_exchange(A *, C *, CP, int) 5684 GNUXchg, 5685 5686 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 5687 C11CmpXchg, 5688 5689 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 5690 GNUCmpXchg 5691 } Form = Init; 5692 5693 const unsigned NumForm = GNUCmpXchg + 1; 5694 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 5695 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 5696 // where: 5697 // C is an appropriate type, 5698 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 5699 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 5700 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 5701 // the int parameters are for orderings. 5702 5703 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 5704 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 5705 "need to update code for modified forms"); 5706 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 5707 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 5708 AtomicExpr::AO__atomic_load, 5709 "need to update code for modified C11 atomics"); 5710 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 5711 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 5712 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load && 5713 Op <= AtomicExpr::AO__hip_atomic_fetch_max; 5714 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 5715 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 5716 IsOpenCL; 5717 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 5718 Op == AtomicExpr::AO__atomic_store_n || 5719 Op == AtomicExpr::AO__atomic_exchange_n || 5720 Op == AtomicExpr::AO__atomic_compare_exchange_n; 5721 bool IsAddSub = false; 5722 5723 switch (Op) { 5724 case AtomicExpr::AO__c11_atomic_init: 5725 case AtomicExpr::AO__opencl_atomic_init: 5726 Form = Init; 5727 break; 5728 5729 case AtomicExpr::AO__c11_atomic_load: 5730 case AtomicExpr::AO__opencl_atomic_load: 5731 case AtomicExpr::AO__hip_atomic_load: 5732 case AtomicExpr::AO__atomic_load_n: 5733 Form = Load; 5734 break; 5735 5736 case AtomicExpr::AO__atomic_load: 5737 Form = LoadCopy; 5738 break; 5739 5740 case AtomicExpr::AO__c11_atomic_store: 5741 case AtomicExpr::AO__opencl_atomic_store: 5742 case AtomicExpr::AO__hip_atomic_store: 5743 case AtomicExpr::AO__atomic_store: 5744 case AtomicExpr::AO__atomic_store_n: 5745 Form = Copy; 5746 break; 5747 case AtomicExpr::AO__hip_atomic_fetch_add: 5748 case AtomicExpr::AO__hip_atomic_fetch_min: 5749 case AtomicExpr::AO__hip_atomic_fetch_max: 5750 case AtomicExpr::AO__c11_atomic_fetch_add: 5751 case AtomicExpr::AO__c11_atomic_fetch_sub: 5752 case AtomicExpr::AO__opencl_atomic_fetch_add: 5753 case AtomicExpr::AO__opencl_atomic_fetch_sub: 5754 case AtomicExpr::AO__atomic_fetch_add: 5755 case AtomicExpr::AO__atomic_fetch_sub: 5756 case AtomicExpr::AO__atomic_add_fetch: 5757 case AtomicExpr::AO__atomic_sub_fetch: 5758 IsAddSub = true; 5759 Form = Arithmetic; 5760 break; 5761 case AtomicExpr::AO__c11_atomic_fetch_and: 5762 case AtomicExpr::AO__c11_atomic_fetch_or: 5763 case AtomicExpr::AO__c11_atomic_fetch_xor: 5764 case AtomicExpr::AO__hip_atomic_fetch_and: 5765 case AtomicExpr::AO__hip_atomic_fetch_or: 5766 case AtomicExpr::AO__hip_atomic_fetch_xor: 5767 case AtomicExpr::AO__c11_atomic_fetch_nand: 5768 case AtomicExpr::AO__opencl_atomic_fetch_and: 5769 case AtomicExpr::AO__opencl_atomic_fetch_or: 5770 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5771 case AtomicExpr::AO__atomic_fetch_and: 5772 case AtomicExpr::AO__atomic_fetch_or: 5773 case AtomicExpr::AO__atomic_fetch_xor: 5774 case AtomicExpr::AO__atomic_fetch_nand: 5775 case AtomicExpr::AO__atomic_and_fetch: 5776 case AtomicExpr::AO__atomic_or_fetch: 5777 case AtomicExpr::AO__atomic_xor_fetch: 5778 case AtomicExpr::AO__atomic_nand_fetch: 5779 Form = Arithmetic; 5780 break; 5781 case AtomicExpr::AO__c11_atomic_fetch_min: 5782 case AtomicExpr::AO__c11_atomic_fetch_max: 5783 case AtomicExpr::AO__opencl_atomic_fetch_min: 5784 case AtomicExpr::AO__opencl_atomic_fetch_max: 5785 case AtomicExpr::AO__atomic_min_fetch: 5786 case AtomicExpr::AO__atomic_max_fetch: 5787 case AtomicExpr::AO__atomic_fetch_min: 5788 case AtomicExpr::AO__atomic_fetch_max: 5789 Form = Arithmetic; 5790 break; 5791 5792 case AtomicExpr::AO__c11_atomic_exchange: 5793 case AtomicExpr::AO__hip_atomic_exchange: 5794 case AtomicExpr::AO__opencl_atomic_exchange: 5795 case AtomicExpr::AO__atomic_exchange_n: 5796 Form = Xchg; 5797 break; 5798 5799 case AtomicExpr::AO__atomic_exchange: 5800 Form = GNUXchg; 5801 break; 5802 5803 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5804 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5805 case AtomicExpr::AO__hip_atomic_compare_exchange_strong: 5806 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5807 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5808 case AtomicExpr::AO__hip_atomic_compare_exchange_weak: 5809 Form = C11CmpXchg; 5810 break; 5811 5812 case AtomicExpr::AO__atomic_compare_exchange: 5813 case AtomicExpr::AO__atomic_compare_exchange_n: 5814 Form = GNUCmpXchg; 5815 break; 5816 } 5817 5818 unsigned AdjustedNumArgs = NumArgs[Form]; 5819 if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init) 5820 ++AdjustedNumArgs; 5821 // Check we have the right number of arguments. 5822 if (Args.size() < AdjustedNumArgs) { 5823 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5824 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5825 << ExprRange; 5826 return ExprError(); 5827 } else if (Args.size() > AdjustedNumArgs) { 5828 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5829 diag::err_typecheck_call_too_many_args) 5830 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5831 << ExprRange; 5832 return ExprError(); 5833 } 5834 5835 // Inspect the first argument of the atomic operation. 5836 Expr *Ptr = Args[0]; 5837 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5838 if (ConvertedPtr.isInvalid()) 5839 return ExprError(); 5840 5841 Ptr = ConvertedPtr.get(); 5842 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5843 if (!pointerType) { 5844 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5845 << Ptr->getType() << Ptr->getSourceRange(); 5846 return ExprError(); 5847 } 5848 5849 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5850 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5851 QualType ValType = AtomTy; // 'C' 5852 if (IsC11) { 5853 if (!AtomTy->isAtomicType()) { 5854 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5855 << Ptr->getType() << Ptr->getSourceRange(); 5856 return ExprError(); 5857 } 5858 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5859 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5860 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5861 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5862 << Ptr->getSourceRange(); 5863 return ExprError(); 5864 } 5865 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5866 } else if (Form != Load && Form != LoadCopy) { 5867 if (ValType.isConstQualified()) { 5868 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5869 << Ptr->getType() << Ptr->getSourceRange(); 5870 return ExprError(); 5871 } 5872 } 5873 5874 // For an arithmetic operation, the implied arithmetic must be well-formed. 5875 if (Form == Arithmetic) { 5876 // GCC does not enforce these rules for GNU atomics, but we do to help catch 5877 // trivial type errors. 5878 auto IsAllowedValueType = [&](QualType ValType) { 5879 if (ValType->isIntegerType()) 5880 return true; 5881 if (ValType->isPointerType()) 5882 return true; 5883 if (!ValType->isFloatingType()) 5884 return false; 5885 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5886 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5887 &Context.getTargetInfo().getLongDoubleFormat() == 5888 &llvm::APFloat::x87DoubleExtended()) 5889 return false; 5890 return true; 5891 }; 5892 if (IsAddSub && !IsAllowedValueType(ValType)) { 5893 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5894 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5895 return ExprError(); 5896 } 5897 if (!IsAddSub && !ValType->isIntegerType()) { 5898 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5899 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5900 return ExprError(); 5901 } 5902 if (IsC11 && ValType->isPointerType() && 5903 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5904 diag::err_incomplete_type)) { 5905 return ExprError(); 5906 } 5907 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5908 // For __atomic_*_n operations, the value type must be a scalar integral or 5909 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5910 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5911 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5912 return ExprError(); 5913 } 5914 5915 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5916 !AtomTy->isScalarType()) { 5917 // For GNU atomics, require a trivially-copyable type. This is not part of 5918 // the GNU atomics specification but we enforce it for consistency with 5919 // other atomics which generally all require a trivially-copyable type. This 5920 // is because atomics just copy bits. 5921 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5922 << Ptr->getType() << Ptr->getSourceRange(); 5923 return ExprError(); 5924 } 5925 5926 switch (ValType.getObjCLifetime()) { 5927 case Qualifiers::OCL_None: 5928 case Qualifiers::OCL_ExplicitNone: 5929 // okay 5930 break; 5931 5932 case Qualifiers::OCL_Weak: 5933 case Qualifiers::OCL_Strong: 5934 case Qualifiers::OCL_Autoreleasing: 5935 // FIXME: Can this happen? By this point, ValType should be known 5936 // to be trivially copyable. 5937 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5938 << ValType << Ptr->getSourceRange(); 5939 return ExprError(); 5940 } 5941 5942 // All atomic operations have an overload which takes a pointer to a volatile 5943 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5944 // into the result or the other operands. Similarly atomic_load takes a 5945 // pointer to a const 'A'. 5946 ValType.removeLocalVolatile(); 5947 ValType.removeLocalConst(); 5948 QualType ResultType = ValType; 5949 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5950 Form == Init) 5951 ResultType = Context.VoidTy; 5952 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5953 ResultType = Context.BoolTy; 5954 5955 // The type of a parameter passed 'by value'. In the GNU atomics, such 5956 // arguments are actually passed as pointers. 5957 QualType ByValType = ValType; // 'CP' 5958 bool IsPassedByAddress = false; 5959 if (!IsC11 && !IsHIP && !IsN) { 5960 ByValType = Ptr->getType(); 5961 IsPassedByAddress = true; 5962 } 5963 5964 SmallVector<Expr *, 5> APIOrderedArgs; 5965 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5966 APIOrderedArgs.push_back(Args[0]); 5967 switch (Form) { 5968 case Init: 5969 case Load: 5970 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5971 break; 5972 case LoadCopy: 5973 case Copy: 5974 case Arithmetic: 5975 case Xchg: 5976 APIOrderedArgs.push_back(Args[2]); // Val1 5977 APIOrderedArgs.push_back(Args[1]); // Order 5978 break; 5979 case GNUXchg: 5980 APIOrderedArgs.push_back(Args[2]); // Val1 5981 APIOrderedArgs.push_back(Args[3]); // Val2 5982 APIOrderedArgs.push_back(Args[1]); // Order 5983 break; 5984 case C11CmpXchg: 5985 APIOrderedArgs.push_back(Args[2]); // Val1 5986 APIOrderedArgs.push_back(Args[4]); // Val2 5987 APIOrderedArgs.push_back(Args[1]); // Order 5988 APIOrderedArgs.push_back(Args[3]); // OrderFail 5989 break; 5990 case GNUCmpXchg: 5991 APIOrderedArgs.push_back(Args[2]); // Val1 5992 APIOrderedArgs.push_back(Args[4]); // Val2 5993 APIOrderedArgs.push_back(Args[5]); // Weak 5994 APIOrderedArgs.push_back(Args[1]); // Order 5995 APIOrderedArgs.push_back(Args[3]); // OrderFail 5996 break; 5997 } 5998 } else 5999 APIOrderedArgs.append(Args.begin(), Args.end()); 6000 6001 // The first argument's non-CV pointer type is used to deduce the type of 6002 // subsequent arguments, except for: 6003 // - weak flag (always converted to bool) 6004 // - memory order (always converted to int) 6005 // - scope (always converted to int) 6006 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 6007 QualType Ty; 6008 if (i < NumVals[Form] + 1) { 6009 switch (i) { 6010 case 0: 6011 // The first argument is always a pointer. It has a fixed type. 6012 // It is always dereferenced, a nullptr is undefined. 6013 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 6014 // Nothing else to do: we already know all we want about this pointer. 6015 continue; 6016 case 1: 6017 // The second argument is the non-atomic operand. For arithmetic, this 6018 // is always passed by value, and for a compare_exchange it is always 6019 // passed by address. For the rest, GNU uses by-address and C11 uses 6020 // by-value. 6021 assert(Form != Load); 6022 if (Form == Arithmetic && ValType->isPointerType()) 6023 Ty = Context.getPointerDiffType(); 6024 else if (Form == Init || Form == Arithmetic) 6025 Ty = ValType; 6026 else if (Form == Copy || Form == Xchg) { 6027 if (IsPassedByAddress) { 6028 // The value pointer is always dereferenced, a nullptr is undefined. 6029 CheckNonNullArgument(*this, APIOrderedArgs[i], 6030 ExprRange.getBegin()); 6031 } 6032 Ty = ByValType; 6033 } else { 6034 Expr *ValArg = APIOrderedArgs[i]; 6035 // The value pointer is always dereferenced, a nullptr is undefined. 6036 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 6037 LangAS AS = LangAS::Default; 6038 // Keep address space of non-atomic pointer type. 6039 if (const PointerType *PtrTy = 6040 ValArg->getType()->getAs<PointerType>()) { 6041 AS = PtrTy->getPointeeType().getAddressSpace(); 6042 } 6043 Ty = Context.getPointerType( 6044 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 6045 } 6046 break; 6047 case 2: 6048 // The third argument to compare_exchange / GNU exchange is the desired 6049 // value, either by-value (for the C11 and *_n variant) or as a pointer. 6050 if (IsPassedByAddress) 6051 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 6052 Ty = ByValType; 6053 break; 6054 case 3: 6055 // The fourth argument to GNU compare_exchange is a 'weak' flag. 6056 Ty = Context.BoolTy; 6057 break; 6058 } 6059 } else { 6060 // The order(s) and scope are always converted to int. 6061 Ty = Context.IntTy; 6062 } 6063 6064 InitializedEntity Entity = 6065 InitializedEntity::InitializeParameter(Context, Ty, false); 6066 ExprResult Arg = APIOrderedArgs[i]; 6067 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6068 if (Arg.isInvalid()) 6069 return true; 6070 APIOrderedArgs[i] = Arg.get(); 6071 } 6072 6073 // Permute the arguments into a 'consistent' order. 6074 SmallVector<Expr*, 5> SubExprs; 6075 SubExprs.push_back(Ptr); 6076 switch (Form) { 6077 case Init: 6078 // Note, AtomicExpr::getVal1() has a special case for this atomic. 6079 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6080 break; 6081 case Load: 6082 SubExprs.push_back(APIOrderedArgs[1]); // Order 6083 break; 6084 case LoadCopy: 6085 case Copy: 6086 case Arithmetic: 6087 case Xchg: 6088 SubExprs.push_back(APIOrderedArgs[2]); // Order 6089 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6090 break; 6091 case GNUXchg: 6092 // Note, AtomicExpr::getVal2() has a special case for this atomic. 6093 SubExprs.push_back(APIOrderedArgs[3]); // Order 6094 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6095 SubExprs.push_back(APIOrderedArgs[2]); // Val2 6096 break; 6097 case C11CmpXchg: 6098 SubExprs.push_back(APIOrderedArgs[3]); // Order 6099 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6100 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 6101 SubExprs.push_back(APIOrderedArgs[2]); // Val2 6102 break; 6103 case GNUCmpXchg: 6104 SubExprs.push_back(APIOrderedArgs[4]); // Order 6105 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6106 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 6107 SubExprs.push_back(APIOrderedArgs[2]); // Val2 6108 SubExprs.push_back(APIOrderedArgs[3]); // Weak 6109 break; 6110 } 6111 6112 if (SubExprs.size() >= 2 && Form != Init) { 6113 if (Optional<llvm::APSInt> Result = 6114 SubExprs[1]->getIntegerConstantExpr(Context)) 6115 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 6116 Diag(SubExprs[1]->getBeginLoc(), 6117 diag::warn_atomic_op_has_invalid_memory_order) 6118 << SubExprs[1]->getSourceRange(); 6119 } 6120 6121 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 6122 auto *Scope = Args[Args.size() - 1]; 6123 if (Optional<llvm::APSInt> Result = 6124 Scope->getIntegerConstantExpr(Context)) { 6125 if (!ScopeModel->isValid(Result->getZExtValue())) 6126 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 6127 << Scope->getSourceRange(); 6128 } 6129 SubExprs.push_back(Scope); 6130 } 6131 6132 AtomicExpr *AE = new (Context) 6133 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 6134 6135 if ((Op == AtomicExpr::AO__c11_atomic_load || 6136 Op == AtomicExpr::AO__c11_atomic_store || 6137 Op == AtomicExpr::AO__opencl_atomic_load || 6138 Op == AtomicExpr::AO__hip_atomic_load || 6139 Op == AtomicExpr::AO__opencl_atomic_store || 6140 Op == AtomicExpr::AO__hip_atomic_store) && 6141 Context.AtomicUsesUnsupportedLibcall(AE)) 6142 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 6143 << ((Op == AtomicExpr::AO__c11_atomic_load || 6144 Op == AtomicExpr::AO__opencl_atomic_load || 6145 Op == AtomicExpr::AO__hip_atomic_load) 6146 ? 0 6147 : 1); 6148 6149 if (ValType->isBitIntType()) { 6150 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit); 6151 return ExprError(); 6152 } 6153 6154 return AE; 6155 } 6156 6157 /// checkBuiltinArgument - Given a call to a builtin function, perform 6158 /// normal type-checking on the given argument, updating the call in 6159 /// place. This is useful when a builtin function requires custom 6160 /// type-checking for some of its arguments but not necessarily all of 6161 /// them. 6162 /// 6163 /// Returns true on error. 6164 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 6165 FunctionDecl *Fn = E->getDirectCallee(); 6166 assert(Fn && "builtin call without direct callee!"); 6167 6168 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 6169 InitializedEntity Entity = 6170 InitializedEntity::InitializeParameter(S.Context, Param); 6171 6172 ExprResult Arg = E->getArg(0); 6173 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 6174 if (Arg.isInvalid()) 6175 return true; 6176 6177 E->setArg(ArgIndex, Arg.get()); 6178 return false; 6179 } 6180 6181 /// We have a call to a function like __sync_fetch_and_add, which is an 6182 /// overloaded function based on the pointer type of its first argument. 6183 /// The main BuildCallExpr routines have already promoted the types of 6184 /// arguments because all of these calls are prototyped as void(...). 6185 /// 6186 /// This function goes through and does final semantic checking for these 6187 /// builtins, as well as generating any warnings. 6188 ExprResult 6189 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 6190 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 6191 Expr *Callee = TheCall->getCallee(); 6192 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 6193 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6194 6195 // Ensure that we have at least one argument to do type inference from. 6196 if (TheCall->getNumArgs() < 1) { 6197 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6198 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 6199 return ExprError(); 6200 } 6201 6202 // Inspect the first argument of the atomic builtin. This should always be 6203 // a pointer type, whose element is an integral scalar or pointer type. 6204 // Because it is a pointer type, we don't have to worry about any implicit 6205 // casts here. 6206 // FIXME: We don't allow floating point scalars as input. 6207 Expr *FirstArg = TheCall->getArg(0); 6208 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 6209 if (FirstArgResult.isInvalid()) 6210 return ExprError(); 6211 FirstArg = FirstArgResult.get(); 6212 TheCall->setArg(0, FirstArg); 6213 6214 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 6215 if (!pointerType) { 6216 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 6217 << FirstArg->getType() << FirstArg->getSourceRange(); 6218 return ExprError(); 6219 } 6220 6221 QualType ValType = pointerType->getPointeeType(); 6222 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6223 !ValType->isBlockPointerType()) { 6224 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 6225 << FirstArg->getType() << FirstArg->getSourceRange(); 6226 return ExprError(); 6227 } 6228 6229 if (ValType.isConstQualified()) { 6230 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 6231 << FirstArg->getType() << FirstArg->getSourceRange(); 6232 return ExprError(); 6233 } 6234 6235 switch (ValType.getObjCLifetime()) { 6236 case Qualifiers::OCL_None: 6237 case Qualifiers::OCL_ExplicitNone: 6238 // okay 6239 break; 6240 6241 case Qualifiers::OCL_Weak: 6242 case Qualifiers::OCL_Strong: 6243 case Qualifiers::OCL_Autoreleasing: 6244 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 6245 << ValType << FirstArg->getSourceRange(); 6246 return ExprError(); 6247 } 6248 6249 // Strip any qualifiers off ValType. 6250 ValType = ValType.getUnqualifiedType(); 6251 6252 // The majority of builtins return a value, but a few have special return 6253 // types, so allow them to override appropriately below. 6254 QualType ResultType = ValType; 6255 6256 // We need to figure out which concrete builtin this maps onto. For example, 6257 // __sync_fetch_and_add with a 2 byte object turns into 6258 // __sync_fetch_and_add_2. 6259 #define BUILTIN_ROW(x) \ 6260 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 6261 Builtin::BI##x##_8, Builtin::BI##x##_16 } 6262 6263 static const unsigned BuiltinIndices[][5] = { 6264 BUILTIN_ROW(__sync_fetch_and_add), 6265 BUILTIN_ROW(__sync_fetch_and_sub), 6266 BUILTIN_ROW(__sync_fetch_and_or), 6267 BUILTIN_ROW(__sync_fetch_and_and), 6268 BUILTIN_ROW(__sync_fetch_and_xor), 6269 BUILTIN_ROW(__sync_fetch_and_nand), 6270 6271 BUILTIN_ROW(__sync_add_and_fetch), 6272 BUILTIN_ROW(__sync_sub_and_fetch), 6273 BUILTIN_ROW(__sync_and_and_fetch), 6274 BUILTIN_ROW(__sync_or_and_fetch), 6275 BUILTIN_ROW(__sync_xor_and_fetch), 6276 BUILTIN_ROW(__sync_nand_and_fetch), 6277 6278 BUILTIN_ROW(__sync_val_compare_and_swap), 6279 BUILTIN_ROW(__sync_bool_compare_and_swap), 6280 BUILTIN_ROW(__sync_lock_test_and_set), 6281 BUILTIN_ROW(__sync_lock_release), 6282 BUILTIN_ROW(__sync_swap) 6283 }; 6284 #undef BUILTIN_ROW 6285 6286 // Determine the index of the size. 6287 unsigned SizeIndex; 6288 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 6289 case 1: SizeIndex = 0; break; 6290 case 2: SizeIndex = 1; break; 6291 case 4: SizeIndex = 2; break; 6292 case 8: SizeIndex = 3; break; 6293 case 16: SizeIndex = 4; break; 6294 default: 6295 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 6296 << FirstArg->getType() << FirstArg->getSourceRange(); 6297 return ExprError(); 6298 } 6299 6300 // Each of these builtins has one pointer argument, followed by some number of 6301 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 6302 // that we ignore. Find out which row of BuiltinIndices to read from as well 6303 // as the number of fixed args. 6304 unsigned BuiltinID = FDecl->getBuiltinID(); 6305 unsigned BuiltinIndex, NumFixed = 1; 6306 bool WarnAboutSemanticsChange = false; 6307 switch (BuiltinID) { 6308 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 6309 case Builtin::BI__sync_fetch_and_add: 6310 case Builtin::BI__sync_fetch_and_add_1: 6311 case Builtin::BI__sync_fetch_and_add_2: 6312 case Builtin::BI__sync_fetch_and_add_4: 6313 case Builtin::BI__sync_fetch_and_add_8: 6314 case Builtin::BI__sync_fetch_and_add_16: 6315 BuiltinIndex = 0; 6316 break; 6317 6318 case Builtin::BI__sync_fetch_and_sub: 6319 case Builtin::BI__sync_fetch_and_sub_1: 6320 case Builtin::BI__sync_fetch_and_sub_2: 6321 case Builtin::BI__sync_fetch_and_sub_4: 6322 case Builtin::BI__sync_fetch_and_sub_8: 6323 case Builtin::BI__sync_fetch_and_sub_16: 6324 BuiltinIndex = 1; 6325 break; 6326 6327 case Builtin::BI__sync_fetch_and_or: 6328 case Builtin::BI__sync_fetch_and_or_1: 6329 case Builtin::BI__sync_fetch_and_or_2: 6330 case Builtin::BI__sync_fetch_and_or_4: 6331 case Builtin::BI__sync_fetch_and_or_8: 6332 case Builtin::BI__sync_fetch_and_or_16: 6333 BuiltinIndex = 2; 6334 break; 6335 6336 case Builtin::BI__sync_fetch_and_and: 6337 case Builtin::BI__sync_fetch_and_and_1: 6338 case Builtin::BI__sync_fetch_and_and_2: 6339 case Builtin::BI__sync_fetch_and_and_4: 6340 case Builtin::BI__sync_fetch_and_and_8: 6341 case Builtin::BI__sync_fetch_and_and_16: 6342 BuiltinIndex = 3; 6343 break; 6344 6345 case Builtin::BI__sync_fetch_and_xor: 6346 case Builtin::BI__sync_fetch_and_xor_1: 6347 case Builtin::BI__sync_fetch_and_xor_2: 6348 case Builtin::BI__sync_fetch_and_xor_4: 6349 case Builtin::BI__sync_fetch_and_xor_8: 6350 case Builtin::BI__sync_fetch_and_xor_16: 6351 BuiltinIndex = 4; 6352 break; 6353 6354 case Builtin::BI__sync_fetch_and_nand: 6355 case Builtin::BI__sync_fetch_and_nand_1: 6356 case Builtin::BI__sync_fetch_and_nand_2: 6357 case Builtin::BI__sync_fetch_and_nand_4: 6358 case Builtin::BI__sync_fetch_and_nand_8: 6359 case Builtin::BI__sync_fetch_and_nand_16: 6360 BuiltinIndex = 5; 6361 WarnAboutSemanticsChange = true; 6362 break; 6363 6364 case Builtin::BI__sync_add_and_fetch: 6365 case Builtin::BI__sync_add_and_fetch_1: 6366 case Builtin::BI__sync_add_and_fetch_2: 6367 case Builtin::BI__sync_add_and_fetch_4: 6368 case Builtin::BI__sync_add_and_fetch_8: 6369 case Builtin::BI__sync_add_and_fetch_16: 6370 BuiltinIndex = 6; 6371 break; 6372 6373 case Builtin::BI__sync_sub_and_fetch: 6374 case Builtin::BI__sync_sub_and_fetch_1: 6375 case Builtin::BI__sync_sub_and_fetch_2: 6376 case Builtin::BI__sync_sub_and_fetch_4: 6377 case Builtin::BI__sync_sub_and_fetch_8: 6378 case Builtin::BI__sync_sub_and_fetch_16: 6379 BuiltinIndex = 7; 6380 break; 6381 6382 case Builtin::BI__sync_and_and_fetch: 6383 case Builtin::BI__sync_and_and_fetch_1: 6384 case Builtin::BI__sync_and_and_fetch_2: 6385 case Builtin::BI__sync_and_and_fetch_4: 6386 case Builtin::BI__sync_and_and_fetch_8: 6387 case Builtin::BI__sync_and_and_fetch_16: 6388 BuiltinIndex = 8; 6389 break; 6390 6391 case Builtin::BI__sync_or_and_fetch: 6392 case Builtin::BI__sync_or_and_fetch_1: 6393 case Builtin::BI__sync_or_and_fetch_2: 6394 case Builtin::BI__sync_or_and_fetch_4: 6395 case Builtin::BI__sync_or_and_fetch_8: 6396 case Builtin::BI__sync_or_and_fetch_16: 6397 BuiltinIndex = 9; 6398 break; 6399 6400 case Builtin::BI__sync_xor_and_fetch: 6401 case Builtin::BI__sync_xor_and_fetch_1: 6402 case Builtin::BI__sync_xor_and_fetch_2: 6403 case Builtin::BI__sync_xor_and_fetch_4: 6404 case Builtin::BI__sync_xor_and_fetch_8: 6405 case Builtin::BI__sync_xor_and_fetch_16: 6406 BuiltinIndex = 10; 6407 break; 6408 6409 case Builtin::BI__sync_nand_and_fetch: 6410 case Builtin::BI__sync_nand_and_fetch_1: 6411 case Builtin::BI__sync_nand_and_fetch_2: 6412 case Builtin::BI__sync_nand_and_fetch_4: 6413 case Builtin::BI__sync_nand_and_fetch_8: 6414 case Builtin::BI__sync_nand_and_fetch_16: 6415 BuiltinIndex = 11; 6416 WarnAboutSemanticsChange = true; 6417 break; 6418 6419 case Builtin::BI__sync_val_compare_and_swap: 6420 case Builtin::BI__sync_val_compare_and_swap_1: 6421 case Builtin::BI__sync_val_compare_and_swap_2: 6422 case Builtin::BI__sync_val_compare_and_swap_4: 6423 case Builtin::BI__sync_val_compare_and_swap_8: 6424 case Builtin::BI__sync_val_compare_and_swap_16: 6425 BuiltinIndex = 12; 6426 NumFixed = 2; 6427 break; 6428 6429 case Builtin::BI__sync_bool_compare_and_swap: 6430 case Builtin::BI__sync_bool_compare_and_swap_1: 6431 case Builtin::BI__sync_bool_compare_and_swap_2: 6432 case Builtin::BI__sync_bool_compare_and_swap_4: 6433 case Builtin::BI__sync_bool_compare_and_swap_8: 6434 case Builtin::BI__sync_bool_compare_and_swap_16: 6435 BuiltinIndex = 13; 6436 NumFixed = 2; 6437 ResultType = Context.BoolTy; 6438 break; 6439 6440 case Builtin::BI__sync_lock_test_and_set: 6441 case Builtin::BI__sync_lock_test_and_set_1: 6442 case Builtin::BI__sync_lock_test_and_set_2: 6443 case Builtin::BI__sync_lock_test_and_set_4: 6444 case Builtin::BI__sync_lock_test_and_set_8: 6445 case Builtin::BI__sync_lock_test_and_set_16: 6446 BuiltinIndex = 14; 6447 break; 6448 6449 case Builtin::BI__sync_lock_release: 6450 case Builtin::BI__sync_lock_release_1: 6451 case Builtin::BI__sync_lock_release_2: 6452 case Builtin::BI__sync_lock_release_4: 6453 case Builtin::BI__sync_lock_release_8: 6454 case Builtin::BI__sync_lock_release_16: 6455 BuiltinIndex = 15; 6456 NumFixed = 0; 6457 ResultType = Context.VoidTy; 6458 break; 6459 6460 case Builtin::BI__sync_swap: 6461 case Builtin::BI__sync_swap_1: 6462 case Builtin::BI__sync_swap_2: 6463 case Builtin::BI__sync_swap_4: 6464 case Builtin::BI__sync_swap_8: 6465 case Builtin::BI__sync_swap_16: 6466 BuiltinIndex = 16; 6467 break; 6468 } 6469 6470 // Now that we know how many fixed arguments we expect, first check that we 6471 // have at least that many. 6472 if (TheCall->getNumArgs() < 1+NumFixed) { 6473 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6474 << 0 << 1 + NumFixed << TheCall->getNumArgs() 6475 << Callee->getSourceRange(); 6476 return ExprError(); 6477 } 6478 6479 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 6480 << Callee->getSourceRange(); 6481 6482 if (WarnAboutSemanticsChange) { 6483 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 6484 << Callee->getSourceRange(); 6485 } 6486 6487 // Get the decl for the concrete builtin from this, we can tell what the 6488 // concrete integer type we should convert to is. 6489 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 6490 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 6491 FunctionDecl *NewBuiltinDecl; 6492 if (NewBuiltinID == BuiltinID) 6493 NewBuiltinDecl = FDecl; 6494 else { 6495 // Perform builtin lookup to avoid redeclaring it. 6496 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 6497 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 6498 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 6499 assert(Res.getFoundDecl()); 6500 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 6501 if (!NewBuiltinDecl) 6502 return ExprError(); 6503 } 6504 6505 // The first argument --- the pointer --- has a fixed type; we 6506 // deduce the types of the rest of the arguments accordingly. Walk 6507 // the remaining arguments, converting them to the deduced value type. 6508 for (unsigned i = 0; i != NumFixed; ++i) { 6509 ExprResult Arg = TheCall->getArg(i+1); 6510 6511 // GCC does an implicit conversion to the pointer or integer ValType. This 6512 // can fail in some cases (1i -> int**), check for this error case now. 6513 // Initialize the argument. 6514 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6515 ValType, /*consume*/ false); 6516 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6517 if (Arg.isInvalid()) 6518 return ExprError(); 6519 6520 // Okay, we have something that *can* be converted to the right type. Check 6521 // to see if there is a potentially weird extension going on here. This can 6522 // happen when you do an atomic operation on something like an char* and 6523 // pass in 42. The 42 gets converted to char. This is even more strange 6524 // for things like 45.123 -> char, etc. 6525 // FIXME: Do this check. 6526 TheCall->setArg(i+1, Arg.get()); 6527 } 6528 6529 // Create a new DeclRefExpr to refer to the new decl. 6530 DeclRefExpr *NewDRE = DeclRefExpr::Create( 6531 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 6532 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 6533 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 6534 6535 // Set the callee in the CallExpr. 6536 // FIXME: This loses syntactic information. 6537 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 6538 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 6539 CK_BuiltinFnToFnPtr); 6540 TheCall->setCallee(PromotedCall.get()); 6541 6542 // Change the result type of the call to match the original value type. This 6543 // is arbitrary, but the codegen for these builtins ins design to handle it 6544 // gracefully. 6545 TheCall->setType(ResultType); 6546 6547 // Prohibit problematic uses of bit-precise integer types with atomic 6548 // builtins. The arguments would have already been converted to the first 6549 // argument's type, so only need to check the first argument. 6550 const auto *BitIntValType = ValType->getAs<BitIntType>(); 6551 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) { 6552 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 6553 return ExprError(); 6554 } 6555 6556 return TheCallResult; 6557 } 6558 6559 /// SemaBuiltinNontemporalOverloaded - We have a call to 6560 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 6561 /// overloaded function based on the pointer type of its last argument. 6562 /// 6563 /// This function goes through and does final semantic checking for these 6564 /// builtins. 6565 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 6566 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 6567 DeclRefExpr *DRE = 6568 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6569 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6570 unsigned BuiltinID = FDecl->getBuiltinID(); 6571 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 6572 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 6573 "Unexpected nontemporal load/store builtin!"); 6574 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 6575 unsigned numArgs = isStore ? 2 : 1; 6576 6577 // Ensure that we have the proper number of arguments. 6578 if (checkArgCount(*this, TheCall, numArgs)) 6579 return ExprError(); 6580 6581 // Inspect the last argument of the nontemporal builtin. This should always 6582 // be a pointer type, from which we imply the type of the memory access. 6583 // Because it is a pointer type, we don't have to worry about any implicit 6584 // casts here. 6585 Expr *PointerArg = TheCall->getArg(numArgs - 1); 6586 ExprResult PointerArgResult = 6587 DefaultFunctionArrayLvalueConversion(PointerArg); 6588 6589 if (PointerArgResult.isInvalid()) 6590 return ExprError(); 6591 PointerArg = PointerArgResult.get(); 6592 TheCall->setArg(numArgs - 1, PointerArg); 6593 6594 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 6595 if (!pointerType) { 6596 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 6597 << PointerArg->getType() << PointerArg->getSourceRange(); 6598 return ExprError(); 6599 } 6600 6601 QualType ValType = pointerType->getPointeeType(); 6602 6603 // Strip any qualifiers off ValType. 6604 ValType = ValType.getUnqualifiedType(); 6605 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6606 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 6607 !ValType->isVectorType()) { 6608 Diag(DRE->getBeginLoc(), 6609 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 6610 << PointerArg->getType() << PointerArg->getSourceRange(); 6611 return ExprError(); 6612 } 6613 6614 if (!isStore) { 6615 TheCall->setType(ValType); 6616 return TheCallResult; 6617 } 6618 6619 ExprResult ValArg = TheCall->getArg(0); 6620 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6621 Context, ValType, /*consume*/ false); 6622 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 6623 if (ValArg.isInvalid()) 6624 return ExprError(); 6625 6626 TheCall->setArg(0, ValArg.get()); 6627 TheCall->setType(Context.VoidTy); 6628 return TheCallResult; 6629 } 6630 6631 /// CheckObjCString - Checks that the argument to the builtin 6632 /// CFString constructor is correct 6633 /// Note: It might also make sense to do the UTF-16 conversion here (would 6634 /// simplify the backend). 6635 bool Sema::CheckObjCString(Expr *Arg) { 6636 Arg = Arg->IgnoreParenCasts(); 6637 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 6638 6639 if (!Literal || !Literal->isAscii()) { 6640 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 6641 << Arg->getSourceRange(); 6642 return true; 6643 } 6644 6645 if (Literal->containsNonAsciiOrNull()) { 6646 StringRef String = Literal->getString(); 6647 unsigned NumBytes = String.size(); 6648 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6649 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6650 llvm::UTF16 *ToPtr = &ToBuf[0]; 6651 6652 llvm::ConversionResult Result = 6653 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6654 ToPtr + NumBytes, llvm::strictConversion); 6655 // Check for conversion failure. 6656 if (Result != llvm::conversionOK) 6657 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6658 << Arg->getSourceRange(); 6659 } 6660 return false; 6661 } 6662 6663 /// CheckObjCString - Checks that the format string argument to the os_log() 6664 /// and os_trace() functions is correct, and converts it to const char *. 6665 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6666 Arg = Arg->IgnoreParenCasts(); 6667 auto *Literal = dyn_cast<StringLiteral>(Arg); 6668 if (!Literal) { 6669 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6670 Literal = ObjcLiteral->getString(); 6671 } 6672 } 6673 6674 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6675 return ExprError( 6676 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 6677 << Arg->getSourceRange()); 6678 } 6679 6680 ExprResult Result(Literal); 6681 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 6682 InitializedEntity Entity = 6683 InitializedEntity::InitializeParameter(Context, ResultTy, false); 6684 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 6685 return Result; 6686 } 6687 6688 /// Check that the user is calling the appropriate va_start builtin for the 6689 /// target and calling convention. 6690 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 6691 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 6692 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 6693 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 6694 TT.getArch() == llvm::Triple::aarch64_32); 6695 bool IsWindows = TT.isOSWindows(); 6696 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 6697 if (IsX64 || IsAArch64) { 6698 CallingConv CC = CC_C; 6699 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 6700 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 6701 if (IsMSVAStart) { 6702 // Don't allow this in System V ABI functions. 6703 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 6704 return S.Diag(Fn->getBeginLoc(), 6705 diag::err_ms_va_start_used_in_sysv_function); 6706 } else { 6707 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 6708 // On x64 Windows, don't allow this in System V ABI functions. 6709 // (Yes, that means there's no corresponding way to support variadic 6710 // System V ABI functions on Windows.) 6711 if ((IsWindows && CC == CC_X86_64SysV) || 6712 (!IsWindows && CC == CC_Win64)) 6713 return S.Diag(Fn->getBeginLoc(), 6714 diag::err_va_start_used_in_wrong_abi_function) 6715 << !IsWindows; 6716 } 6717 return false; 6718 } 6719 6720 if (IsMSVAStart) 6721 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 6722 return false; 6723 } 6724 6725 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 6726 ParmVarDecl **LastParam = nullptr) { 6727 // Determine whether the current function, block, or obj-c method is variadic 6728 // and get its parameter list. 6729 bool IsVariadic = false; 6730 ArrayRef<ParmVarDecl *> Params; 6731 DeclContext *Caller = S.CurContext; 6732 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 6733 IsVariadic = Block->isVariadic(); 6734 Params = Block->parameters(); 6735 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 6736 IsVariadic = FD->isVariadic(); 6737 Params = FD->parameters(); 6738 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 6739 IsVariadic = MD->isVariadic(); 6740 // FIXME: This isn't correct for methods (results in bogus warning). 6741 Params = MD->parameters(); 6742 } else if (isa<CapturedDecl>(Caller)) { 6743 // We don't support va_start in a CapturedDecl. 6744 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 6745 return true; 6746 } else { 6747 // This must be some other declcontext that parses exprs. 6748 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 6749 return true; 6750 } 6751 6752 if (!IsVariadic) { 6753 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 6754 return true; 6755 } 6756 6757 if (LastParam) 6758 *LastParam = Params.empty() ? nullptr : Params.back(); 6759 6760 return false; 6761 } 6762 6763 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 6764 /// for validity. Emit an error and return true on failure; return false 6765 /// on success. 6766 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 6767 Expr *Fn = TheCall->getCallee(); 6768 6769 if (checkVAStartABI(*this, BuiltinID, Fn)) 6770 return true; 6771 6772 if (checkArgCount(*this, TheCall, 2)) 6773 return true; 6774 6775 // Type-check the first argument normally. 6776 if (checkBuiltinArgument(*this, TheCall, 0)) 6777 return true; 6778 6779 // Check that the current function is variadic, and get its last parameter. 6780 ParmVarDecl *LastParam; 6781 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6782 return true; 6783 6784 // Verify that the second argument to the builtin is the last argument of the 6785 // current function or method. 6786 bool SecondArgIsLastNamedArgument = false; 6787 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6788 6789 // These are valid if SecondArgIsLastNamedArgument is false after the next 6790 // block. 6791 QualType Type; 6792 SourceLocation ParamLoc; 6793 bool IsCRegister = false; 6794 6795 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6796 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6797 SecondArgIsLastNamedArgument = PV == LastParam; 6798 6799 Type = PV->getType(); 6800 ParamLoc = PV->getLocation(); 6801 IsCRegister = 6802 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6803 } 6804 } 6805 6806 if (!SecondArgIsLastNamedArgument) 6807 Diag(TheCall->getArg(1)->getBeginLoc(), 6808 diag::warn_second_arg_of_va_start_not_last_named_param); 6809 else if (IsCRegister || Type->isReferenceType() || 6810 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6811 // Promotable integers are UB, but enumerations need a bit of 6812 // extra checking to see what their promotable type actually is. 6813 if (!Type->isPromotableIntegerType()) 6814 return false; 6815 if (!Type->isEnumeralType()) 6816 return true; 6817 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6818 return !(ED && 6819 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6820 }()) { 6821 unsigned Reason = 0; 6822 if (Type->isReferenceType()) Reason = 1; 6823 else if (IsCRegister) Reason = 2; 6824 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6825 Diag(ParamLoc, diag::note_parameter_type) << Type; 6826 } 6827 6828 TheCall->setType(Context.VoidTy); 6829 return false; 6830 } 6831 6832 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6833 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool { 6834 const LangOptions &LO = getLangOpts(); 6835 6836 if (LO.CPlusPlus) 6837 return Arg->getType() 6838 .getCanonicalType() 6839 .getTypePtr() 6840 ->getPointeeType() 6841 .withoutLocalFastQualifiers() == Context.CharTy; 6842 6843 // In C, allow aliasing through `char *`, this is required for AArch64 at 6844 // least. 6845 return true; 6846 }; 6847 6848 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6849 // const char *named_addr); 6850 6851 Expr *Func = Call->getCallee(); 6852 6853 if (Call->getNumArgs() < 3) 6854 return Diag(Call->getEndLoc(), 6855 diag::err_typecheck_call_too_few_args_at_least) 6856 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6857 6858 // Type-check the first argument normally. 6859 if (checkBuiltinArgument(*this, Call, 0)) 6860 return true; 6861 6862 // Check that the current function is variadic. 6863 if (checkVAStartIsInVariadicFunction(*this, Func)) 6864 return true; 6865 6866 // __va_start on Windows does not validate the parameter qualifiers 6867 6868 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6869 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6870 6871 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6872 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6873 6874 const QualType &ConstCharPtrTy = 6875 Context.getPointerType(Context.CharTy.withConst()); 6876 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1)) 6877 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6878 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6879 << 0 /* qualifier difference */ 6880 << 3 /* parameter mismatch */ 6881 << 2 << Arg1->getType() << ConstCharPtrTy; 6882 6883 const QualType SizeTy = Context.getSizeType(); 6884 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6885 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6886 << Arg2->getType() << SizeTy << 1 /* different class */ 6887 << 0 /* qualifier difference */ 6888 << 3 /* parameter mismatch */ 6889 << 3 << Arg2->getType() << SizeTy; 6890 6891 return false; 6892 } 6893 6894 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6895 /// friends. This is declared to take (...), so we have to check everything. 6896 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6897 if (checkArgCount(*this, TheCall, 2)) 6898 return true; 6899 6900 ExprResult OrigArg0 = TheCall->getArg(0); 6901 ExprResult OrigArg1 = TheCall->getArg(1); 6902 6903 // Do standard promotions between the two arguments, returning their common 6904 // type. 6905 QualType Res = UsualArithmeticConversions( 6906 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6907 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6908 return true; 6909 6910 // Make sure any conversions are pushed back into the call; this is 6911 // type safe since unordered compare builtins are declared as "_Bool 6912 // foo(...)". 6913 TheCall->setArg(0, OrigArg0.get()); 6914 TheCall->setArg(1, OrigArg1.get()); 6915 6916 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6917 return false; 6918 6919 // If the common type isn't a real floating type, then the arguments were 6920 // invalid for this operation. 6921 if (Res.isNull() || !Res->isRealFloatingType()) 6922 return Diag(OrigArg0.get()->getBeginLoc(), 6923 diag::err_typecheck_call_invalid_ordered_compare) 6924 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6925 << SourceRange(OrigArg0.get()->getBeginLoc(), 6926 OrigArg1.get()->getEndLoc()); 6927 6928 return false; 6929 } 6930 6931 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6932 /// __builtin_isnan and friends. This is declared to take (...), so we have 6933 /// to check everything. We expect the last argument to be a floating point 6934 /// value. 6935 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6936 if (checkArgCount(*this, TheCall, NumArgs)) 6937 return true; 6938 6939 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6940 // on all preceding parameters just being int. Try all of those. 6941 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6942 Expr *Arg = TheCall->getArg(i); 6943 6944 if (Arg->isTypeDependent()) 6945 return false; 6946 6947 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6948 6949 if (Res.isInvalid()) 6950 return true; 6951 TheCall->setArg(i, Res.get()); 6952 } 6953 6954 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6955 6956 if (OrigArg->isTypeDependent()) 6957 return false; 6958 6959 // Usual Unary Conversions will convert half to float, which we want for 6960 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6961 // type how it is, but do normal L->Rvalue conversions. 6962 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6963 OrigArg = UsualUnaryConversions(OrigArg).get(); 6964 else 6965 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6966 TheCall->setArg(NumArgs - 1, OrigArg); 6967 6968 // This operation requires a non-_Complex floating-point number. 6969 if (!OrigArg->getType()->isRealFloatingType()) 6970 return Diag(OrigArg->getBeginLoc(), 6971 diag::err_typecheck_call_invalid_unary_fp) 6972 << OrigArg->getType() << OrigArg->getSourceRange(); 6973 6974 return false; 6975 } 6976 6977 /// Perform semantic analysis for a call to __builtin_complex. 6978 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6979 if (checkArgCount(*this, TheCall, 2)) 6980 return true; 6981 6982 bool Dependent = false; 6983 for (unsigned I = 0; I != 2; ++I) { 6984 Expr *Arg = TheCall->getArg(I); 6985 QualType T = Arg->getType(); 6986 if (T->isDependentType()) { 6987 Dependent = true; 6988 continue; 6989 } 6990 6991 // Despite supporting _Complex int, GCC requires a real floating point type 6992 // for the operands of __builtin_complex. 6993 if (!T->isRealFloatingType()) { 6994 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6995 << Arg->getType() << Arg->getSourceRange(); 6996 } 6997 6998 ExprResult Converted = DefaultLvalueConversion(Arg); 6999 if (Converted.isInvalid()) 7000 return true; 7001 TheCall->setArg(I, Converted.get()); 7002 } 7003 7004 if (Dependent) { 7005 TheCall->setType(Context.DependentTy); 7006 return false; 7007 } 7008 7009 Expr *Real = TheCall->getArg(0); 7010 Expr *Imag = TheCall->getArg(1); 7011 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 7012 return Diag(Real->getBeginLoc(), 7013 diag::err_typecheck_call_different_arg_types) 7014 << Real->getType() << Imag->getType() 7015 << Real->getSourceRange() << Imag->getSourceRange(); 7016 } 7017 7018 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 7019 // don't allow this builtin to form those types either. 7020 // FIXME: Should we allow these types? 7021 if (Real->getType()->isFloat16Type()) 7022 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 7023 << "_Float16"; 7024 if (Real->getType()->isHalfType()) 7025 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 7026 << "half"; 7027 7028 TheCall->setType(Context.getComplexType(Real->getType())); 7029 return false; 7030 } 7031 7032 // Customized Sema Checking for VSX builtins that have the following signature: 7033 // vector [...] builtinName(vector [...], vector [...], const int); 7034 // Which takes the same type of vectors (any legal vector type) for the first 7035 // two arguments and takes compile time constant for the third argument. 7036 // Example builtins are : 7037 // vector double vec_xxpermdi(vector double, vector double, int); 7038 // vector short vec_xxsldwi(vector short, vector short, int); 7039 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 7040 unsigned ExpectedNumArgs = 3; 7041 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 7042 return true; 7043 7044 // Check the third argument is a compile time constant 7045 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 7046 return Diag(TheCall->getBeginLoc(), 7047 diag::err_vsx_builtin_nonconstant_argument) 7048 << 3 /* argument index */ << TheCall->getDirectCallee() 7049 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 7050 TheCall->getArg(2)->getEndLoc()); 7051 7052 QualType Arg1Ty = TheCall->getArg(0)->getType(); 7053 QualType Arg2Ty = TheCall->getArg(1)->getType(); 7054 7055 // Check the type of argument 1 and argument 2 are vectors. 7056 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 7057 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 7058 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 7059 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 7060 << TheCall->getDirectCallee() 7061 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 7062 TheCall->getArg(1)->getEndLoc()); 7063 } 7064 7065 // Check the first two arguments are the same type. 7066 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 7067 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 7068 << TheCall->getDirectCallee() 7069 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 7070 TheCall->getArg(1)->getEndLoc()); 7071 } 7072 7073 // When default clang type checking is turned off and the customized type 7074 // checking is used, the returning type of the function must be explicitly 7075 // set. Otherwise it is _Bool by default. 7076 TheCall->setType(Arg1Ty); 7077 7078 return false; 7079 } 7080 7081 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 7082 // This is declared to take (...), so we have to check everything. 7083 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 7084 if (TheCall->getNumArgs() < 2) 7085 return ExprError(Diag(TheCall->getEndLoc(), 7086 diag::err_typecheck_call_too_few_args_at_least) 7087 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 7088 << TheCall->getSourceRange()); 7089 7090 // Determine which of the following types of shufflevector we're checking: 7091 // 1) unary, vector mask: (lhs, mask) 7092 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 7093 QualType resType = TheCall->getArg(0)->getType(); 7094 unsigned numElements = 0; 7095 7096 if (!TheCall->getArg(0)->isTypeDependent() && 7097 !TheCall->getArg(1)->isTypeDependent()) { 7098 QualType LHSType = TheCall->getArg(0)->getType(); 7099 QualType RHSType = TheCall->getArg(1)->getType(); 7100 7101 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 7102 return ExprError( 7103 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 7104 << TheCall->getDirectCallee() 7105 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 7106 TheCall->getArg(1)->getEndLoc())); 7107 7108 numElements = LHSType->castAs<VectorType>()->getNumElements(); 7109 unsigned numResElements = TheCall->getNumArgs() - 2; 7110 7111 // Check to see if we have a call with 2 vector arguments, the unary shuffle 7112 // with mask. If so, verify that RHS is an integer vector type with the 7113 // same number of elts as lhs. 7114 if (TheCall->getNumArgs() == 2) { 7115 if (!RHSType->hasIntegerRepresentation() || 7116 RHSType->castAs<VectorType>()->getNumElements() != numElements) 7117 return ExprError(Diag(TheCall->getBeginLoc(), 7118 diag::err_vec_builtin_incompatible_vector) 7119 << TheCall->getDirectCallee() 7120 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 7121 TheCall->getArg(1)->getEndLoc())); 7122 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 7123 return ExprError(Diag(TheCall->getBeginLoc(), 7124 diag::err_vec_builtin_incompatible_vector) 7125 << TheCall->getDirectCallee() 7126 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 7127 TheCall->getArg(1)->getEndLoc())); 7128 } else if (numElements != numResElements) { 7129 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 7130 resType = Context.getVectorType(eltType, numResElements, 7131 VectorType::GenericVector); 7132 } 7133 } 7134 7135 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 7136 if (TheCall->getArg(i)->isTypeDependent() || 7137 TheCall->getArg(i)->isValueDependent()) 7138 continue; 7139 7140 Optional<llvm::APSInt> Result; 7141 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 7142 return ExprError(Diag(TheCall->getBeginLoc(), 7143 diag::err_shufflevector_nonconstant_argument) 7144 << TheCall->getArg(i)->getSourceRange()); 7145 7146 // Allow -1 which will be translated to undef in the IR. 7147 if (Result->isSigned() && Result->isAllOnes()) 7148 continue; 7149 7150 if (Result->getActiveBits() > 64 || 7151 Result->getZExtValue() >= numElements * 2) 7152 return ExprError(Diag(TheCall->getBeginLoc(), 7153 diag::err_shufflevector_argument_too_large) 7154 << TheCall->getArg(i)->getSourceRange()); 7155 } 7156 7157 SmallVector<Expr*, 32> exprs; 7158 7159 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 7160 exprs.push_back(TheCall->getArg(i)); 7161 TheCall->setArg(i, nullptr); 7162 } 7163 7164 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 7165 TheCall->getCallee()->getBeginLoc(), 7166 TheCall->getRParenLoc()); 7167 } 7168 7169 /// SemaConvertVectorExpr - Handle __builtin_convertvector 7170 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 7171 SourceLocation BuiltinLoc, 7172 SourceLocation RParenLoc) { 7173 ExprValueKind VK = VK_PRValue; 7174 ExprObjectKind OK = OK_Ordinary; 7175 QualType DstTy = TInfo->getType(); 7176 QualType SrcTy = E->getType(); 7177 7178 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 7179 return ExprError(Diag(BuiltinLoc, 7180 diag::err_convertvector_non_vector) 7181 << E->getSourceRange()); 7182 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 7183 return ExprError(Diag(BuiltinLoc, 7184 diag::err_convertvector_non_vector_type)); 7185 7186 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 7187 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 7188 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 7189 if (SrcElts != DstElts) 7190 return ExprError(Diag(BuiltinLoc, 7191 diag::err_convertvector_incompatible_vector) 7192 << E->getSourceRange()); 7193 } 7194 7195 return new (Context) 7196 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 7197 } 7198 7199 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 7200 // This is declared to take (const void*, ...) and can take two 7201 // optional constant int args. 7202 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 7203 unsigned NumArgs = TheCall->getNumArgs(); 7204 7205 if (NumArgs > 3) 7206 return Diag(TheCall->getEndLoc(), 7207 diag::err_typecheck_call_too_many_args_at_most) 7208 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 7209 7210 // Argument 0 is checked for us and the remaining arguments must be 7211 // constant integers. 7212 for (unsigned i = 1; i != NumArgs; ++i) 7213 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 7214 return true; 7215 7216 return false; 7217 } 7218 7219 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 7220 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 7221 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 7222 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 7223 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7224 if (checkArgCount(*this, TheCall, 1)) 7225 return true; 7226 Expr *Arg = TheCall->getArg(0); 7227 if (Arg->isInstantiationDependent()) 7228 return false; 7229 7230 QualType ArgTy = Arg->getType(); 7231 if (!ArgTy->hasFloatingRepresentation()) 7232 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 7233 << ArgTy; 7234 if (Arg->isLValue()) { 7235 ExprResult FirstArg = DefaultLvalueConversion(Arg); 7236 TheCall->setArg(0, FirstArg.get()); 7237 } 7238 TheCall->setType(TheCall->getArg(0)->getType()); 7239 return false; 7240 } 7241 7242 /// SemaBuiltinAssume - Handle __assume (MS Extension). 7243 // __assume does not evaluate its arguments, and should warn if its argument 7244 // has side effects. 7245 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 7246 Expr *Arg = TheCall->getArg(0); 7247 if (Arg->isInstantiationDependent()) return false; 7248 7249 if (Arg->HasSideEffects(Context)) 7250 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 7251 << Arg->getSourceRange() 7252 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 7253 7254 return false; 7255 } 7256 7257 /// Handle __builtin_alloca_with_align. This is declared 7258 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 7259 /// than 8. 7260 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 7261 // The alignment must be a constant integer. 7262 Expr *Arg = TheCall->getArg(1); 7263 7264 // We can't check the value of a dependent argument. 7265 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 7266 if (const auto *UE = 7267 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 7268 if (UE->getKind() == UETT_AlignOf || 7269 UE->getKind() == UETT_PreferredAlignOf) 7270 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 7271 << Arg->getSourceRange(); 7272 7273 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 7274 7275 if (!Result.isPowerOf2()) 7276 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 7277 << Arg->getSourceRange(); 7278 7279 if (Result < Context.getCharWidth()) 7280 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 7281 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 7282 7283 if (Result > std::numeric_limits<int32_t>::max()) 7284 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 7285 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 7286 } 7287 7288 return false; 7289 } 7290 7291 /// Handle __builtin_assume_aligned. This is declared 7292 /// as (const void*, size_t, ...) and can take one optional constant int arg. 7293 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 7294 unsigned NumArgs = TheCall->getNumArgs(); 7295 7296 if (NumArgs > 3) 7297 return Diag(TheCall->getEndLoc(), 7298 diag::err_typecheck_call_too_many_args_at_most) 7299 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 7300 7301 // The alignment must be a constant integer. 7302 Expr *Arg = TheCall->getArg(1); 7303 7304 // We can't check the value of a dependent argument. 7305 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 7306 llvm::APSInt Result; 7307 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7308 return true; 7309 7310 if (!Result.isPowerOf2()) 7311 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 7312 << Arg->getSourceRange(); 7313 7314 if (Result > Sema::MaximumAlignment) 7315 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 7316 << Arg->getSourceRange() << Sema::MaximumAlignment; 7317 } 7318 7319 if (NumArgs > 2) { 7320 ExprResult Arg(TheCall->getArg(2)); 7321 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 7322 Context.getSizeType(), false); 7323 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 7324 if (Arg.isInvalid()) return true; 7325 TheCall->setArg(2, Arg.get()); 7326 } 7327 7328 return false; 7329 } 7330 7331 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 7332 unsigned BuiltinID = 7333 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 7334 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 7335 7336 unsigned NumArgs = TheCall->getNumArgs(); 7337 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 7338 if (NumArgs < NumRequiredArgs) { 7339 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 7340 << 0 /* function call */ << NumRequiredArgs << NumArgs 7341 << TheCall->getSourceRange(); 7342 } 7343 if (NumArgs >= NumRequiredArgs + 0x100) { 7344 return Diag(TheCall->getEndLoc(), 7345 diag::err_typecheck_call_too_many_args_at_most) 7346 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 7347 << TheCall->getSourceRange(); 7348 } 7349 unsigned i = 0; 7350 7351 // For formatting call, check buffer arg. 7352 if (!IsSizeCall) { 7353 ExprResult Arg(TheCall->getArg(i)); 7354 InitializedEntity Entity = InitializedEntity::InitializeParameter( 7355 Context, Context.VoidPtrTy, false); 7356 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 7357 if (Arg.isInvalid()) 7358 return true; 7359 TheCall->setArg(i, Arg.get()); 7360 i++; 7361 } 7362 7363 // Check string literal arg. 7364 unsigned FormatIdx = i; 7365 { 7366 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 7367 if (Arg.isInvalid()) 7368 return true; 7369 TheCall->setArg(i, Arg.get()); 7370 i++; 7371 } 7372 7373 // Make sure variadic args are scalar. 7374 unsigned FirstDataArg = i; 7375 while (i < NumArgs) { 7376 ExprResult Arg = DefaultVariadicArgumentPromotion( 7377 TheCall->getArg(i), VariadicFunction, nullptr); 7378 if (Arg.isInvalid()) 7379 return true; 7380 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 7381 if (ArgSize.getQuantity() >= 0x100) { 7382 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 7383 << i << (int)ArgSize.getQuantity() << 0xff 7384 << TheCall->getSourceRange(); 7385 } 7386 TheCall->setArg(i, Arg.get()); 7387 i++; 7388 } 7389 7390 // Check formatting specifiers. NOTE: We're only doing this for the non-size 7391 // call to avoid duplicate diagnostics. 7392 if (!IsSizeCall) { 7393 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 7394 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 7395 bool Success = CheckFormatArguments( 7396 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 7397 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 7398 CheckedVarArgs); 7399 if (!Success) 7400 return true; 7401 } 7402 7403 if (IsSizeCall) { 7404 TheCall->setType(Context.getSizeType()); 7405 } else { 7406 TheCall->setType(Context.VoidPtrTy); 7407 } 7408 return false; 7409 } 7410 7411 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 7412 /// TheCall is a constant expression. 7413 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 7414 llvm::APSInt &Result) { 7415 Expr *Arg = TheCall->getArg(ArgNum); 7416 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 7417 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 7418 7419 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 7420 7421 Optional<llvm::APSInt> R; 7422 if (!(R = Arg->getIntegerConstantExpr(Context))) 7423 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 7424 << FDecl->getDeclName() << Arg->getSourceRange(); 7425 Result = *R; 7426 return false; 7427 } 7428 7429 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 7430 /// TheCall is a constant expression in the range [Low, High]. 7431 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 7432 int Low, int High, bool RangeIsError) { 7433 if (isConstantEvaluated()) 7434 return false; 7435 llvm::APSInt Result; 7436 7437 // We can't check the value of a dependent argument. 7438 Expr *Arg = TheCall->getArg(ArgNum); 7439 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7440 return false; 7441 7442 // Check constant-ness first. 7443 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7444 return true; 7445 7446 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 7447 if (RangeIsError) 7448 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 7449 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 7450 else 7451 // Defer the warning until we know if the code will be emitted so that 7452 // dead code can ignore this. 7453 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 7454 PDiag(diag::warn_argument_invalid_range) 7455 << toString(Result, 10) << Low << High 7456 << Arg->getSourceRange()); 7457 } 7458 7459 return false; 7460 } 7461 7462 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 7463 /// TheCall is a constant expression is a multiple of Num.. 7464 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 7465 unsigned Num) { 7466 llvm::APSInt Result; 7467 7468 // We can't check the value of a dependent argument. 7469 Expr *Arg = TheCall->getArg(ArgNum); 7470 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7471 return false; 7472 7473 // Check constant-ness first. 7474 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7475 return true; 7476 7477 if (Result.getSExtValue() % Num != 0) 7478 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 7479 << Num << Arg->getSourceRange(); 7480 7481 return false; 7482 } 7483 7484 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 7485 /// constant expression representing a power of 2. 7486 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 7487 llvm::APSInt Result; 7488 7489 // We can't check the value of a dependent argument. 7490 Expr *Arg = TheCall->getArg(ArgNum); 7491 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7492 return false; 7493 7494 // Check constant-ness first. 7495 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7496 return true; 7497 7498 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 7499 // and only if x is a power of 2. 7500 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 7501 return false; 7502 7503 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 7504 << Arg->getSourceRange(); 7505 } 7506 7507 static bool IsShiftedByte(llvm::APSInt Value) { 7508 if (Value.isNegative()) 7509 return false; 7510 7511 // Check if it's a shifted byte, by shifting it down 7512 while (true) { 7513 // If the value fits in the bottom byte, the check passes. 7514 if (Value < 0x100) 7515 return true; 7516 7517 // Otherwise, if the value has _any_ bits in the bottom byte, the check 7518 // fails. 7519 if ((Value & 0xFF) != 0) 7520 return false; 7521 7522 // If the bottom 8 bits are all 0, but something above that is nonzero, 7523 // then shifting the value right by 8 bits won't affect whether it's a 7524 // shifted byte or not. So do that, and go round again. 7525 Value >>= 8; 7526 } 7527 } 7528 7529 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 7530 /// a constant expression representing an arbitrary byte value shifted left by 7531 /// a multiple of 8 bits. 7532 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 7533 unsigned ArgBits) { 7534 llvm::APSInt Result; 7535 7536 // We can't check the value of a dependent argument. 7537 Expr *Arg = TheCall->getArg(ArgNum); 7538 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7539 return false; 7540 7541 // Check constant-ness first. 7542 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7543 return true; 7544 7545 // Truncate to the given size. 7546 Result = Result.getLoBits(ArgBits); 7547 Result.setIsUnsigned(true); 7548 7549 if (IsShiftedByte(Result)) 7550 return false; 7551 7552 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 7553 << Arg->getSourceRange(); 7554 } 7555 7556 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 7557 /// TheCall is a constant expression representing either a shifted byte value, 7558 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 7559 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 7560 /// Arm MVE intrinsics. 7561 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 7562 int ArgNum, 7563 unsigned ArgBits) { 7564 llvm::APSInt Result; 7565 7566 // We can't check the value of a dependent argument. 7567 Expr *Arg = TheCall->getArg(ArgNum); 7568 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7569 return false; 7570 7571 // Check constant-ness first. 7572 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7573 return true; 7574 7575 // Truncate to the given size. 7576 Result = Result.getLoBits(ArgBits); 7577 Result.setIsUnsigned(true); 7578 7579 // Check to see if it's in either of the required forms. 7580 if (IsShiftedByte(Result) || 7581 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 7582 return false; 7583 7584 return Diag(TheCall->getBeginLoc(), 7585 diag::err_argument_not_shifted_byte_or_xxff) 7586 << Arg->getSourceRange(); 7587 } 7588 7589 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 7590 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 7591 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 7592 if (checkArgCount(*this, TheCall, 2)) 7593 return true; 7594 Expr *Arg0 = TheCall->getArg(0); 7595 Expr *Arg1 = TheCall->getArg(1); 7596 7597 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7598 if (FirstArg.isInvalid()) 7599 return true; 7600 QualType FirstArgType = FirstArg.get()->getType(); 7601 if (!FirstArgType->isAnyPointerType()) 7602 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7603 << "first" << FirstArgType << Arg0->getSourceRange(); 7604 TheCall->setArg(0, FirstArg.get()); 7605 7606 ExprResult SecArg = DefaultLvalueConversion(Arg1); 7607 if (SecArg.isInvalid()) 7608 return true; 7609 QualType SecArgType = SecArg.get()->getType(); 7610 if (!SecArgType->isIntegerType()) 7611 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7612 << "second" << SecArgType << Arg1->getSourceRange(); 7613 7614 // Derive the return type from the pointer argument. 7615 TheCall->setType(FirstArgType); 7616 return false; 7617 } 7618 7619 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 7620 if (checkArgCount(*this, TheCall, 2)) 7621 return true; 7622 7623 Expr *Arg0 = TheCall->getArg(0); 7624 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7625 if (FirstArg.isInvalid()) 7626 return true; 7627 QualType FirstArgType = FirstArg.get()->getType(); 7628 if (!FirstArgType->isAnyPointerType()) 7629 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7630 << "first" << FirstArgType << Arg0->getSourceRange(); 7631 TheCall->setArg(0, FirstArg.get()); 7632 7633 // Derive the return type from the pointer argument. 7634 TheCall->setType(FirstArgType); 7635 7636 // Second arg must be an constant in range [0,15] 7637 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7638 } 7639 7640 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 7641 if (checkArgCount(*this, TheCall, 2)) 7642 return true; 7643 Expr *Arg0 = TheCall->getArg(0); 7644 Expr *Arg1 = TheCall->getArg(1); 7645 7646 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7647 if (FirstArg.isInvalid()) 7648 return true; 7649 QualType FirstArgType = FirstArg.get()->getType(); 7650 if (!FirstArgType->isAnyPointerType()) 7651 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7652 << "first" << FirstArgType << Arg0->getSourceRange(); 7653 7654 QualType SecArgType = Arg1->getType(); 7655 if (!SecArgType->isIntegerType()) 7656 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7657 << "second" << SecArgType << Arg1->getSourceRange(); 7658 TheCall->setType(Context.IntTy); 7659 return false; 7660 } 7661 7662 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7663 BuiltinID == AArch64::BI__builtin_arm_stg) { 7664 if (checkArgCount(*this, TheCall, 1)) 7665 return true; 7666 Expr *Arg0 = TheCall->getArg(0); 7667 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7668 if (FirstArg.isInvalid()) 7669 return true; 7670 7671 QualType FirstArgType = FirstArg.get()->getType(); 7672 if (!FirstArgType->isAnyPointerType()) 7673 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7674 << "first" << FirstArgType << Arg0->getSourceRange(); 7675 TheCall->setArg(0, FirstArg.get()); 7676 7677 // Derive the return type from the pointer argument. 7678 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 7679 TheCall->setType(FirstArgType); 7680 return false; 7681 } 7682 7683 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 7684 Expr *ArgA = TheCall->getArg(0); 7685 Expr *ArgB = TheCall->getArg(1); 7686 7687 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 7688 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 7689 7690 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 7691 return true; 7692 7693 QualType ArgTypeA = ArgExprA.get()->getType(); 7694 QualType ArgTypeB = ArgExprB.get()->getType(); 7695 7696 auto isNull = [&] (Expr *E) -> bool { 7697 return E->isNullPointerConstant( 7698 Context, Expr::NPC_ValueDependentIsNotNull); }; 7699 7700 // argument should be either a pointer or null 7701 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 7702 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7703 << "first" << ArgTypeA << ArgA->getSourceRange(); 7704 7705 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 7706 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7707 << "second" << ArgTypeB << ArgB->getSourceRange(); 7708 7709 // Ensure Pointee types are compatible 7710 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 7711 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 7712 QualType pointeeA = ArgTypeA->getPointeeType(); 7713 QualType pointeeB = ArgTypeB->getPointeeType(); 7714 if (!Context.typesAreCompatible( 7715 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 7716 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 7717 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 7718 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 7719 << ArgB->getSourceRange(); 7720 } 7721 } 7722 7723 // at least one argument should be pointer type 7724 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 7725 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 7726 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 7727 7728 if (isNull(ArgA)) // adopt type of the other pointer 7729 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 7730 7731 if (isNull(ArgB)) 7732 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 7733 7734 TheCall->setArg(0, ArgExprA.get()); 7735 TheCall->setArg(1, ArgExprB.get()); 7736 TheCall->setType(Context.LongLongTy); 7737 return false; 7738 } 7739 assert(false && "Unhandled ARM MTE intrinsic"); 7740 return true; 7741 } 7742 7743 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 7744 /// TheCall is an ARM/AArch64 special register string literal. 7745 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 7746 int ArgNum, unsigned ExpectedFieldNum, 7747 bool AllowName) { 7748 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 7749 BuiltinID == ARM::BI__builtin_arm_wsr64 || 7750 BuiltinID == ARM::BI__builtin_arm_rsr || 7751 BuiltinID == ARM::BI__builtin_arm_rsrp || 7752 BuiltinID == ARM::BI__builtin_arm_wsr || 7753 BuiltinID == ARM::BI__builtin_arm_wsrp; 7754 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 7755 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 7756 BuiltinID == AArch64::BI__builtin_arm_rsr || 7757 BuiltinID == AArch64::BI__builtin_arm_rsrp || 7758 BuiltinID == AArch64::BI__builtin_arm_wsr || 7759 BuiltinID == AArch64::BI__builtin_arm_wsrp; 7760 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 7761 7762 // We can't check the value of a dependent argument. 7763 Expr *Arg = TheCall->getArg(ArgNum); 7764 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7765 return false; 7766 7767 // Check if the argument is a string literal. 7768 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 7769 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 7770 << Arg->getSourceRange(); 7771 7772 // Check the type of special register given. 7773 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 7774 SmallVector<StringRef, 6> Fields; 7775 Reg.split(Fields, ":"); 7776 7777 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 7778 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7779 << Arg->getSourceRange(); 7780 7781 // If the string is the name of a register then we cannot check that it is 7782 // valid here but if the string is of one the forms described in ACLE then we 7783 // can check that the supplied fields are integers and within the valid 7784 // ranges. 7785 if (Fields.size() > 1) { 7786 bool FiveFields = Fields.size() == 5; 7787 7788 bool ValidString = true; 7789 if (IsARMBuiltin) { 7790 ValidString &= Fields[0].startswith_insensitive("cp") || 7791 Fields[0].startswith_insensitive("p"); 7792 if (ValidString) 7793 Fields[0] = Fields[0].drop_front( 7794 Fields[0].startswith_insensitive("cp") ? 2 : 1); 7795 7796 ValidString &= Fields[2].startswith_insensitive("c"); 7797 if (ValidString) 7798 Fields[2] = Fields[2].drop_front(1); 7799 7800 if (FiveFields) { 7801 ValidString &= Fields[3].startswith_insensitive("c"); 7802 if (ValidString) 7803 Fields[3] = Fields[3].drop_front(1); 7804 } 7805 } 7806 7807 SmallVector<int, 5> Ranges; 7808 if (FiveFields) 7809 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 7810 else 7811 Ranges.append({15, 7, 15}); 7812 7813 for (unsigned i=0; i<Fields.size(); ++i) { 7814 int IntField; 7815 ValidString &= !Fields[i].getAsInteger(10, IntField); 7816 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7817 } 7818 7819 if (!ValidString) 7820 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7821 << Arg->getSourceRange(); 7822 } else if (IsAArch64Builtin && Fields.size() == 1) { 7823 // If the register name is one of those that appear in the condition below 7824 // and the special register builtin being used is one of the write builtins, 7825 // then we require that the argument provided for writing to the register 7826 // is an integer constant expression. This is because it will be lowered to 7827 // an MSR (immediate) instruction, so we need to know the immediate at 7828 // compile time. 7829 if (TheCall->getNumArgs() != 2) 7830 return false; 7831 7832 std::string RegLower = Reg.lower(); 7833 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7834 RegLower != "pan" && RegLower != "uao") 7835 return false; 7836 7837 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7838 } 7839 7840 return false; 7841 } 7842 7843 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7844 /// Emit an error and return true on failure; return false on success. 7845 /// TypeStr is a string containing the type descriptor of the value returned by 7846 /// the builtin and the descriptors of the expected type of the arguments. 7847 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID, 7848 const char *TypeStr) { 7849 7850 assert((TypeStr[0] != '\0') && 7851 "Invalid types in PPC MMA builtin declaration"); 7852 7853 switch (BuiltinID) { 7854 default: 7855 // This function is called in CheckPPCBuiltinFunctionCall where the 7856 // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here 7857 // we are isolating the pair vector memop builtins that can be used with mma 7858 // off so the default case is every builtin that requires mma and paired 7859 // vector memops. 7860 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7861 diag::err_ppc_builtin_only_on_arch, "10") || 7862 SemaFeatureCheck(*this, TheCall, "mma", 7863 diag::err_ppc_builtin_only_on_arch, "10")) 7864 return true; 7865 break; 7866 case PPC::BI__builtin_vsx_lxvp: 7867 case PPC::BI__builtin_vsx_stxvp: 7868 case PPC::BI__builtin_vsx_assemble_pair: 7869 case PPC::BI__builtin_vsx_disassemble_pair: 7870 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7871 diag::err_ppc_builtin_only_on_arch, "10")) 7872 return true; 7873 break; 7874 } 7875 7876 unsigned Mask = 0; 7877 unsigned ArgNum = 0; 7878 7879 // The first type in TypeStr is the type of the value returned by the 7880 // builtin. So we first read that type and change the type of TheCall. 7881 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7882 TheCall->setType(type); 7883 7884 while (*TypeStr != '\0') { 7885 Mask = 0; 7886 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7887 if (ArgNum >= TheCall->getNumArgs()) { 7888 ArgNum++; 7889 break; 7890 } 7891 7892 Expr *Arg = TheCall->getArg(ArgNum); 7893 QualType PassedType = Arg->getType(); 7894 QualType StrippedRVType = PassedType.getCanonicalType(); 7895 7896 // Strip Restrict/Volatile qualifiers. 7897 if (StrippedRVType.isRestrictQualified() || 7898 StrippedRVType.isVolatileQualified()) 7899 StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType(); 7900 7901 // The only case where the argument type and expected type are allowed to 7902 // mismatch is if the argument type is a non-void pointer (or array) and 7903 // expected type is a void pointer. 7904 if (StrippedRVType != ExpectedType) 7905 if (!(ExpectedType->isVoidPointerType() && 7906 (StrippedRVType->isPointerType() || StrippedRVType->isArrayType()))) 7907 return Diag(Arg->getBeginLoc(), 7908 diag::err_typecheck_convert_incompatible) 7909 << PassedType << ExpectedType << 1 << 0 << 0; 7910 7911 // If the value of the Mask is not 0, we have a constraint in the size of 7912 // the integer argument so here we ensure the argument is a constant that 7913 // is in the valid range. 7914 if (Mask != 0 && 7915 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7916 return true; 7917 7918 ArgNum++; 7919 } 7920 7921 // In case we exited early from the previous loop, there are other types to 7922 // read from TypeStr. So we need to read them all to ensure we have the right 7923 // number of arguments in TheCall and if it is not the case, to display a 7924 // better error message. 7925 while (*TypeStr != '\0') { 7926 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7927 ArgNum++; 7928 } 7929 if (checkArgCount(*this, TheCall, ArgNum)) 7930 return true; 7931 7932 return false; 7933 } 7934 7935 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7936 /// This checks that the target supports __builtin_longjmp and 7937 /// that val is a constant 1. 7938 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7939 if (!Context.getTargetInfo().hasSjLjLowering()) 7940 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7941 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7942 7943 Expr *Arg = TheCall->getArg(1); 7944 llvm::APSInt Result; 7945 7946 // TODO: This is less than ideal. Overload this to take a value. 7947 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7948 return true; 7949 7950 if (Result != 1) 7951 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7952 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7953 7954 return false; 7955 } 7956 7957 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7958 /// This checks that the target supports __builtin_setjmp. 7959 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7960 if (!Context.getTargetInfo().hasSjLjLowering()) 7961 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7962 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7963 return false; 7964 } 7965 7966 namespace { 7967 7968 class UncoveredArgHandler { 7969 enum { Unknown = -1, AllCovered = -2 }; 7970 7971 signed FirstUncoveredArg = Unknown; 7972 SmallVector<const Expr *, 4> DiagnosticExprs; 7973 7974 public: 7975 UncoveredArgHandler() = default; 7976 7977 bool hasUncoveredArg() const { 7978 return (FirstUncoveredArg >= 0); 7979 } 7980 7981 unsigned getUncoveredArg() const { 7982 assert(hasUncoveredArg() && "no uncovered argument"); 7983 return FirstUncoveredArg; 7984 } 7985 7986 void setAllCovered() { 7987 // A string has been found with all arguments covered, so clear out 7988 // the diagnostics. 7989 DiagnosticExprs.clear(); 7990 FirstUncoveredArg = AllCovered; 7991 } 7992 7993 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7994 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7995 7996 // Don't update if a previous string covers all arguments. 7997 if (FirstUncoveredArg == AllCovered) 7998 return; 7999 8000 // UncoveredArgHandler tracks the highest uncovered argument index 8001 // and with it all the strings that match this index. 8002 if (NewFirstUncoveredArg == FirstUncoveredArg) 8003 DiagnosticExprs.push_back(StrExpr); 8004 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 8005 DiagnosticExprs.clear(); 8006 DiagnosticExprs.push_back(StrExpr); 8007 FirstUncoveredArg = NewFirstUncoveredArg; 8008 } 8009 } 8010 8011 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 8012 }; 8013 8014 enum StringLiteralCheckType { 8015 SLCT_NotALiteral, 8016 SLCT_UncheckedLiteral, 8017 SLCT_CheckedLiteral 8018 }; 8019 8020 } // namespace 8021 8022 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 8023 BinaryOperatorKind BinOpKind, 8024 bool AddendIsRight) { 8025 unsigned BitWidth = Offset.getBitWidth(); 8026 unsigned AddendBitWidth = Addend.getBitWidth(); 8027 // There might be negative interim results. 8028 if (Addend.isUnsigned()) { 8029 Addend = Addend.zext(++AddendBitWidth); 8030 Addend.setIsSigned(true); 8031 } 8032 // Adjust the bit width of the APSInts. 8033 if (AddendBitWidth > BitWidth) { 8034 Offset = Offset.sext(AddendBitWidth); 8035 BitWidth = AddendBitWidth; 8036 } else if (BitWidth > AddendBitWidth) { 8037 Addend = Addend.sext(BitWidth); 8038 } 8039 8040 bool Ov = false; 8041 llvm::APSInt ResOffset = Offset; 8042 if (BinOpKind == BO_Add) 8043 ResOffset = Offset.sadd_ov(Addend, Ov); 8044 else { 8045 assert(AddendIsRight && BinOpKind == BO_Sub && 8046 "operator must be add or sub with addend on the right"); 8047 ResOffset = Offset.ssub_ov(Addend, Ov); 8048 } 8049 8050 // We add an offset to a pointer here so we should support an offset as big as 8051 // possible. 8052 if (Ov) { 8053 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 8054 "index (intermediate) result too big"); 8055 Offset = Offset.sext(2 * BitWidth); 8056 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 8057 return; 8058 } 8059 8060 Offset = ResOffset; 8061 } 8062 8063 namespace { 8064 8065 // This is a wrapper class around StringLiteral to support offsetted string 8066 // literals as format strings. It takes the offset into account when returning 8067 // the string and its length or the source locations to display notes correctly. 8068 class FormatStringLiteral { 8069 const StringLiteral *FExpr; 8070 int64_t Offset; 8071 8072 public: 8073 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 8074 : FExpr(fexpr), Offset(Offset) {} 8075 8076 StringRef getString() const { 8077 return FExpr->getString().drop_front(Offset); 8078 } 8079 8080 unsigned getByteLength() const { 8081 return FExpr->getByteLength() - getCharByteWidth() * Offset; 8082 } 8083 8084 unsigned getLength() const { return FExpr->getLength() - Offset; } 8085 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 8086 8087 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 8088 8089 QualType getType() const { return FExpr->getType(); } 8090 8091 bool isAscii() const { return FExpr->isAscii(); } 8092 bool isWide() const { return FExpr->isWide(); } 8093 bool isUTF8() const { return FExpr->isUTF8(); } 8094 bool isUTF16() const { return FExpr->isUTF16(); } 8095 bool isUTF32() const { return FExpr->isUTF32(); } 8096 bool isPascal() const { return FExpr->isPascal(); } 8097 8098 SourceLocation getLocationOfByte( 8099 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 8100 const TargetInfo &Target, unsigned *StartToken = nullptr, 8101 unsigned *StartTokenByteOffset = nullptr) const { 8102 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 8103 StartToken, StartTokenByteOffset); 8104 } 8105 8106 SourceLocation getBeginLoc() const LLVM_READONLY { 8107 return FExpr->getBeginLoc().getLocWithOffset(Offset); 8108 } 8109 8110 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 8111 }; 8112 8113 } // namespace 8114 8115 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8116 const Expr *OrigFormatExpr, 8117 ArrayRef<const Expr *> Args, 8118 bool HasVAListArg, unsigned format_idx, 8119 unsigned firstDataArg, 8120 Sema::FormatStringType Type, 8121 bool inFunctionCall, 8122 Sema::VariadicCallType CallType, 8123 llvm::SmallBitVector &CheckedVarArgs, 8124 UncoveredArgHandler &UncoveredArg, 8125 bool IgnoreStringsWithoutSpecifiers); 8126 8127 // Determine if an expression is a string literal or constant string. 8128 // If this function returns false on the arguments to a function expecting a 8129 // format string, we will usually need to emit a warning. 8130 // True string literals are then checked by CheckFormatString. 8131 static StringLiteralCheckType 8132 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 8133 bool HasVAListArg, unsigned format_idx, 8134 unsigned firstDataArg, Sema::FormatStringType Type, 8135 Sema::VariadicCallType CallType, bool InFunctionCall, 8136 llvm::SmallBitVector &CheckedVarArgs, 8137 UncoveredArgHandler &UncoveredArg, 8138 llvm::APSInt Offset, 8139 bool IgnoreStringsWithoutSpecifiers = false) { 8140 if (S.isConstantEvaluated()) 8141 return SLCT_NotALiteral; 8142 tryAgain: 8143 assert(Offset.isSigned() && "invalid offset"); 8144 8145 if (E->isTypeDependent() || E->isValueDependent()) 8146 return SLCT_NotALiteral; 8147 8148 E = E->IgnoreParenCasts(); 8149 8150 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 8151 // Technically -Wformat-nonliteral does not warn about this case. 8152 // The behavior of printf and friends in this case is implementation 8153 // dependent. Ideally if the format string cannot be null then 8154 // it should have a 'nonnull' attribute in the function prototype. 8155 return SLCT_UncheckedLiteral; 8156 8157 switch (E->getStmtClass()) { 8158 case Stmt::BinaryConditionalOperatorClass: 8159 case Stmt::ConditionalOperatorClass: { 8160 // The expression is a literal if both sub-expressions were, and it was 8161 // completely checked only if both sub-expressions were checked. 8162 const AbstractConditionalOperator *C = 8163 cast<AbstractConditionalOperator>(E); 8164 8165 // Determine whether it is necessary to check both sub-expressions, for 8166 // example, because the condition expression is a constant that can be 8167 // evaluated at compile time. 8168 bool CheckLeft = true, CheckRight = true; 8169 8170 bool Cond; 8171 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 8172 S.isConstantEvaluated())) { 8173 if (Cond) 8174 CheckRight = false; 8175 else 8176 CheckLeft = false; 8177 } 8178 8179 // We need to maintain the offsets for the right and the left hand side 8180 // separately to check if every possible indexed expression is a valid 8181 // string literal. They might have different offsets for different string 8182 // literals in the end. 8183 StringLiteralCheckType Left; 8184 if (!CheckLeft) 8185 Left = SLCT_UncheckedLiteral; 8186 else { 8187 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 8188 HasVAListArg, format_idx, firstDataArg, 8189 Type, CallType, InFunctionCall, 8190 CheckedVarArgs, UncoveredArg, Offset, 8191 IgnoreStringsWithoutSpecifiers); 8192 if (Left == SLCT_NotALiteral || !CheckRight) { 8193 return Left; 8194 } 8195 } 8196 8197 StringLiteralCheckType Right = checkFormatStringExpr( 8198 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 8199 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8200 IgnoreStringsWithoutSpecifiers); 8201 8202 return (CheckLeft && Left < Right) ? Left : Right; 8203 } 8204 8205 case Stmt::ImplicitCastExprClass: 8206 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 8207 goto tryAgain; 8208 8209 case Stmt::OpaqueValueExprClass: 8210 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 8211 E = src; 8212 goto tryAgain; 8213 } 8214 return SLCT_NotALiteral; 8215 8216 case Stmt::PredefinedExprClass: 8217 // While __func__, etc., are technically not string literals, they 8218 // cannot contain format specifiers and thus are not a security 8219 // liability. 8220 return SLCT_UncheckedLiteral; 8221 8222 case Stmt::DeclRefExprClass: { 8223 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8224 8225 // As an exception, do not flag errors for variables binding to 8226 // const string literals. 8227 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 8228 bool isConstant = false; 8229 QualType T = DR->getType(); 8230 8231 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 8232 isConstant = AT->getElementType().isConstant(S.Context); 8233 } else if (const PointerType *PT = T->getAs<PointerType>()) { 8234 isConstant = T.isConstant(S.Context) && 8235 PT->getPointeeType().isConstant(S.Context); 8236 } else if (T->isObjCObjectPointerType()) { 8237 // In ObjC, there is usually no "const ObjectPointer" type, 8238 // so don't check if the pointee type is constant. 8239 isConstant = T.isConstant(S.Context); 8240 } 8241 8242 if (isConstant) { 8243 if (const Expr *Init = VD->getAnyInitializer()) { 8244 // Look through initializers like const char c[] = { "foo" } 8245 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 8246 if (InitList->isStringLiteralInit()) 8247 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 8248 } 8249 return checkFormatStringExpr(S, Init, Args, 8250 HasVAListArg, format_idx, 8251 firstDataArg, Type, CallType, 8252 /*InFunctionCall*/ false, CheckedVarArgs, 8253 UncoveredArg, Offset); 8254 } 8255 } 8256 8257 // For vprintf* functions (i.e., HasVAListArg==true), we add a 8258 // special check to see if the format string is a function parameter 8259 // of the function calling the printf function. If the function 8260 // has an attribute indicating it is a printf-like function, then we 8261 // should suppress warnings concerning non-literals being used in a call 8262 // to a vprintf function. For example: 8263 // 8264 // void 8265 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 8266 // va_list ap; 8267 // va_start(ap, fmt); 8268 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 8269 // ... 8270 // } 8271 if (HasVAListArg) { 8272 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 8273 if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) { 8274 int PVIndex = PV->getFunctionScopeIndex() + 1; 8275 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) { 8276 // adjust for implicit parameter 8277 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) 8278 if (MD->isInstance()) 8279 ++PVIndex; 8280 // We also check if the formats are compatible. 8281 // We can't pass a 'scanf' string to a 'printf' function. 8282 if (PVIndex == PVFormat->getFormatIdx() && 8283 Type == S.GetFormatStringType(PVFormat)) 8284 return SLCT_UncheckedLiteral; 8285 } 8286 } 8287 } 8288 } 8289 } 8290 8291 return SLCT_NotALiteral; 8292 } 8293 8294 case Stmt::CallExprClass: 8295 case Stmt::CXXMemberCallExprClass: { 8296 const CallExpr *CE = cast<CallExpr>(E); 8297 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 8298 bool IsFirst = true; 8299 StringLiteralCheckType CommonResult; 8300 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 8301 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 8302 StringLiteralCheckType Result = checkFormatStringExpr( 8303 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 8304 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8305 IgnoreStringsWithoutSpecifiers); 8306 if (IsFirst) { 8307 CommonResult = Result; 8308 IsFirst = false; 8309 } 8310 } 8311 if (!IsFirst) 8312 return CommonResult; 8313 8314 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 8315 unsigned BuiltinID = FD->getBuiltinID(); 8316 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 8317 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 8318 const Expr *Arg = CE->getArg(0); 8319 return checkFormatStringExpr(S, Arg, Args, 8320 HasVAListArg, format_idx, 8321 firstDataArg, Type, CallType, 8322 InFunctionCall, CheckedVarArgs, 8323 UncoveredArg, Offset, 8324 IgnoreStringsWithoutSpecifiers); 8325 } 8326 } 8327 } 8328 8329 return SLCT_NotALiteral; 8330 } 8331 case Stmt::ObjCMessageExprClass: { 8332 const auto *ME = cast<ObjCMessageExpr>(E); 8333 if (const auto *MD = ME->getMethodDecl()) { 8334 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 8335 // As a special case heuristic, if we're using the method -[NSBundle 8336 // localizedStringForKey:value:table:], ignore any key strings that lack 8337 // format specifiers. The idea is that if the key doesn't have any 8338 // format specifiers then its probably just a key to map to the 8339 // localized strings. If it does have format specifiers though, then its 8340 // likely that the text of the key is the format string in the 8341 // programmer's language, and should be checked. 8342 const ObjCInterfaceDecl *IFace; 8343 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 8344 IFace->getIdentifier()->isStr("NSBundle") && 8345 MD->getSelector().isKeywordSelector( 8346 {"localizedStringForKey", "value", "table"})) { 8347 IgnoreStringsWithoutSpecifiers = true; 8348 } 8349 8350 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 8351 return checkFormatStringExpr( 8352 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 8353 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8354 IgnoreStringsWithoutSpecifiers); 8355 } 8356 } 8357 8358 return SLCT_NotALiteral; 8359 } 8360 case Stmt::ObjCStringLiteralClass: 8361 case Stmt::StringLiteralClass: { 8362 const StringLiteral *StrE = nullptr; 8363 8364 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 8365 StrE = ObjCFExpr->getString(); 8366 else 8367 StrE = cast<StringLiteral>(E); 8368 8369 if (StrE) { 8370 if (Offset.isNegative() || Offset > StrE->getLength()) { 8371 // TODO: It would be better to have an explicit warning for out of 8372 // bounds literals. 8373 return SLCT_NotALiteral; 8374 } 8375 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 8376 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 8377 firstDataArg, Type, InFunctionCall, CallType, 8378 CheckedVarArgs, UncoveredArg, 8379 IgnoreStringsWithoutSpecifiers); 8380 return SLCT_CheckedLiteral; 8381 } 8382 8383 return SLCT_NotALiteral; 8384 } 8385 case Stmt::BinaryOperatorClass: { 8386 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 8387 8388 // A string literal + an int offset is still a string literal. 8389 if (BinOp->isAdditiveOp()) { 8390 Expr::EvalResult LResult, RResult; 8391 8392 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 8393 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8394 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 8395 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8396 8397 if (LIsInt != RIsInt) { 8398 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 8399 8400 if (LIsInt) { 8401 if (BinOpKind == BO_Add) { 8402 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 8403 E = BinOp->getRHS(); 8404 goto tryAgain; 8405 } 8406 } else { 8407 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 8408 E = BinOp->getLHS(); 8409 goto tryAgain; 8410 } 8411 } 8412 } 8413 8414 return SLCT_NotALiteral; 8415 } 8416 case Stmt::UnaryOperatorClass: { 8417 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 8418 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 8419 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 8420 Expr::EvalResult IndexResult; 8421 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 8422 Expr::SE_NoSideEffects, 8423 S.isConstantEvaluated())) { 8424 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 8425 /*RHS is int*/ true); 8426 E = ASE->getBase(); 8427 goto tryAgain; 8428 } 8429 } 8430 8431 return SLCT_NotALiteral; 8432 } 8433 8434 default: 8435 return SLCT_NotALiteral; 8436 } 8437 } 8438 8439 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 8440 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 8441 .Case("scanf", FST_Scanf) 8442 .Cases("printf", "printf0", FST_Printf) 8443 .Cases("NSString", "CFString", FST_NSString) 8444 .Case("strftime", FST_Strftime) 8445 .Case("strfmon", FST_Strfmon) 8446 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 8447 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 8448 .Case("os_trace", FST_OSLog) 8449 .Case("os_log", FST_OSLog) 8450 .Default(FST_Unknown); 8451 } 8452 8453 /// CheckFormatArguments - Check calls to printf and scanf (and similar 8454 /// functions) for correct use of format strings. 8455 /// Returns true if a format string has been fully checked. 8456 bool Sema::CheckFormatArguments(const FormatAttr *Format, 8457 ArrayRef<const Expr *> Args, 8458 bool IsCXXMember, 8459 VariadicCallType CallType, 8460 SourceLocation Loc, SourceRange Range, 8461 llvm::SmallBitVector &CheckedVarArgs) { 8462 FormatStringInfo FSI; 8463 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 8464 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 8465 FSI.FirstDataArg, GetFormatStringType(Format), 8466 CallType, Loc, Range, CheckedVarArgs); 8467 return false; 8468 } 8469 8470 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 8471 bool HasVAListArg, unsigned format_idx, 8472 unsigned firstDataArg, FormatStringType Type, 8473 VariadicCallType CallType, 8474 SourceLocation Loc, SourceRange Range, 8475 llvm::SmallBitVector &CheckedVarArgs) { 8476 // CHECK: printf/scanf-like function is called with no format string. 8477 if (format_idx >= Args.size()) { 8478 Diag(Loc, diag::warn_missing_format_string) << Range; 8479 return false; 8480 } 8481 8482 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 8483 8484 // CHECK: format string is not a string literal. 8485 // 8486 // Dynamically generated format strings are difficult to 8487 // automatically vet at compile time. Requiring that format strings 8488 // are string literals: (1) permits the checking of format strings by 8489 // the compiler and thereby (2) can practically remove the source of 8490 // many format string exploits. 8491 8492 // Format string can be either ObjC string (e.g. @"%d") or 8493 // C string (e.g. "%d") 8494 // ObjC string uses the same format specifiers as C string, so we can use 8495 // the same format string checking logic for both ObjC and C strings. 8496 UncoveredArgHandler UncoveredArg; 8497 StringLiteralCheckType CT = 8498 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 8499 format_idx, firstDataArg, Type, CallType, 8500 /*IsFunctionCall*/ true, CheckedVarArgs, 8501 UncoveredArg, 8502 /*no string offset*/ llvm::APSInt(64, false) = 0); 8503 8504 // Generate a diagnostic where an uncovered argument is detected. 8505 if (UncoveredArg.hasUncoveredArg()) { 8506 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 8507 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 8508 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 8509 } 8510 8511 if (CT != SLCT_NotALiteral) 8512 // Literal format string found, check done! 8513 return CT == SLCT_CheckedLiteral; 8514 8515 // Strftime is particular as it always uses a single 'time' argument, 8516 // so it is safe to pass a non-literal string. 8517 if (Type == FST_Strftime) 8518 return false; 8519 8520 // Do not emit diag when the string param is a macro expansion and the 8521 // format is either NSString or CFString. This is a hack to prevent 8522 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 8523 // which are usually used in place of NS and CF string literals. 8524 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 8525 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 8526 return false; 8527 8528 // If there are no arguments specified, warn with -Wformat-security, otherwise 8529 // warn only with -Wformat-nonliteral. 8530 if (Args.size() == firstDataArg) { 8531 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 8532 << OrigFormatExpr->getSourceRange(); 8533 switch (Type) { 8534 default: 8535 break; 8536 case FST_Kprintf: 8537 case FST_FreeBSDKPrintf: 8538 case FST_Printf: 8539 Diag(FormatLoc, diag::note_format_security_fixit) 8540 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 8541 break; 8542 case FST_NSString: 8543 Diag(FormatLoc, diag::note_format_security_fixit) 8544 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 8545 break; 8546 } 8547 } else { 8548 Diag(FormatLoc, diag::warn_format_nonliteral) 8549 << OrigFormatExpr->getSourceRange(); 8550 } 8551 return false; 8552 } 8553 8554 namespace { 8555 8556 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 8557 protected: 8558 Sema &S; 8559 const FormatStringLiteral *FExpr; 8560 const Expr *OrigFormatExpr; 8561 const Sema::FormatStringType FSType; 8562 const unsigned FirstDataArg; 8563 const unsigned NumDataArgs; 8564 const char *Beg; // Start of format string. 8565 const bool HasVAListArg; 8566 ArrayRef<const Expr *> Args; 8567 unsigned FormatIdx; 8568 llvm::SmallBitVector CoveredArgs; 8569 bool usesPositionalArgs = false; 8570 bool atFirstArg = true; 8571 bool inFunctionCall; 8572 Sema::VariadicCallType CallType; 8573 llvm::SmallBitVector &CheckedVarArgs; 8574 UncoveredArgHandler &UncoveredArg; 8575 8576 public: 8577 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 8578 const Expr *origFormatExpr, 8579 const Sema::FormatStringType type, unsigned firstDataArg, 8580 unsigned numDataArgs, const char *beg, bool hasVAListArg, 8581 ArrayRef<const Expr *> Args, unsigned formatIdx, 8582 bool inFunctionCall, Sema::VariadicCallType callType, 8583 llvm::SmallBitVector &CheckedVarArgs, 8584 UncoveredArgHandler &UncoveredArg) 8585 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 8586 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 8587 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 8588 inFunctionCall(inFunctionCall), CallType(callType), 8589 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 8590 CoveredArgs.resize(numDataArgs); 8591 CoveredArgs.reset(); 8592 } 8593 8594 void DoneProcessing(); 8595 8596 void HandleIncompleteSpecifier(const char *startSpecifier, 8597 unsigned specifierLen) override; 8598 8599 void HandleInvalidLengthModifier( 8600 const analyze_format_string::FormatSpecifier &FS, 8601 const analyze_format_string::ConversionSpecifier &CS, 8602 const char *startSpecifier, unsigned specifierLen, 8603 unsigned DiagID); 8604 8605 void HandleNonStandardLengthModifier( 8606 const analyze_format_string::FormatSpecifier &FS, 8607 const char *startSpecifier, unsigned specifierLen); 8608 8609 void HandleNonStandardConversionSpecifier( 8610 const analyze_format_string::ConversionSpecifier &CS, 8611 const char *startSpecifier, unsigned specifierLen); 8612 8613 void HandlePosition(const char *startPos, unsigned posLen) override; 8614 8615 void HandleInvalidPosition(const char *startSpecifier, 8616 unsigned specifierLen, 8617 analyze_format_string::PositionContext p) override; 8618 8619 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 8620 8621 void HandleNullChar(const char *nullCharacter) override; 8622 8623 template <typename Range> 8624 static void 8625 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 8626 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 8627 bool IsStringLocation, Range StringRange, 8628 ArrayRef<FixItHint> Fixit = None); 8629 8630 protected: 8631 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 8632 const char *startSpec, 8633 unsigned specifierLen, 8634 const char *csStart, unsigned csLen); 8635 8636 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 8637 const char *startSpec, 8638 unsigned specifierLen); 8639 8640 SourceRange getFormatStringRange(); 8641 CharSourceRange getSpecifierRange(const char *startSpecifier, 8642 unsigned specifierLen); 8643 SourceLocation getLocationOfByte(const char *x); 8644 8645 const Expr *getDataArg(unsigned i) const; 8646 8647 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 8648 const analyze_format_string::ConversionSpecifier &CS, 8649 const char *startSpecifier, unsigned specifierLen, 8650 unsigned argIndex); 8651 8652 template <typename Range> 8653 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 8654 bool IsStringLocation, Range StringRange, 8655 ArrayRef<FixItHint> Fixit = None); 8656 }; 8657 8658 } // namespace 8659 8660 SourceRange CheckFormatHandler::getFormatStringRange() { 8661 return OrigFormatExpr->getSourceRange(); 8662 } 8663 8664 CharSourceRange CheckFormatHandler:: 8665 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 8666 SourceLocation Start = getLocationOfByte(startSpecifier); 8667 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 8668 8669 // Advance the end SourceLocation by one due to half-open ranges. 8670 End = End.getLocWithOffset(1); 8671 8672 return CharSourceRange::getCharRange(Start, End); 8673 } 8674 8675 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 8676 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 8677 S.getLangOpts(), S.Context.getTargetInfo()); 8678 } 8679 8680 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 8681 unsigned specifierLen){ 8682 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 8683 getLocationOfByte(startSpecifier), 8684 /*IsStringLocation*/true, 8685 getSpecifierRange(startSpecifier, specifierLen)); 8686 } 8687 8688 void CheckFormatHandler::HandleInvalidLengthModifier( 8689 const analyze_format_string::FormatSpecifier &FS, 8690 const analyze_format_string::ConversionSpecifier &CS, 8691 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 8692 using namespace analyze_format_string; 8693 8694 const LengthModifier &LM = FS.getLengthModifier(); 8695 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8696 8697 // See if we know how to fix this length modifier. 8698 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8699 if (FixedLM) { 8700 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8701 getLocationOfByte(LM.getStart()), 8702 /*IsStringLocation*/true, 8703 getSpecifierRange(startSpecifier, specifierLen)); 8704 8705 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8706 << FixedLM->toString() 8707 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8708 8709 } else { 8710 FixItHint Hint; 8711 if (DiagID == diag::warn_format_nonsensical_length) 8712 Hint = FixItHint::CreateRemoval(LMRange); 8713 8714 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8715 getLocationOfByte(LM.getStart()), 8716 /*IsStringLocation*/true, 8717 getSpecifierRange(startSpecifier, specifierLen), 8718 Hint); 8719 } 8720 } 8721 8722 void CheckFormatHandler::HandleNonStandardLengthModifier( 8723 const analyze_format_string::FormatSpecifier &FS, 8724 const char *startSpecifier, unsigned specifierLen) { 8725 using namespace analyze_format_string; 8726 8727 const LengthModifier &LM = FS.getLengthModifier(); 8728 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8729 8730 // See if we know how to fix this length modifier. 8731 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8732 if (FixedLM) { 8733 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8734 << LM.toString() << 0, 8735 getLocationOfByte(LM.getStart()), 8736 /*IsStringLocation*/true, 8737 getSpecifierRange(startSpecifier, specifierLen)); 8738 8739 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8740 << FixedLM->toString() 8741 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8742 8743 } else { 8744 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8745 << LM.toString() << 0, 8746 getLocationOfByte(LM.getStart()), 8747 /*IsStringLocation*/true, 8748 getSpecifierRange(startSpecifier, specifierLen)); 8749 } 8750 } 8751 8752 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 8753 const analyze_format_string::ConversionSpecifier &CS, 8754 const char *startSpecifier, unsigned specifierLen) { 8755 using namespace analyze_format_string; 8756 8757 // See if we know how to fix this conversion specifier. 8758 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 8759 if (FixedCS) { 8760 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8761 << CS.toString() << /*conversion specifier*/1, 8762 getLocationOfByte(CS.getStart()), 8763 /*IsStringLocation*/true, 8764 getSpecifierRange(startSpecifier, specifierLen)); 8765 8766 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 8767 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 8768 << FixedCS->toString() 8769 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 8770 } else { 8771 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8772 << CS.toString() << /*conversion specifier*/1, 8773 getLocationOfByte(CS.getStart()), 8774 /*IsStringLocation*/true, 8775 getSpecifierRange(startSpecifier, specifierLen)); 8776 } 8777 } 8778 8779 void CheckFormatHandler::HandlePosition(const char *startPos, 8780 unsigned posLen) { 8781 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 8782 getLocationOfByte(startPos), 8783 /*IsStringLocation*/true, 8784 getSpecifierRange(startPos, posLen)); 8785 } 8786 8787 void 8788 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 8789 analyze_format_string::PositionContext p) { 8790 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 8791 << (unsigned) p, 8792 getLocationOfByte(startPos), /*IsStringLocation*/true, 8793 getSpecifierRange(startPos, posLen)); 8794 } 8795 8796 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 8797 unsigned posLen) { 8798 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 8799 getLocationOfByte(startPos), 8800 /*IsStringLocation*/true, 8801 getSpecifierRange(startPos, posLen)); 8802 } 8803 8804 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 8805 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 8806 // The presence of a null character is likely an error. 8807 EmitFormatDiagnostic( 8808 S.PDiag(diag::warn_printf_format_string_contains_null_char), 8809 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 8810 getFormatStringRange()); 8811 } 8812 } 8813 8814 // Note that this may return NULL if there was an error parsing or building 8815 // one of the argument expressions. 8816 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 8817 return Args[FirstDataArg + i]; 8818 } 8819 8820 void CheckFormatHandler::DoneProcessing() { 8821 // Does the number of data arguments exceed the number of 8822 // format conversions in the format string? 8823 if (!HasVAListArg) { 8824 // Find any arguments that weren't covered. 8825 CoveredArgs.flip(); 8826 signed notCoveredArg = CoveredArgs.find_first(); 8827 if (notCoveredArg >= 0) { 8828 assert((unsigned)notCoveredArg < NumDataArgs); 8829 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 8830 } else { 8831 UncoveredArg.setAllCovered(); 8832 } 8833 } 8834 } 8835 8836 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 8837 const Expr *ArgExpr) { 8838 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 8839 "Invalid state"); 8840 8841 if (!ArgExpr) 8842 return; 8843 8844 SourceLocation Loc = ArgExpr->getBeginLoc(); 8845 8846 if (S.getSourceManager().isInSystemMacro(Loc)) 8847 return; 8848 8849 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8850 for (auto E : DiagnosticExprs) 8851 PDiag << E->getSourceRange(); 8852 8853 CheckFormatHandler::EmitFormatDiagnostic( 8854 S, IsFunctionCall, DiagnosticExprs[0], 8855 PDiag, Loc, /*IsStringLocation*/false, 8856 DiagnosticExprs[0]->getSourceRange()); 8857 } 8858 8859 bool 8860 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8861 SourceLocation Loc, 8862 const char *startSpec, 8863 unsigned specifierLen, 8864 const char *csStart, 8865 unsigned csLen) { 8866 bool keepGoing = true; 8867 if (argIndex < NumDataArgs) { 8868 // Consider the argument coverered, even though the specifier doesn't 8869 // make sense. 8870 CoveredArgs.set(argIndex); 8871 } 8872 else { 8873 // If argIndex exceeds the number of data arguments we 8874 // don't issue a warning because that is just a cascade of warnings (and 8875 // they may have intended '%%' anyway). We don't want to continue processing 8876 // the format string after this point, however, as we will like just get 8877 // gibberish when trying to match arguments. 8878 keepGoing = false; 8879 } 8880 8881 StringRef Specifier(csStart, csLen); 8882 8883 // If the specifier in non-printable, it could be the first byte of a UTF-8 8884 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8885 // hex value. 8886 std::string CodePointStr; 8887 if (!llvm::sys::locale::isPrint(*csStart)) { 8888 llvm::UTF32 CodePoint; 8889 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8890 const llvm::UTF8 *E = 8891 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8892 llvm::ConversionResult Result = 8893 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8894 8895 if (Result != llvm::conversionOK) { 8896 unsigned char FirstChar = *csStart; 8897 CodePoint = (llvm::UTF32)FirstChar; 8898 } 8899 8900 llvm::raw_string_ostream OS(CodePointStr); 8901 if (CodePoint < 256) 8902 OS << "\\x" << llvm::format("%02x", CodePoint); 8903 else if (CodePoint <= 0xFFFF) 8904 OS << "\\u" << llvm::format("%04x", CodePoint); 8905 else 8906 OS << "\\U" << llvm::format("%08x", CodePoint); 8907 OS.flush(); 8908 Specifier = CodePointStr; 8909 } 8910 8911 EmitFormatDiagnostic( 8912 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8913 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8914 8915 return keepGoing; 8916 } 8917 8918 void 8919 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8920 const char *startSpec, 8921 unsigned specifierLen) { 8922 EmitFormatDiagnostic( 8923 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8924 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8925 } 8926 8927 bool 8928 CheckFormatHandler::CheckNumArgs( 8929 const analyze_format_string::FormatSpecifier &FS, 8930 const analyze_format_string::ConversionSpecifier &CS, 8931 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8932 8933 if (argIndex >= NumDataArgs) { 8934 PartialDiagnostic PDiag = FS.usesPositionalArg() 8935 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8936 << (argIndex+1) << NumDataArgs) 8937 : S.PDiag(diag::warn_printf_insufficient_data_args); 8938 EmitFormatDiagnostic( 8939 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8940 getSpecifierRange(startSpecifier, specifierLen)); 8941 8942 // Since more arguments than conversion tokens are given, by extension 8943 // all arguments are covered, so mark this as so. 8944 UncoveredArg.setAllCovered(); 8945 return false; 8946 } 8947 return true; 8948 } 8949 8950 template<typename Range> 8951 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8952 SourceLocation Loc, 8953 bool IsStringLocation, 8954 Range StringRange, 8955 ArrayRef<FixItHint> FixIt) { 8956 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8957 Loc, IsStringLocation, StringRange, FixIt); 8958 } 8959 8960 /// If the format string is not within the function call, emit a note 8961 /// so that the function call and string are in diagnostic messages. 8962 /// 8963 /// \param InFunctionCall if true, the format string is within the function 8964 /// call and only one diagnostic message will be produced. Otherwise, an 8965 /// extra note will be emitted pointing to location of the format string. 8966 /// 8967 /// \param ArgumentExpr the expression that is passed as the format string 8968 /// argument in the function call. Used for getting locations when two 8969 /// diagnostics are emitted. 8970 /// 8971 /// \param PDiag the callee should already have provided any strings for the 8972 /// diagnostic message. This function only adds locations and fixits 8973 /// to diagnostics. 8974 /// 8975 /// \param Loc primary location for diagnostic. If two diagnostics are 8976 /// required, one will be at Loc and a new SourceLocation will be created for 8977 /// the other one. 8978 /// 8979 /// \param IsStringLocation if true, Loc points to the format string should be 8980 /// used for the note. Otherwise, Loc points to the argument list and will 8981 /// be used with PDiag. 8982 /// 8983 /// \param StringRange some or all of the string to highlight. This is 8984 /// templated so it can accept either a CharSourceRange or a SourceRange. 8985 /// 8986 /// \param FixIt optional fix it hint for the format string. 8987 template <typename Range> 8988 void CheckFormatHandler::EmitFormatDiagnostic( 8989 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8990 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8991 Range StringRange, ArrayRef<FixItHint> FixIt) { 8992 if (InFunctionCall) { 8993 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8994 D << StringRange; 8995 D << FixIt; 8996 } else { 8997 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8998 << ArgumentExpr->getSourceRange(); 8999 9000 const Sema::SemaDiagnosticBuilder &Note = 9001 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 9002 diag::note_format_string_defined); 9003 9004 Note << StringRange; 9005 Note << FixIt; 9006 } 9007 } 9008 9009 //===--- CHECK: Printf format string checking ------------------------------===// 9010 9011 namespace { 9012 9013 class CheckPrintfHandler : public CheckFormatHandler { 9014 public: 9015 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 9016 const Expr *origFormatExpr, 9017 const Sema::FormatStringType type, unsigned firstDataArg, 9018 unsigned numDataArgs, bool isObjC, const char *beg, 9019 bool hasVAListArg, ArrayRef<const Expr *> Args, 9020 unsigned formatIdx, bool inFunctionCall, 9021 Sema::VariadicCallType CallType, 9022 llvm::SmallBitVector &CheckedVarArgs, 9023 UncoveredArgHandler &UncoveredArg) 9024 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9025 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9026 inFunctionCall, CallType, CheckedVarArgs, 9027 UncoveredArg) {} 9028 9029 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 9030 9031 /// Returns true if '%@' specifiers are allowed in the format string. 9032 bool allowsObjCArg() const { 9033 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 9034 FSType == Sema::FST_OSTrace; 9035 } 9036 9037 bool HandleInvalidPrintfConversionSpecifier( 9038 const analyze_printf::PrintfSpecifier &FS, 9039 const char *startSpecifier, 9040 unsigned specifierLen) override; 9041 9042 void handleInvalidMaskType(StringRef MaskType) override; 9043 9044 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 9045 const char *startSpecifier, unsigned specifierLen, 9046 const TargetInfo &Target) override; 9047 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9048 const char *StartSpecifier, 9049 unsigned SpecifierLen, 9050 const Expr *E); 9051 9052 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 9053 const char *startSpecifier, unsigned specifierLen); 9054 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 9055 const analyze_printf::OptionalAmount &Amt, 9056 unsigned type, 9057 const char *startSpecifier, unsigned specifierLen); 9058 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 9059 const analyze_printf::OptionalFlag &flag, 9060 const char *startSpecifier, unsigned specifierLen); 9061 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 9062 const analyze_printf::OptionalFlag &ignoredFlag, 9063 const analyze_printf::OptionalFlag &flag, 9064 const char *startSpecifier, unsigned specifierLen); 9065 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 9066 const Expr *E); 9067 9068 void HandleEmptyObjCModifierFlag(const char *startFlag, 9069 unsigned flagLen) override; 9070 9071 void HandleInvalidObjCModifierFlag(const char *startFlag, 9072 unsigned flagLen) override; 9073 9074 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 9075 const char *flagsEnd, 9076 const char *conversionPosition) 9077 override; 9078 }; 9079 9080 } // namespace 9081 9082 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 9083 const analyze_printf::PrintfSpecifier &FS, 9084 const char *startSpecifier, 9085 unsigned specifierLen) { 9086 const analyze_printf::PrintfConversionSpecifier &CS = 9087 FS.getConversionSpecifier(); 9088 9089 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9090 getLocationOfByte(CS.getStart()), 9091 startSpecifier, specifierLen, 9092 CS.getStart(), CS.getLength()); 9093 } 9094 9095 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 9096 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 9097 } 9098 9099 bool CheckPrintfHandler::HandleAmount( 9100 const analyze_format_string::OptionalAmount &Amt, 9101 unsigned k, const char *startSpecifier, 9102 unsigned specifierLen) { 9103 if (Amt.hasDataArgument()) { 9104 if (!HasVAListArg) { 9105 unsigned argIndex = Amt.getArgIndex(); 9106 if (argIndex >= NumDataArgs) { 9107 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 9108 << k, 9109 getLocationOfByte(Amt.getStart()), 9110 /*IsStringLocation*/true, 9111 getSpecifierRange(startSpecifier, specifierLen)); 9112 // Don't do any more checking. We will just emit 9113 // spurious errors. 9114 return false; 9115 } 9116 9117 // Type check the data argument. It should be an 'int'. 9118 // Although not in conformance with C99, we also allow the argument to be 9119 // an 'unsigned int' as that is a reasonably safe case. GCC also 9120 // doesn't emit a warning for that case. 9121 CoveredArgs.set(argIndex); 9122 const Expr *Arg = getDataArg(argIndex); 9123 if (!Arg) 9124 return false; 9125 9126 QualType T = Arg->getType(); 9127 9128 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 9129 assert(AT.isValid()); 9130 9131 if (!AT.matchesType(S.Context, T)) { 9132 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 9133 << k << AT.getRepresentativeTypeName(S.Context) 9134 << T << Arg->getSourceRange(), 9135 getLocationOfByte(Amt.getStart()), 9136 /*IsStringLocation*/true, 9137 getSpecifierRange(startSpecifier, specifierLen)); 9138 // Don't do any more checking. We will just emit 9139 // spurious errors. 9140 return false; 9141 } 9142 } 9143 } 9144 return true; 9145 } 9146 9147 void CheckPrintfHandler::HandleInvalidAmount( 9148 const analyze_printf::PrintfSpecifier &FS, 9149 const analyze_printf::OptionalAmount &Amt, 9150 unsigned type, 9151 const char *startSpecifier, 9152 unsigned specifierLen) { 9153 const analyze_printf::PrintfConversionSpecifier &CS = 9154 FS.getConversionSpecifier(); 9155 9156 FixItHint fixit = 9157 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 9158 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 9159 Amt.getConstantLength())) 9160 : FixItHint(); 9161 9162 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 9163 << type << CS.toString(), 9164 getLocationOfByte(Amt.getStart()), 9165 /*IsStringLocation*/true, 9166 getSpecifierRange(startSpecifier, specifierLen), 9167 fixit); 9168 } 9169 9170 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 9171 const analyze_printf::OptionalFlag &flag, 9172 const char *startSpecifier, 9173 unsigned specifierLen) { 9174 // Warn about pointless flag with a fixit removal. 9175 const analyze_printf::PrintfConversionSpecifier &CS = 9176 FS.getConversionSpecifier(); 9177 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 9178 << flag.toString() << CS.toString(), 9179 getLocationOfByte(flag.getPosition()), 9180 /*IsStringLocation*/true, 9181 getSpecifierRange(startSpecifier, specifierLen), 9182 FixItHint::CreateRemoval( 9183 getSpecifierRange(flag.getPosition(), 1))); 9184 } 9185 9186 void CheckPrintfHandler::HandleIgnoredFlag( 9187 const analyze_printf::PrintfSpecifier &FS, 9188 const analyze_printf::OptionalFlag &ignoredFlag, 9189 const analyze_printf::OptionalFlag &flag, 9190 const char *startSpecifier, 9191 unsigned specifierLen) { 9192 // Warn about ignored flag with a fixit removal. 9193 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 9194 << ignoredFlag.toString() << flag.toString(), 9195 getLocationOfByte(ignoredFlag.getPosition()), 9196 /*IsStringLocation*/true, 9197 getSpecifierRange(startSpecifier, specifierLen), 9198 FixItHint::CreateRemoval( 9199 getSpecifierRange(ignoredFlag.getPosition(), 1))); 9200 } 9201 9202 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 9203 unsigned flagLen) { 9204 // Warn about an empty flag. 9205 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 9206 getLocationOfByte(startFlag), 9207 /*IsStringLocation*/true, 9208 getSpecifierRange(startFlag, flagLen)); 9209 } 9210 9211 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 9212 unsigned flagLen) { 9213 // Warn about an invalid flag. 9214 auto Range = getSpecifierRange(startFlag, flagLen); 9215 StringRef flag(startFlag, flagLen); 9216 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 9217 getLocationOfByte(startFlag), 9218 /*IsStringLocation*/true, 9219 Range, FixItHint::CreateRemoval(Range)); 9220 } 9221 9222 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 9223 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 9224 // Warn about using '[...]' without a '@' conversion. 9225 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 9226 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 9227 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 9228 getLocationOfByte(conversionPosition), 9229 /*IsStringLocation*/true, 9230 Range, FixItHint::CreateRemoval(Range)); 9231 } 9232 9233 // Determines if the specified is a C++ class or struct containing 9234 // a member with the specified name and kind (e.g. a CXXMethodDecl named 9235 // "c_str()"). 9236 template<typename MemberKind> 9237 static llvm::SmallPtrSet<MemberKind*, 1> 9238 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 9239 const RecordType *RT = Ty->getAs<RecordType>(); 9240 llvm::SmallPtrSet<MemberKind*, 1> Results; 9241 9242 if (!RT) 9243 return Results; 9244 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 9245 if (!RD || !RD->getDefinition()) 9246 return Results; 9247 9248 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 9249 Sema::LookupMemberName); 9250 R.suppressDiagnostics(); 9251 9252 // We just need to include all members of the right kind turned up by the 9253 // filter, at this point. 9254 if (S.LookupQualifiedName(R, RT->getDecl())) 9255 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 9256 NamedDecl *decl = (*I)->getUnderlyingDecl(); 9257 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 9258 Results.insert(FK); 9259 } 9260 return Results; 9261 } 9262 9263 /// Check if we could call '.c_str()' on an object. 9264 /// 9265 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 9266 /// allow the call, or if it would be ambiguous). 9267 bool Sema::hasCStrMethod(const Expr *E) { 9268 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 9269 9270 MethodSet Results = 9271 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 9272 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 9273 MI != ME; ++MI) 9274 if ((*MI)->getMinRequiredArguments() == 0) 9275 return true; 9276 return false; 9277 } 9278 9279 // Check if a (w)string was passed when a (w)char* was needed, and offer a 9280 // better diagnostic if so. AT is assumed to be valid. 9281 // Returns true when a c_str() conversion method is found. 9282 bool CheckPrintfHandler::checkForCStrMembers( 9283 const analyze_printf::ArgType &AT, const Expr *E) { 9284 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 9285 9286 MethodSet Results = 9287 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 9288 9289 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 9290 MI != ME; ++MI) { 9291 const CXXMethodDecl *Method = *MI; 9292 if (Method->getMinRequiredArguments() == 0 && 9293 AT.matchesType(S.Context, Method->getReturnType())) { 9294 // FIXME: Suggest parens if the expression needs them. 9295 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 9296 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 9297 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 9298 return true; 9299 } 9300 } 9301 9302 return false; 9303 } 9304 9305 bool CheckPrintfHandler::HandlePrintfSpecifier( 9306 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier, 9307 unsigned specifierLen, const TargetInfo &Target) { 9308 using namespace analyze_format_string; 9309 using namespace analyze_printf; 9310 9311 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 9312 9313 if (FS.consumesDataArgument()) { 9314 if (atFirstArg) { 9315 atFirstArg = false; 9316 usesPositionalArgs = FS.usesPositionalArg(); 9317 } 9318 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9319 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9320 startSpecifier, specifierLen); 9321 return false; 9322 } 9323 } 9324 9325 // First check if the field width, precision, and conversion specifier 9326 // have matching data arguments. 9327 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 9328 startSpecifier, specifierLen)) { 9329 return false; 9330 } 9331 9332 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 9333 startSpecifier, specifierLen)) { 9334 return false; 9335 } 9336 9337 if (!CS.consumesDataArgument()) { 9338 // FIXME: Technically specifying a precision or field width here 9339 // makes no sense. Worth issuing a warning at some point. 9340 return true; 9341 } 9342 9343 // Consume the argument. 9344 unsigned argIndex = FS.getArgIndex(); 9345 if (argIndex < NumDataArgs) { 9346 // The check to see if the argIndex is valid will come later. 9347 // We set the bit here because we may exit early from this 9348 // function if we encounter some other error. 9349 CoveredArgs.set(argIndex); 9350 } 9351 9352 // FreeBSD kernel extensions. 9353 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 9354 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 9355 // We need at least two arguments. 9356 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 9357 return false; 9358 9359 // Claim the second argument. 9360 CoveredArgs.set(argIndex + 1); 9361 9362 // Type check the first argument (int for %b, pointer for %D) 9363 const Expr *Ex = getDataArg(argIndex); 9364 const analyze_printf::ArgType &AT = 9365 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 9366 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 9367 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 9368 EmitFormatDiagnostic( 9369 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9370 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 9371 << false << Ex->getSourceRange(), 9372 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9373 getSpecifierRange(startSpecifier, specifierLen)); 9374 9375 // Type check the second argument (char * for both %b and %D) 9376 Ex = getDataArg(argIndex + 1); 9377 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 9378 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 9379 EmitFormatDiagnostic( 9380 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9381 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 9382 << false << Ex->getSourceRange(), 9383 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9384 getSpecifierRange(startSpecifier, specifierLen)); 9385 9386 return true; 9387 } 9388 9389 // Check for using an Objective-C specific conversion specifier 9390 // in a non-ObjC literal. 9391 if (!allowsObjCArg() && CS.isObjCArg()) { 9392 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9393 specifierLen); 9394 } 9395 9396 // %P can only be used with os_log. 9397 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 9398 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9399 specifierLen); 9400 } 9401 9402 // %n is not allowed with os_log. 9403 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 9404 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 9405 getLocationOfByte(CS.getStart()), 9406 /*IsStringLocation*/ false, 9407 getSpecifierRange(startSpecifier, specifierLen)); 9408 9409 return true; 9410 } 9411 9412 // Only scalars are allowed for os_trace. 9413 if (FSType == Sema::FST_OSTrace && 9414 (CS.getKind() == ConversionSpecifier::PArg || 9415 CS.getKind() == ConversionSpecifier::sArg || 9416 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 9417 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9418 specifierLen); 9419 } 9420 9421 // Check for use of public/private annotation outside of os_log(). 9422 if (FSType != Sema::FST_OSLog) { 9423 if (FS.isPublic().isSet()) { 9424 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9425 << "public", 9426 getLocationOfByte(FS.isPublic().getPosition()), 9427 /*IsStringLocation*/ false, 9428 getSpecifierRange(startSpecifier, specifierLen)); 9429 } 9430 if (FS.isPrivate().isSet()) { 9431 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9432 << "private", 9433 getLocationOfByte(FS.isPrivate().getPosition()), 9434 /*IsStringLocation*/ false, 9435 getSpecifierRange(startSpecifier, specifierLen)); 9436 } 9437 } 9438 9439 const llvm::Triple &Triple = Target.getTriple(); 9440 if (CS.getKind() == ConversionSpecifier::nArg && 9441 (Triple.isAndroid() || Triple.isOSFuchsia())) { 9442 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported), 9443 getLocationOfByte(CS.getStart()), 9444 /*IsStringLocation*/ false, 9445 getSpecifierRange(startSpecifier, specifierLen)); 9446 } 9447 9448 // Check for invalid use of field width 9449 if (!FS.hasValidFieldWidth()) { 9450 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 9451 startSpecifier, specifierLen); 9452 } 9453 9454 // Check for invalid use of precision 9455 if (!FS.hasValidPrecision()) { 9456 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 9457 startSpecifier, specifierLen); 9458 } 9459 9460 // Precision is mandatory for %P specifier. 9461 if (CS.getKind() == ConversionSpecifier::PArg && 9462 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 9463 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 9464 getLocationOfByte(startSpecifier), 9465 /*IsStringLocation*/ false, 9466 getSpecifierRange(startSpecifier, specifierLen)); 9467 } 9468 9469 // Check each flag does not conflict with any other component. 9470 if (!FS.hasValidThousandsGroupingPrefix()) 9471 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 9472 if (!FS.hasValidLeadingZeros()) 9473 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 9474 if (!FS.hasValidPlusPrefix()) 9475 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 9476 if (!FS.hasValidSpacePrefix()) 9477 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 9478 if (!FS.hasValidAlternativeForm()) 9479 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 9480 if (!FS.hasValidLeftJustified()) 9481 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 9482 9483 // Check that flags are not ignored by another flag 9484 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 9485 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 9486 startSpecifier, specifierLen); 9487 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 9488 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 9489 startSpecifier, specifierLen); 9490 9491 // Check the length modifier is valid with the given conversion specifier. 9492 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9493 S.getLangOpts())) 9494 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9495 diag::warn_format_nonsensical_length); 9496 else if (!FS.hasStandardLengthModifier()) 9497 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9498 else if (!FS.hasStandardLengthConversionCombination()) 9499 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9500 diag::warn_format_non_standard_conversion_spec); 9501 9502 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9503 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9504 9505 // The remaining checks depend on the data arguments. 9506 if (HasVAListArg) 9507 return true; 9508 9509 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9510 return false; 9511 9512 const Expr *Arg = getDataArg(argIndex); 9513 if (!Arg) 9514 return true; 9515 9516 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 9517 } 9518 9519 static bool requiresParensToAddCast(const Expr *E) { 9520 // FIXME: We should have a general way to reason about operator 9521 // precedence and whether parens are actually needed here. 9522 // Take care of a few common cases where they aren't. 9523 const Expr *Inside = E->IgnoreImpCasts(); 9524 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 9525 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 9526 9527 switch (Inside->getStmtClass()) { 9528 case Stmt::ArraySubscriptExprClass: 9529 case Stmt::CallExprClass: 9530 case Stmt::CharacterLiteralClass: 9531 case Stmt::CXXBoolLiteralExprClass: 9532 case Stmt::DeclRefExprClass: 9533 case Stmt::FloatingLiteralClass: 9534 case Stmt::IntegerLiteralClass: 9535 case Stmt::MemberExprClass: 9536 case Stmt::ObjCArrayLiteralClass: 9537 case Stmt::ObjCBoolLiteralExprClass: 9538 case Stmt::ObjCBoxedExprClass: 9539 case Stmt::ObjCDictionaryLiteralClass: 9540 case Stmt::ObjCEncodeExprClass: 9541 case Stmt::ObjCIvarRefExprClass: 9542 case Stmt::ObjCMessageExprClass: 9543 case Stmt::ObjCPropertyRefExprClass: 9544 case Stmt::ObjCStringLiteralClass: 9545 case Stmt::ObjCSubscriptRefExprClass: 9546 case Stmt::ParenExprClass: 9547 case Stmt::StringLiteralClass: 9548 case Stmt::UnaryOperatorClass: 9549 return false; 9550 default: 9551 return true; 9552 } 9553 } 9554 9555 static std::pair<QualType, StringRef> 9556 shouldNotPrintDirectly(const ASTContext &Context, 9557 QualType IntendedTy, 9558 const Expr *E) { 9559 // Use a 'while' to peel off layers of typedefs. 9560 QualType TyTy = IntendedTy; 9561 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 9562 StringRef Name = UserTy->getDecl()->getName(); 9563 QualType CastTy = llvm::StringSwitch<QualType>(Name) 9564 .Case("CFIndex", Context.getNSIntegerType()) 9565 .Case("NSInteger", Context.getNSIntegerType()) 9566 .Case("NSUInteger", Context.getNSUIntegerType()) 9567 .Case("SInt32", Context.IntTy) 9568 .Case("UInt32", Context.UnsignedIntTy) 9569 .Default(QualType()); 9570 9571 if (!CastTy.isNull()) 9572 return std::make_pair(CastTy, Name); 9573 9574 TyTy = UserTy->desugar(); 9575 } 9576 9577 // Strip parens if necessary. 9578 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 9579 return shouldNotPrintDirectly(Context, 9580 PE->getSubExpr()->getType(), 9581 PE->getSubExpr()); 9582 9583 // If this is a conditional expression, then its result type is constructed 9584 // via usual arithmetic conversions and thus there might be no necessary 9585 // typedef sugar there. Recurse to operands to check for NSInteger & 9586 // Co. usage condition. 9587 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9588 QualType TrueTy, FalseTy; 9589 StringRef TrueName, FalseName; 9590 9591 std::tie(TrueTy, TrueName) = 9592 shouldNotPrintDirectly(Context, 9593 CO->getTrueExpr()->getType(), 9594 CO->getTrueExpr()); 9595 std::tie(FalseTy, FalseName) = 9596 shouldNotPrintDirectly(Context, 9597 CO->getFalseExpr()->getType(), 9598 CO->getFalseExpr()); 9599 9600 if (TrueTy == FalseTy) 9601 return std::make_pair(TrueTy, TrueName); 9602 else if (TrueTy.isNull()) 9603 return std::make_pair(FalseTy, FalseName); 9604 else if (FalseTy.isNull()) 9605 return std::make_pair(TrueTy, TrueName); 9606 } 9607 9608 return std::make_pair(QualType(), StringRef()); 9609 } 9610 9611 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 9612 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 9613 /// type do not count. 9614 static bool 9615 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 9616 QualType From = ICE->getSubExpr()->getType(); 9617 QualType To = ICE->getType(); 9618 // It's an integer promotion if the destination type is the promoted 9619 // source type. 9620 if (ICE->getCastKind() == CK_IntegralCast && 9621 From->isPromotableIntegerType() && 9622 S.Context.getPromotedIntegerType(From) == To) 9623 return true; 9624 // Look through vector types, since we do default argument promotion for 9625 // those in OpenCL. 9626 if (const auto *VecTy = From->getAs<ExtVectorType>()) 9627 From = VecTy->getElementType(); 9628 if (const auto *VecTy = To->getAs<ExtVectorType>()) 9629 To = VecTy->getElementType(); 9630 // It's a floating promotion if the source type is a lower rank. 9631 return ICE->getCastKind() == CK_FloatingCast && 9632 S.Context.getFloatingTypeOrder(From, To) < 0; 9633 } 9634 9635 bool 9636 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9637 const char *StartSpecifier, 9638 unsigned SpecifierLen, 9639 const Expr *E) { 9640 using namespace analyze_format_string; 9641 using namespace analyze_printf; 9642 9643 // Now type check the data expression that matches the 9644 // format specifier. 9645 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 9646 if (!AT.isValid()) 9647 return true; 9648 9649 QualType ExprTy = E->getType(); 9650 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 9651 ExprTy = TET->getUnderlyingExpr()->getType(); 9652 } 9653 9654 // Diagnose attempts to print a boolean value as a character. Unlike other 9655 // -Wformat diagnostics, this is fine from a type perspective, but it still 9656 // doesn't make sense. 9657 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 9658 E->isKnownToHaveBooleanValue()) { 9659 const CharSourceRange &CSR = 9660 getSpecifierRange(StartSpecifier, SpecifierLen); 9661 SmallString<4> FSString; 9662 llvm::raw_svector_ostream os(FSString); 9663 FS.toString(os); 9664 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 9665 << FSString, 9666 E->getExprLoc(), false, CSR); 9667 return true; 9668 } 9669 9670 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 9671 if (Match == analyze_printf::ArgType::Match) 9672 return true; 9673 9674 // Look through argument promotions for our error message's reported type. 9675 // This includes the integral and floating promotions, but excludes array 9676 // and function pointer decay (seeing that an argument intended to be a 9677 // string has type 'char [6]' is probably more confusing than 'char *') and 9678 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 9679 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9680 if (isArithmeticArgumentPromotion(S, ICE)) { 9681 E = ICE->getSubExpr(); 9682 ExprTy = E->getType(); 9683 9684 // Check if we didn't match because of an implicit cast from a 'char' 9685 // or 'short' to an 'int'. This is done because printf is a varargs 9686 // function. 9687 if (ICE->getType() == S.Context.IntTy || 9688 ICE->getType() == S.Context.UnsignedIntTy) { 9689 // All further checking is done on the subexpression 9690 const analyze_printf::ArgType::MatchKind ImplicitMatch = 9691 AT.matchesType(S.Context, ExprTy); 9692 if (ImplicitMatch == analyze_printf::ArgType::Match) 9693 return true; 9694 if (ImplicitMatch == ArgType::NoMatchPedantic || 9695 ImplicitMatch == ArgType::NoMatchTypeConfusion) 9696 Match = ImplicitMatch; 9697 } 9698 } 9699 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 9700 // Special case for 'a', which has type 'int' in C. 9701 // Note, however, that we do /not/ want to treat multibyte constants like 9702 // 'MooV' as characters! This form is deprecated but still exists. In 9703 // addition, don't treat expressions as of type 'char' if one byte length 9704 // modifier is provided. 9705 if (ExprTy == S.Context.IntTy && 9706 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 9707 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 9708 ExprTy = S.Context.CharTy; 9709 } 9710 9711 // Look through enums to their underlying type. 9712 bool IsEnum = false; 9713 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 9714 ExprTy = EnumTy->getDecl()->getIntegerType(); 9715 IsEnum = true; 9716 } 9717 9718 // %C in an Objective-C context prints a unichar, not a wchar_t. 9719 // If the argument is an integer of some kind, believe the %C and suggest 9720 // a cast instead of changing the conversion specifier. 9721 QualType IntendedTy = ExprTy; 9722 if (isObjCContext() && 9723 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 9724 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 9725 !ExprTy->isCharType()) { 9726 // 'unichar' is defined as a typedef of unsigned short, but we should 9727 // prefer using the typedef if it is visible. 9728 IntendedTy = S.Context.UnsignedShortTy; 9729 9730 // While we are here, check if the value is an IntegerLiteral that happens 9731 // to be within the valid range. 9732 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 9733 const llvm::APInt &V = IL->getValue(); 9734 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 9735 return true; 9736 } 9737 9738 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 9739 Sema::LookupOrdinaryName); 9740 if (S.LookupName(Result, S.getCurScope())) { 9741 NamedDecl *ND = Result.getFoundDecl(); 9742 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 9743 if (TD->getUnderlyingType() == IntendedTy) 9744 IntendedTy = S.Context.getTypedefType(TD); 9745 } 9746 } 9747 } 9748 9749 // Special-case some of Darwin's platform-independence types by suggesting 9750 // casts to primitive types that are known to be large enough. 9751 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 9752 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 9753 QualType CastTy; 9754 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 9755 if (!CastTy.isNull()) { 9756 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 9757 // (long in ASTContext). Only complain to pedants. 9758 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 9759 (AT.isSizeT() || AT.isPtrdiffT()) && 9760 AT.matchesType(S.Context, CastTy)) 9761 Match = ArgType::NoMatchPedantic; 9762 IntendedTy = CastTy; 9763 ShouldNotPrintDirectly = true; 9764 } 9765 } 9766 9767 // We may be able to offer a FixItHint if it is a supported type. 9768 PrintfSpecifier fixedFS = FS; 9769 bool Success = 9770 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 9771 9772 if (Success) { 9773 // Get the fix string from the fixed format specifier 9774 SmallString<16> buf; 9775 llvm::raw_svector_ostream os(buf); 9776 fixedFS.toString(os); 9777 9778 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 9779 9780 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 9781 unsigned Diag; 9782 switch (Match) { 9783 case ArgType::Match: llvm_unreachable("expected non-matching"); 9784 case ArgType::NoMatchPedantic: 9785 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9786 break; 9787 case ArgType::NoMatchTypeConfusion: 9788 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9789 break; 9790 case ArgType::NoMatch: 9791 Diag = diag::warn_format_conversion_argument_type_mismatch; 9792 break; 9793 } 9794 9795 // In this case, the specifier is wrong and should be changed to match 9796 // the argument. 9797 EmitFormatDiagnostic(S.PDiag(Diag) 9798 << AT.getRepresentativeTypeName(S.Context) 9799 << IntendedTy << IsEnum << E->getSourceRange(), 9800 E->getBeginLoc(), 9801 /*IsStringLocation*/ false, SpecRange, 9802 FixItHint::CreateReplacement(SpecRange, os.str())); 9803 } else { 9804 // The canonical type for formatting this value is different from the 9805 // actual type of the expression. (This occurs, for example, with Darwin's 9806 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 9807 // should be printed as 'long' for 64-bit compatibility.) 9808 // Rather than emitting a normal format/argument mismatch, we want to 9809 // add a cast to the recommended type (and correct the format string 9810 // if necessary). 9811 SmallString<16> CastBuf; 9812 llvm::raw_svector_ostream CastFix(CastBuf); 9813 CastFix << "("; 9814 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 9815 CastFix << ")"; 9816 9817 SmallVector<FixItHint,4> Hints; 9818 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 9819 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 9820 9821 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 9822 // If there's already a cast present, just replace it. 9823 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 9824 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 9825 9826 } else if (!requiresParensToAddCast(E)) { 9827 // If the expression has high enough precedence, 9828 // just write the C-style cast. 9829 Hints.push_back( 9830 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9831 } else { 9832 // Otherwise, add parens around the expression as well as the cast. 9833 CastFix << "("; 9834 Hints.push_back( 9835 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9836 9837 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 9838 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 9839 } 9840 9841 if (ShouldNotPrintDirectly) { 9842 // The expression has a type that should not be printed directly. 9843 // We extract the name from the typedef because we don't want to show 9844 // the underlying type in the diagnostic. 9845 StringRef Name; 9846 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 9847 Name = TypedefTy->getDecl()->getName(); 9848 else 9849 Name = CastTyName; 9850 unsigned Diag = Match == ArgType::NoMatchPedantic 9851 ? diag::warn_format_argument_needs_cast_pedantic 9852 : diag::warn_format_argument_needs_cast; 9853 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 9854 << E->getSourceRange(), 9855 E->getBeginLoc(), /*IsStringLocation=*/false, 9856 SpecRange, Hints); 9857 } else { 9858 // In this case, the expression could be printed using a different 9859 // specifier, but we've decided that the specifier is probably correct 9860 // and we should cast instead. Just use the normal warning message. 9861 EmitFormatDiagnostic( 9862 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9863 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9864 << E->getSourceRange(), 9865 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9866 } 9867 } 9868 } else { 9869 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9870 SpecifierLen); 9871 // Since the warning for passing non-POD types to variadic functions 9872 // was deferred until now, we emit a warning for non-POD 9873 // arguments here. 9874 switch (S.isValidVarArgType(ExprTy)) { 9875 case Sema::VAK_Valid: 9876 case Sema::VAK_ValidInCXX11: { 9877 unsigned Diag; 9878 switch (Match) { 9879 case ArgType::Match: llvm_unreachable("expected non-matching"); 9880 case ArgType::NoMatchPedantic: 9881 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9882 break; 9883 case ArgType::NoMatchTypeConfusion: 9884 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9885 break; 9886 case ArgType::NoMatch: 9887 Diag = diag::warn_format_conversion_argument_type_mismatch; 9888 break; 9889 } 9890 9891 EmitFormatDiagnostic( 9892 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9893 << IsEnum << CSR << E->getSourceRange(), 9894 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9895 break; 9896 } 9897 case Sema::VAK_Undefined: 9898 case Sema::VAK_MSVCUndefined: 9899 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9900 << S.getLangOpts().CPlusPlus11 << ExprTy 9901 << CallType 9902 << AT.getRepresentativeTypeName(S.Context) << CSR 9903 << E->getSourceRange(), 9904 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9905 checkForCStrMembers(AT, E); 9906 break; 9907 9908 case Sema::VAK_Invalid: 9909 if (ExprTy->isObjCObjectType()) 9910 EmitFormatDiagnostic( 9911 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9912 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9913 << AT.getRepresentativeTypeName(S.Context) << CSR 9914 << E->getSourceRange(), 9915 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9916 else 9917 // FIXME: If this is an initializer list, suggest removing the braces 9918 // or inserting a cast to the target type. 9919 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9920 << isa<InitListExpr>(E) << ExprTy << CallType 9921 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9922 break; 9923 } 9924 9925 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9926 "format string specifier index out of range"); 9927 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9928 } 9929 9930 return true; 9931 } 9932 9933 //===--- CHECK: Scanf format string checking ------------------------------===// 9934 9935 namespace { 9936 9937 class CheckScanfHandler : public CheckFormatHandler { 9938 public: 9939 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9940 const Expr *origFormatExpr, Sema::FormatStringType type, 9941 unsigned firstDataArg, unsigned numDataArgs, 9942 const char *beg, bool hasVAListArg, 9943 ArrayRef<const Expr *> Args, unsigned formatIdx, 9944 bool inFunctionCall, Sema::VariadicCallType CallType, 9945 llvm::SmallBitVector &CheckedVarArgs, 9946 UncoveredArgHandler &UncoveredArg) 9947 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9948 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9949 inFunctionCall, CallType, CheckedVarArgs, 9950 UncoveredArg) {} 9951 9952 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9953 const char *startSpecifier, 9954 unsigned specifierLen) override; 9955 9956 bool HandleInvalidScanfConversionSpecifier( 9957 const analyze_scanf::ScanfSpecifier &FS, 9958 const char *startSpecifier, 9959 unsigned specifierLen) override; 9960 9961 void HandleIncompleteScanList(const char *start, const char *end) override; 9962 }; 9963 9964 } // namespace 9965 9966 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9967 const char *end) { 9968 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9969 getLocationOfByte(end), /*IsStringLocation*/true, 9970 getSpecifierRange(start, end - start)); 9971 } 9972 9973 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9974 const analyze_scanf::ScanfSpecifier &FS, 9975 const char *startSpecifier, 9976 unsigned specifierLen) { 9977 const analyze_scanf::ScanfConversionSpecifier &CS = 9978 FS.getConversionSpecifier(); 9979 9980 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9981 getLocationOfByte(CS.getStart()), 9982 startSpecifier, specifierLen, 9983 CS.getStart(), CS.getLength()); 9984 } 9985 9986 bool CheckScanfHandler::HandleScanfSpecifier( 9987 const analyze_scanf::ScanfSpecifier &FS, 9988 const char *startSpecifier, 9989 unsigned specifierLen) { 9990 using namespace analyze_scanf; 9991 using namespace analyze_format_string; 9992 9993 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9994 9995 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9996 // be used to decide if we are using positional arguments consistently. 9997 if (FS.consumesDataArgument()) { 9998 if (atFirstArg) { 9999 atFirstArg = false; 10000 usesPositionalArgs = FS.usesPositionalArg(); 10001 } 10002 else if (usesPositionalArgs != FS.usesPositionalArg()) { 10003 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 10004 startSpecifier, specifierLen); 10005 return false; 10006 } 10007 } 10008 10009 // Check if the field with is non-zero. 10010 const OptionalAmount &Amt = FS.getFieldWidth(); 10011 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 10012 if (Amt.getConstantAmount() == 0) { 10013 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 10014 Amt.getConstantLength()); 10015 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 10016 getLocationOfByte(Amt.getStart()), 10017 /*IsStringLocation*/true, R, 10018 FixItHint::CreateRemoval(R)); 10019 } 10020 } 10021 10022 if (!FS.consumesDataArgument()) { 10023 // FIXME: Technically specifying a precision or field width here 10024 // makes no sense. Worth issuing a warning at some point. 10025 return true; 10026 } 10027 10028 // Consume the argument. 10029 unsigned argIndex = FS.getArgIndex(); 10030 if (argIndex < NumDataArgs) { 10031 // The check to see if the argIndex is valid will come later. 10032 // We set the bit here because we may exit early from this 10033 // function if we encounter some other error. 10034 CoveredArgs.set(argIndex); 10035 } 10036 10037 // Check the length modifier is valid with the given conversion specifier. 10038 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 10039 S.getLangOpts())) 10040 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 10041 diag::warn_format_nonsensical_length); 10042 else if (!FS.hasStandardLengthModifier()) 10043 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 10044 else if (!FS.hasStandardLengthConversionCombination()) 10045 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 10046 diag::warn_format_non_standard_conversion_spec); 10047 10048 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 10049 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 10050 10051 // The remaining checks depend on the data arguments. 10052 if (HasVAListArg) 10053 return true; 10054 10055 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 10056 return false; 10057 10058 // Check that the argument type matches the format specifier. 10059 const Expr *Ex = getDataArg(argIndex); 10060 if (!Ex) 10061 return true; 10062 10063 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 10064 10065 if (!AT.isValid()) { 10066 return true; 10067 } 10068 10069 analyze_format_string::ArgType::MatchKind Match = 10070 AT.matchesType(S.Context, Ex->getType()); 10071 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 10072 if (Match == analyze_format_string::ArgType::Match) 10073 return true; 10074 10075 ScanfSpecifier fixedFS = FS; 10076 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 10077 S.getLangOpts(), S.Context); 10078 10079 unsigned Diag = 10080 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 10081 : diag::warn_format_conversion_argument_type_mismatch; 10082 10083 if (Success) { 10084 // Get the fix string from the fixed format specifier. 10085 SmallString<128> buf; 10086 llvm::raw_svector_ostream os(buf); 10087 fixedFS.toString(os); 10088 10089 EmitFormatDiagnostic( 10090 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 10091 << Ex->getType() << false << Ex->getSourceRange(), 10092 Ex->getBeginLoc(), 10093 /*IsStringLocation*/ false, 10094 getSpecifierRange(startSpecifier, specifierLen), 10095 FixItHint::CreateReplacement( 10096 getSpecifierRange(startSpecifier, specifierLen), os.str())); 10097 } else { 10098 EmitFormatDiagnostic(S.PDiag(Diag) 10099 << AT.getRepresentativeTypeName(S.Context) 10100 << Ex->getType() << false << Ex->getSourceRange(), 10101 Ex->getBeginLoc(), 10102 /*IsStringLocation*/ false, 10103 getSpecifierRange(startSpecifier, specifierLen)); 10104 } 10105 10106 return true; 10107 } 10108 10109 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 10110 const Expr *OrigFormatExpr, 10111 ArrayRef<const Expr *> Args, 10112 bool HasVAListArg, unsigned format_idx, 10113 unsigned firstDataArg, 10114 Sema::FormatStringType Type, 10115 bool inFunctionCall, 10116 Sema::VariadicCallType CallType, 10117 llvm::SmallBitVector &CheckedVarArgs, 10118 UncoveredArgHandler &UncoveredArg, 10119 bool IgnoreStringsWithoutSpecifiers) { 10120 // CHECK: is the format string a wide literal? 10121 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 10122 CheckFormatHandler::EmitFormatDiagnostic( 10123 S, inFunctionCall, Args[format_idx], 10124 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 10125 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 10126 return; 10127 } 10128 10129 // Str - The format string. NOTE: this is NOT null-terminated! 10130 StringRef StrRef = FExpr->getString(); 10131 const char *Str = StrRef.data(); 10132 // Account for cases where the string literal is truncated in a declaration. 10133 const ConstantArrayType *T = 10134 S.Context.getAsConstantArrayType(FExpr->getType()); 10135 assert(T && "String literal not of constant array type!"); 10136 size_t TypeSize = T->getSize().getZExtValue(); 10137 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 10138 const unsigned numDataArgs = Args.size() - firstDataArg; 10139 10140 if (IgnoreStringsWithoutSpecifiers && 10141 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 10142 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 10143 return; 10144 10145 // Emit a warning if the string literal is truncated and does not contain an 10146 // embedded null character. 10147 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) { 10148 CheckFormatHandler::EmitFormatDiagnostic( 10149 S, inFunctionCall, Args[format_idx], 10150 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 10151 FExpr->getBeginLoc(), 10152 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 10153 return; 10154 } 10155 10156 // CHECK: empty format string? 10157 if (StrLen == 0 && numDataArgs > 0) { 10158 CheckFormatHandler::EmitFormatDiagnostic( 10159 S, inFunctionCall, Args[format_idx], 10160 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 10161 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 10162 return; 10163 } 10164 10165 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 10166 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 10167 Type == Sema::FST_OSTrace) { 10168 CheckPrintfHandler H( 10169 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 10170 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 10171 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 10172 CheckedVarArgs, UncoveredArg); 10173 10174 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 10175 S.getLangOpts(), 10176 S.Context.getTargetInfo(), 10177 Type == Sema::FST_FreeBSDKPrintf)) 10178 H.DoneProcessing(); 10179 } else if (Type == Sema::FST_Scanf) { 10180 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 10181 numDataArgs, Str, HasVAListArg, Args, format_idx, 10182 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 10183 10184 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 10185 S.getLangOpts(), 10186 S.Context.getTargetInfo())) 10187 H.DoneProcessing(); 10188 } // TODO: handle other formats 10189 } 10190 10191 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 10192 // Str - The format string. NOTE: this is NOT null-terminated! 10193 StringRef StrRef = FExpr->getString(); 10194 const char *Str = StrRef.data(); 10195 // Account for cases where the string literal is truncated in a declaration. 10196 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 10197 assert(T && "String literal not of constant array type!"); 10198 size_t TypeSize = T->getSize().getZExtValue(); 10199 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 10200 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 10201 getLangOpts(), 10202 Context.getTargetInfo()); 10203 } 10204 10205 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 10206 10207 // Returns the related absolute value function that is larger, of 0 if one 10208 // does not exist. 10209 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 10210 switch (AbsFunction) { 10211 default: 10212 return 0; 10213 10214 case Builtin::BI__builtin_abs: 10215 return Builtin::BI__builtin_labs; 10216 case Builtin::BI__builtin_labs: 10217 return Builtin::BI__builtin_llabs; 10218 case Builtin::BI__builtin_llabs: 10219 return 0; 10220 10221 case Builtin::BI__builtin_fabsf: 10222 return Builtin::BI__builtin_fabs; 10223 case Builtin::BI__builtin_fabs: 10224 return Builtin::BI__builtin_fabsl; 10225 case Builtin::BI__builtin_fabsl: 10226 return 0; 10227 10228 case Builtin::BI__builtin_cabsf: 10229 return Builtin::BI__builtin_cabs; 10230 case Builtin::BI__builtin_cabs: 10231 return Builtin::BI__builtin_cabsl; 10232 case Builtin::BI__builtin_cabsl: 10233 return 0; 10234 10235 case Builtin::BIabs: 10236 return Builtin::BIlabs; 10237 case Builtin::BIlabs: 10238 return Builtin::BIllabs; 10239 case Builtin::BIllabs: 10240 return 0; 10241 10242 case Builtin::BIfabsf: 10243 return Builtin::BIfabs; 10244 case Builtin::BIfabs: 10245 return Builtin::BIfabsl; 10246 case Builtin::BIfabsl: 10247 return 0; 10248 10249 case Builtin::BIcabsf: 10250 return Builtin::BIcabs; 10251 case Builtin::BIcabs: 10252 return Builtin::BIcabsl; 10253 case Builtin::BIcabsl: 10254 return 0; 10255 } 10256 } 10257 10258 // Returns the argument type of the absolute value function. 10259 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 10260 unsigned AbsType) { 10261 if (AbsType == 0) 10262 return QualType(); 10263 10264 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 10265 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 10266 if (Error != ASTContext::GE_None) 10267 return QualType(); 10268 10269 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 10270 if (!FT) 10271 return QualType(); 10272 10273 if (FT->getNumParams() != 1) 10274 return QualType(); 10275 10276 return FT->getParamType(0); 10277 } 10278 10279 // Returns the best absolute value function, or zero, based on type and 10280 // current absolute value function. 10281 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 10282 unsigned AbsFunctionKind) { 10283 unsigned BestKind = 0; 10284 uint64_t ArgSize = Context.getTypeSize(ArgType); 10285 for (unsigned Kind = AbsFunctionKind; Kind != 0; 10286 Kind = getLargerAbsoluteValueFunction(Kind)) { 10287 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 10288 if (Context.getTypeSize(ParamType) >= ArgSize) { 10289 if (BestKind == 0) 10290 BestKind = Kind; 10291 else if (Context.hasSameType(ParamType, ArgType)) { 10292 BestKind = Kind; 10293 break; 10294 } 10295 } 10296 } 10297 return BestKind; 10298 } 10299 10300 enum AbsoluteValueKind { 10301 AVK_Integer, 10302 AVK_Floating, 10303 AVK_Complex 10304 }; 10305 10306 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 10307 if (T->isIntegralOrEnumerationType()) 10308 return AVK_Integer; 10309 if (T->isRealFloatingType()) 10310 return AVK_Floating; 10311 if (T->isAnyComplexType()) 10312 return AVK_Complex; 10313 10314 llvm_unreachable("Type not integer, floating, or complex"); 10315 } 10316 10317 // Changes the absolute value function to a different type. Preserves whether 10318 // the function is a builtin. 10319 static unsigned changeAbsFunction(unsigned AbsKind, 10320 AbsoluteValueKind ValueKind) { 10321 switch (ValueKind) { 10322 case AVK_Integer: 10323 switch (AbsKind) { 10324 default: 10325 return 0; 10326 case Builtin::BI__builtin_fabsf: 10327 case Builtin::BI__builtin_fabs: 10328 case Builtin::BI__builtin_fabsl: 10329 case Builtin::BI__builtin_cabsf: 10330 case Builtin::BI__builtin_cabs: 10331 case Builtin::BI__builtin_cabsl: 10332 return Builtin::BI__builtin_abs; 10333 case Builtin::BIfabsf: 10334 case Builtin::BIfabs: 10335 case Builtin::BIfabsl: 10336 case Builtin::BIcabsf: 10337 case Builtin::BIcabs: 10338 case Builtin::BIcabsl: 10339 return Builtin::BIabs; 10340 } 10341 case AVK_Floating: 10342 switch (AbsKind) { 10343 default: 10344 return 0; 10345 case Builtin::BI__builtin_abs: 10346 case Builtin::BI__builtin_labs: 10347 case Builtin::BI__builtin_llabs: 10348 case Builtin::BI__builtin_cabsf: 10349 case Builtin::BI__builtin_cabs: 10350 case Builtin::BI__builtin_cabsl: 10351 return Builtin::BI__builtin_fabsf; 10352 case Builtin::BIabs: 10353 case Builtin::BIlabs: 10354 case Builtin::BIllabs: 10355 case Builtin::BIcabsf: 10356 case Builtin::BIcabs: 10357 case Builtin::BIcabsl: 10358 return Builtin::BIfabsf; 10359 } 10360 case AVK_Complex: 10361 switch (AbsKind) { 10362 default: 10363 return 0; 10364 case Builtin::BI__builtin_abs: 10365 case Builtin::BI__builtin_labs: 10366 case Builtin::BI__builtin_llabs: 10367 case Builtin::BI__builtin_fabsf: 10368 case Builtin::BI__builtin_fabs: 10369 case Builtin::BI__builtin_fabsl: 10370 return Builtin::BI__builtin_cabsf; 10371 case Builtin::BIabs: 10372 case Builtin::BIlabs: 10373 case Builtin::BIllabs: 10374 case Builtin::BIfabsf: 10375 case Builtin::BIfabs: 10376 case Builtin::BIfabsl: 10377 return Builtin::BIcabsf; 10378 } 10379 } 10380 llvm_unreachable("Unable to convert function"); 10381 } 10382 10383 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 10384 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 10385 if (!FnInfo) 10386 return 0; 10387 10388 switch (FDecl->getBuiltinID()) { 10389 default: 10390 return 0; 10391 case Builtin::BI__builtin_abs: 10392 case Builtin::BI__builtin_fabs: 10393 case Builtin::BI__builtin_fabsf: 10394 case Builtin::BI__builtin_fabsl: 10395 case Builtin::BI__builtin_labs: 10396 case Builtin::BI__builtin_llabs: 10397 case Builtin::BI__builtin_cabs: 10398 case Builtin::BI__builtin_cabsf: 10399 case Builtin::BI__builtin_cabsl: 10400 case Builtin::BIabs: 10401 case Builtin::BIlabs: 10402 case Builtin::BIllabs: 10403 case Builtin::BIfabs: 10404 case Builtin::BIfabsf: 10405 case Builtin::BIfabsl: 10406 case Builtin::BIcabs: 10407 case Builtin::BIcabsf: 10408 case Builtin::BIcabsl: 10409 return FDecl->getBuiltinID(); 10410 } 10411 llvm_unreachable("Unknown Builtin type"); 10412 } 10413 10414 // If the replacement is valid, emit a note with replacement function. 10415 // Additionally, suggest including the proper header if not already included. 10416 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 10417 unsigned AbsKind, QualType ArgType) { 10418 bool EmitHeaderHint = true; 10419 const char *HeaderName = nullptr; 10420 const char *FunctionName = nullptr; 10421 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 10422 FunctionName = "std::abs"; 10423 if (ArgType->isIntegralOrEnumerationType()) { 10424 HeaderName = "cstdlib"; 10425 } else if (ArgType->isRealFloatingType()) { 10426 HeaderName = "cmath"; 10427 } else { 10428 llvm_unreachable("Invalid Type"); 10429 } 10430 10431 // Lookup all std::abs 10432 if (NamespaceDecl *Std = S.getStdNamespace()) { 10433 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 10434 R.suppressDiagnostics(); 10435 S.LookupQualifiedName(R, Std); 10436 10437 for (const auto *I : R) { 10438 const FunctionDecl *FDecl = nullptr; 10439 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 10440 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 10441 } else { 10442 FDecl = dyn_cast<FunctionDecl>(I); 10443 } 10444 if (!FDecl) 10445 continue; 10446 10447 // Found std::abs(), check that they are the right ones. 10448 if (FDecl->getNumParams() != 1) 10449 continue; 10450 10451 // Check that the parameter type can handle the argument. 10452 QualType ParamType = FDecl->getParamDecl(0)->getType(); 10453 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 10454 S.Context.getTypeSize(ArgType) <= 10455 S.Context.getTypeSize(ParamType)) { 10456 // Found a function, don't need the header hint. 10457 EmitHeaderHint = false; 10458 break; 10459 } 10460 } 10461 } 10462 } else { 10463 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 10464 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 10465 10466 if (HeaderName) { 10467 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 10468 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 10469 R.suppressDiagnostics(); 10470 S.LookupName(R, S.getCurScope()); 10471 10472 if (R.isSingleResult()) { 10473 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 10474 if (FD && FD->getBuiltinID() == AbsKind) { 10475 EmitHeaderHint = false; 10476 } else { 10477 return; 10478 } 10479 } else if (!R.empty()) { 10480 return; 10481 } 10482 } 10483 } 10484 10485 S.Diag(Loc, diag::note_replace_abs_function) 10486 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 10487 10488 if (!HeaderName) 10489 return; 10490 10491 if (!EmitHeaderHint) 10492 return; 10493 10494 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 10495 << FunctionName; 10496 } 10497 10498 template <std::size_t StrLen> 10499 static bool IsStdFunction(const FunctionDecl *FDecl, 10500 const char (&Str)[StrLen]) { 10501 if (!FDecl) 10502 return false; 10503 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 10504 return false; 10505 if (!FDecl->isInStdNamespace()) 10506 return false; 10507 10508 return true; 10509 } 10510 10511 // Warn when using the wrong abs() function. 10512 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 10513 const FunctionDecl *FDecl) { 10514 if (Call->getNumArgs() != 1) 10515 return; 10516 10517 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 10518 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 10519 if (AbsKind == 0 && !IsStdAbs) 10520 return; 10521 10522 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10523 QualType ParamType = Call->getArg(0)->getType(); 10524 10525 // Unsigned types cannot be negative. Suggest removing the absolute value 10526 // function call. 10527 if (ArgType->isUnsignedIntegerType()) { 10528 const char *FunctionName = 10529 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 10530 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 10531 Diag(Call->getExprLoc(), diag::note_remove_abs) 10532 << FunctionName 10533 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 10534 return; 10535 } 10536 10537 // Taking the absolute value of a pointer is very suspicious, they probably 10538 // wanted to index into an array, dereference a pointer, call a function, etc. 10539 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 10540 unsigned DiagType = 0; 10541 if (ArgType->isFunctionType()) 10542 DiagType = 1; 10543 else if (ArgType->isArrayType()) 10544 DiagType = 2; 10545 10546 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 10547 return; 10548 } 10549 10550 // std::abs has overloads which prevent most of the absolute value problems 10551 // from occurring. 10552 if (IsStdAbs) 10553 return; 10554 10555 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 10556 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 10557 10558 // The argument and parameter are the same kind. Check if they are the right 10559 // size. 10560 if (ArgValueKind == ParamValueKind) { 10561 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 10562 return; 10563 10564 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 10565 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 10566 << FDecl << ArgType << ParamType; 10567 10568 if (NewAbsKind == 0) 10569 return; 10570 10571 emitReplacement(*this, Call->getExprLoc(), 10572 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10573 return; 10574 } 10575 10576 // ArgValueKind != ParamValueKind 10577 // The wrong type of absolute value function was used. Attempt to find the 10578 // proper one. 10579 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 10580 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 10581 if (NewAbsKind == 0) 10582 return; 10583 10584 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 10585 << FDecl << ParamValueKind << ArgValueKind; 10586 10587 emitReplacement(*this, Call->getExprLoc(), 10588 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10589 } 10590 10591 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 10592 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 10593 const FunctionDecl *FDecl) { 10594 if (!Call || !FDecl) return; 10595 10596 // Ignore template specializations and macros. 10597 if (inTemplateInstantiation()) return; 10598 if (Call->getExprLoc().isMacroID()) return; 10599 10600 // Only care about the one template argument, two function parameter std::max 10601 if (Call->getNumArgs() != 2) return; 10602 if (!IsStdFunction(FDecl, "max")) return; 10603 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 10604 if (!ArgList) return; 10605 if (ArgList->size() != 1) return; 10606 10607 // Check that template type argument is unsigned integer. 10608 const auto& TA = ArgList->get(0); 10609 if (TA.getKind() != TemplateArgument::Type) return; 10610 QualType ArgType = TA.getAsType(); 10611 if (!ArgType->isUnsignedIntegerType()) return; 10612 10613 // See if either argument is a literal zero. 10614 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 10615 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 10616 if (!MTE) return false; 10617 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 10618 if (!Num) return false; 10619 if (Num->getValue() != 0) return false; 10620 return true; 10621 }; 10622 10623 const Expr *FirstArg = Call->getArg(0); 10624 const Expr *SecondArg = Call->getArg(1); 10625 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 10626 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 10627 10628 // Only warn when exactly one argument is zero. 10629 if (IsFirstArgZero == IsSecondArgZero) return; 10630 10631 SourceRange FirstRange = FirstArg->getSourceRange(); 10632 SourceRange SecondRange = SecondArg->getSourceRange(); 10633 10634 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 10635 10636 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 10637 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 10638 10639 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 10640 SourceRange RemovalRange; 10641 if (IsFirstArgZero) { 10642 RemovalRange = SourceRange(FirstRange.getBegin(), 10643 SecondRange.getBegin().getLocWithOffset(-1)); 10644 } else { 10645 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 10646 SecondRange.getEnd()); 10647 } 10648 10649 Diag(Call->getExprLoc(), diag::note_remove_max_call) 10650 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 10651 << FixItHint::CreateRemoval(RemovalRange); 10652 } 10653 10654 //===--- CHECK: Standard memory functions ---------------------------------===// 10655 10656 /// Takes the expression passed to the size_t parameter of functions 10657 /// such as memcmp, strncat, etc and warns if it's a comparison. 10658 /// 10659 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 10660 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 10661 IdentifierInfo *FnName, 10662 SourceLocation FnLoc, 10663 SourceLocation RParenLoc) { 10664 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 10665 if (!Size) 10666 return false; 10667 10668 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 10669 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 10670 return false; 10671 10672 SourceRange SizeRange = Size->getSourceRange(); 10673 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 10674 << SizeRange << FnName; 10675 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 10676 << FnName 10677 << FixItHint::CreateInsertion( 10678 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 10679 << FixItHint::CreateRemoval(RParenLoc); 10680 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 10681 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 10682 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 10683 ")"); 10684 10685 return true; 10686 } 10687 10688 /// Determine whether the given type is or contains a dynamic class type 10689 /// (e.g., whether it has a vtable). 10690 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 10691 bool &IsContained) { 10692 // Look through array types while ignoring qualifiers. 10693 const Type *Ty = T->getBaseElementTypeUnsafe(); 10694 IsContained = false; 10695 10696 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 10697 RD = RD ? RD->getDefinition() : nullptr; 10698 if (!RD || RD->isInvalidDecl()) 10699 return nullptr; 10700 10701 if (RD->isDynamicClass()) 10702 return RD; 10703 10704 // Check all the fields. If any bases were dynamic, the class is dynamic. 10705 // It's impossible for a class to transitively contain itself by value, so 10706 // infinite recursion is impossible. 10707 for (auto *FD : RD->fields()) { 10708 bool SubContained; 10709 if (const CXXRecordDecl *ContainedRD = 10710 getContainedDynamicClass(FD->getType(), SubContained)) { 10711 IsContained = true; 10712 return ContainedRD; 10713 } 10714 } 10715 10716 return nullptr; 10717 } 10718 10719 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 10720 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 10721 if (Unary->getKind() == UETT_SizeOf) 10722 return Unary; 10723 return nullptr; 10724 } 10725 10726 /// If E is a sizeof expression, returns its argument expression, 10727 /// otherwise returns NULL. 10728 static const Expr *getSizeOfExprArg(const Expr *E) { 10729 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10730 if (!SizeOf->isArgumentType()) 10731 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 10732 return nullptr; 10733 } 10734 10735 /// If E is a sizeof expression, returns its argument type. 10736 static QualType getSizeOfArgType(const Expr *E) { 10737 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10738 return SizeOf->getTypeOfArgument(); 10739 return QualType(); 10740 } 10741 10742 namespace { 10743 10744 struct SearchNonTrivialToInitializeField 10745 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 10746 using Super = 10747 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 10748 10749 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 10750 10751 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 10752 SourceLocation SL) { 10753 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10754 asDerived().visitArray(PDIK, AT, SL); 10755 return; 10756 } 10757 10758 Super::visitWithKind(PDIK, FT, SL); 10759 } 10760 10761 void visitARCStrong(QualType FT, SourceLocation SL) { 10762 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10763 } 10764 void visitARCWeak(QualType FT, SourceLocation SL) { 10765 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10766 } 10767 void visitStruct(QualType FT, SourceLocation SL) { 10768 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10769 visit(FD->getType(), FD->getLocation()); 10770 } 10771 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 10772 const ArrayType *AT, SourceLocation SL) { 10773 visit(getContext().getBaseElementType(AT), SL); 10774 } 10775 void visitTrivial(QualType FT, SourceLocation SL) {} 10776 10777 static void diag(QualType RT, const Expr *E, Sema &S) { 10778 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 10779 } 10780 10781 ASTContext &getContext() { return S.getASTContext(); } 10782 10783 const Expr *E; 10784 Sema &S; 10785 }; 10786 10787 struct SearchNonTrivialToCopyField 10788 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 10789 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 10790 10791 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 10792 10793 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 10794 SourceLocation SL) { 10795 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10796 asDerived().visitArray(PCK, AT, SL); 10797 return; 10798 } 10799 10800 Super::visitWithKind(PCK, FT, SL); 10801 } 10802 10803 void visitARCStrong(QualType FT, SourceLocation SL) { 10804 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10805 } 10806 void visitARCWeak(QualType FT, SourceLocation SL) { 10807 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10808 } 10809 void visitStruct(QualType FT, SourceLocation SL) { 10810 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10811 visit(FD->getType(), FD->getLocation()); 10812 } 10813 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 10814 SourceLocation SL) { 10815 visit(getContext().getBaseElementType(AT), SL); 10816 } 10817 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 10818 SourceLocation SL) {} 10819 void visitTrivial(QualType FT, SourceLocation SL) {} 10820 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 10821 10822 static void diag(QualType RT, const Expr *E, Sema &S) { 10823 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 10824 } 10825 10826 ASTContext &getContext() { return S.getASTContext(); } 10827 10828 const Expr *E; 10829 Sema &S; 10830 }; 10831 10832 } 10833 10834 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 10835 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 10836 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 10837 10838 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 10839 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 10840 return false; 10841 10842 return doesExprLikelyComputeSize(BO->getLHS()) || 10843 doesExprLikelyComputeSize(BO->getRHS()); 10844 } 10845 10846 return getAsSizeOfExpr(SizeofExpr) != nullptr; 10847 } 10848 10849 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 10850 /// 10851 /// \code 10852 /// #define MACRO 0 10853 /// foo(MACRO); 10854 /// foo(0); 10855 /// \endcode 10856 /// 10857 /// This should return true for the first call to foo, but not for the second 10858 /// (regardless of whether foo is a macro or function). 10859 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10860 SourceLocation CallLoc, 10861 SourceLocation ArgLoc) { 10862 if (!CallLoc.isMacroID()) 10863 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10864 10865 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10866 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10867 } 10868 10869 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10870 /// last two arguments transposed. 10871 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10872 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10873 return; 10874 10875 const Expr *SizeArg = 10876 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10877 10878 auto isLiteralZero = [](const Expr *E) { 10879 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10880 }; 10881 10882 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10883 SourceLocation CallLoc = Call->getRParenLoc(); 10884 SourceManager &SM = S.getSourceManager(); 10885 if (isLiteralZero(SizeArg) && 10886 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10887 10888 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10889 10890 // Some platforms #define bzero to __builtin_memset. See if this is the 10891 // case, and if so, emit a better diagnostic. 10892 if (BId == Builtin::BIbzero || 10893 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10894 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10895 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10896 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10897 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10898 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10899 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10900 } 10901 return; 10902 } 10903 10904 // If the second argument to a memset is a sizeof expression and the third 10905 // isn't, this is also likely an error. This should catch 10906 // 'memset(buf, sizeof(buf), 0xff)'. 10907 if (BId == Builtin::BImemset && 10908 doesExprLikelyComputeSize(Call->getArg(1)) && 10909 !doesExprLikelyComputeSize(Call->getArg(2))) { 10910 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10911 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10912 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10913 return; 10914 } 10915 } 10916 10917 /// Check for dangerous or invalid arguments to memset(). 10918 /// 10919 /// This issues warnings on known problematic, dangerous or unspecified 10920 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10921 /// function calls. 10922 /// 10923 /// \param Call The call expression to diagnose. 10924 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10925 unsigned BId, 10926 IdentifierInfo *FnName) { 10927 assert(BId != 0); 10928 10929 // It is possible to have a non-standard definition of memset. Validate 10930 // we have enough arguments, and if not, abort further checking. 10931 unsigned ExpectedNumArgs = 10932 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10933 if (Call->getNumArgs() < ExpectedNumArgs) 10934 return; 10935 10936 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10937 BId == Builtin::BIstrndup ? 1 : 2); 10938 unsigned LenArg = 10939 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10940 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10941 10942 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10943 Call->getBeginLoc(), Call->getRParenLoc())) 10944 return; 10945 10946 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10947 CheckMemaccessSize(*this, BId, Call); 10948 10949 // We have special checking when the length is a sizeof expression. 10950 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10951 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10952 llvm::FoldingSetNodeID SizeOfArgID; 10953 10954 // Although widely used, 'bzero' is not a standard function. Be more strict 10955 // with the argument types before allowing diagnostics and only allow the 10956 // form bzero(ptr, sizeof(...)). 10957 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10958 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10959 return; 10960 10961 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10962 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10963 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10964 10965 QualType DestTy = Dest->getType(); 10966 QualType PointeeTy; 10967 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10968 PointeeTy = DestPtrTy->getPointeeType(); 10969 10970 // Never warn about void type pointers. This can be used to suppress 10971 // false positives. 10972 if (PointeeTy->isVoidType()) 10973 continue; 10974 10975 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10976 // actually comparing the expressions for equality. Because computing the 10977 // expression IDs can be expensive, we only do this if the diagnostic is 10978 // enabled. 10979 if (SizeOfArg && 10980 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10981 SizeOfArg->getExprLoc())) { 10982 // We only compute IDs for expressions if the warning is enabled, and 10983 // cache the sizeof arg's ID. 10984 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10985 SizeOfArg->Profile(SizeOfArgID, Context, true); 10986 llvm::FoldingSetNodeID DestID; 10987 Dest->Profile(DestID, Context, true); 10988 if (DestID == SizeOfArgID) { 10989 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10990 // over sizeof(src) as well. 10991 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10992 StringRef ReadableName = FnName->getName(); 10993 10994 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10995 if (UnaryOp->getOpcode() == UO_AddrOf) 10996 ActionIdx = 1; // If its an address-of operator, just remove it. 10997 if (!PointeeTy->isIncompleteType() && 10998 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10999 ActionIdx = 2; // If the pointee's size is sizeof(char), 11000 // suggest an explicit length. 11001 11002 // If the function is defined as a builtin macro, do not show macro 11003 // expansion. 11004 SourceLocation SL = SizeOfArg->getExprLoc(); 11005 SourceRange DSR = Dest->getSourceRange(); 11006 SourceRange SSR = SizeOfArg->getSourceRange(); 11007 SourceManager &SM = getSourceManager(); 11008 11009 if (SM.isMacroArgExpansion(SL)) { 11010 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 11011 SL = SM.getSpellingLoc(SL); 11012 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 11013 SM.getSpellingLoc(DSR.getEnd())); 11014 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 11015 SM.getSpellingLoc(SSR.getEnd())); 11016 } 11017 11018 DiagRuntimeBehavior(SL, SizeOfArg, 11019 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 11020 << ReadableName 11021 << PointeeTy 11022 << DestTy 11023 << DSR 11024 << SSR); 11025 DiagRuntimeBehavior(SL, SizeOfArg, 11026 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 11027 << ActionIdx 11028 << SSR); 11029 11030 break; 11031 } 11032 } 11033 11034 // Also check for cases where the sizeof argument is the exact same 11035 // type as the memory argument, and where it points to a user-defined 11036 // record type. 11037 if (SizeOfArgTy != QualType()) { 11038 if (PointeeTy->isRecordType() && 11039 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 11040 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 11041 PDiag(diag::warn_sizeof_pointer_type_memaccess) 11042 << FnName << SizeOfArgTy << ArgIdx 11043 << PointeeTy << Dest->getSourceRange() 11044 << LenExpr->getSourceRange()); 11045 break; 11046 } 11047 } 11048 } else if (DestTy->isArrayType()) { 11049 PointeeTy = DestTy; 11050 } 11051 11052 if (PointeeTy == QualType()) 11053 continue; 11054 11055 // Always complain about dynamic classes. 11056 bool IsContained; 11057 if (const CXXRecordDecl *ContainedRD = 11058 getContainedDynamicClass(PointeeTy, IsContained)) { 11059 11060 unsigned OperationType = 0; 11061 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 11062 // "overwritten" if we're warning about the destination for any call 11063 // but memcmp; otherwise a verb appropriate to the call. 11064 if (ArgIdx != 0 || IsCmp) { 11065 if (BId == Builtin::BImemcpy) 11066 OperationType = 1; 11067 else if(BId == Builtin::BImemmove) 11068 OperationType = 2; 11069 else if (IsCmp) 11070 OperationType = 3; 11071 } 11072 11073 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 11074 PDiag(diag::warn_dyn_class_memaccess) 11075 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 11076 << IsContained << ContainedRD << OperationType 11077 << Call->getCallee()->getSourceRange()); 11078 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 11079 BId != Builtin::BImemset) 11080 DiagRuntimeBehavior( 11081 Dest->getExprLoc(), Dest, 11082 PDiag(diag::warn_arc_object_memaccess) 11083 << ArgIdx << FnName << PointeeTy 11084 << Call->getCallee()->getSourceRange()); 11085 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 11086 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 11087 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 11088 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 11089 PDiag(diag::warn_cstruct_memaccess) 11090 << ArgIdx << FnName << PointeeTy << 0); 11091 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 11092 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 11093 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 11094 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 11095 PDiag(diag::warn_cstruct_memaccess) 11096 << ArgIdx << FnName << PointeeTy << 1); 11097 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 11098 } else { 11099 continue; 11100 } 11101 } else 11102 continue; 11103 11104 DiagRuntimeBehavior( 11105 Dest->getExprLoc(), Dest, 11106 PDiag(diag::note_bad_memaccess_silence) 11107 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 11108 break; 11109 } 11110 } 11111 11112 // A little helper routine: ignore addition and subtraction of integer literals. 11113 // This intentionally does not ignore all integer constant expressions because 11114 // we don't want to remove sizeof(). 11115 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 11116 Ex = Ex->IgnoreParenCasts(); 11117 11118 while (true) { 11119 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 11120 if (!BO || !BO->isAdditiveOp()) 11121 break; 11122 11123 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 11124 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 11125 11126 if (isa<IntegerLiteral>(RHS)) 11127 Ex = LHS; 11128 else if (isa<IntegerLiteral>(LHS)) 11129 Ex = RHS; 11130 else 11131 break; 11132 } 11133 11134 return Ex; 11135 } 11136 11137 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 11138 ASTContext &Context) { 11139 // Only handle constant-sized or VLAs, but not flexible members. 11140 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 11141 // Only issue the FIXIT for arrays of size > 1. 11142 if (CAT->getSize().getSExtValue() <= 1) 11143 return false; 11144 } else if (!Ty->isVariableArrayType()) { 11145 return false; 11146 } 11147 return true; 11148 } 11149 11150 // Warn if the user has made the 'size' argument to strlcpy or strlcat 11151 // be the size of the source, instead of the destination. 11152 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 11153 IdentifierInfo *FnName) { 11154 11155 // Don't crash if the user has the wrong number of arguments 11156 unsigned NumArgs = Call->getNumArgs(); 11157 if ((NumArgs != 3) && (NumArgs != 4)) 11158 return; 11159 11160 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 11161 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 11162 const Expr *CompareWithSrc = nullptr; 11163 11164 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 11165 Call->getBeginLoc(), Call->getRParenLoc())) 11166 return; 11167 11168 // Look for 'strlcpy(dst, x, sizeof(x))' 11169 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 11170 CompareWithSrc = Ex; 11171 else { 11172 // Look for 'strlcpy(dst, x, strlen(x))' 11173 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 11174 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 11175 SizeCall->getNumArgs() == 1) 11176 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 11177 } 11178 } 11179 11180 if (!CompareWithSrc) 11181 return; 11182 11183 // Determine if the argument to sizeof/strlen is equal to the source 11184 // argument. In principle there's all kinds of things you could do 11185 // here, for instance creating an == expression and evaluating it with 11186 // EvaluateAsBooleanCondition, but this uses a more direct technique: 11187 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 11188 if (!SrcArgDRE) 11189 return; 11190 11191 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 11192 if (!CompareWithSrcDRE || 11193 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 11194 return; 11195 11196 const Expr *OriginalSizeArg = Call->getArg(2); 11197 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 11198 << OriginalSizeArg->getSourceRange() << FnName; 11199 11200 // Output a FIXIT hint if the destination is an array (rather than a 11201 // pointer to an array). This could be enhanced to handle some 11202 // pointers if we know the actual size, like if DstArg is 'array+2' 11203 // we could say 'sizeof(array)-2'. 11204 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 11205 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 11206 return; 11207 11208 SmallString<128> sizeString; 11209 llvm::raw_svector_ostream OS(sizeString); 11210 OS << "sizeof("; 11211 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11212 OS << ")"; 11213 11214 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 11215 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 11216 OS.str()); 11217 } 11218 11219 /// Check if two expressions refer to the same declaration. 11220 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 11221 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 11222 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 11223 return D1->getDecl() == D2->getDecl(); 11224 return false; 11225 } 11226 11227 static const Expr *getStrlenExprArg(const Expr *E) { 11228 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11229 const FunctionDecl *FD = CE->getDirectCallee(); 11230 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 11231 return nullptr; 11232 return CE->getArg(0)->IgnoreParenCasts(); 11233 } 11234 return nullptr; 11235 } 11236 11237 // Warn on anti-patterns as the 'size' argument to strncat. 11238 // The correct size argument should look like following: 11239 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 11240 void Sema::CheckStrncatArguments(const CallExpr *CE, 11241 IdentifierInfo *FnName) { 11242 // Don't crash if the user has the wrong number of arguments. 11243 if (CE->getNumArgs() < 3) 11244 return; 11245 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 11246 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 11247 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 11248 11249 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 11250 CE->getRParenLoc())) 11251 return; 11252 11253 // Identify common expressions, which are wrongly used as the size argument 11254 // to strncat and may lead to buffer overflows. 11255 unsigned PatternType = 0; 11256 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 11257 // - sizeof(dst) 11258 if (referToTheSameDecl(SizeOfArg, DstArg)) 11259 PatternType = 1; 11260 // - sizeof(src) 11261 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 11262 PatternType = 2; 11263 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 11264 if (BE->getOpcode() == BO_Sub) { 11265 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 11266 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 11267 // - sizeof(dst) - strlen(dst) 11268 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 11269 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 11270 PatternType = 1; 11271 // - sizeof(src) - (anything) 11272 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 11273 PatternType = 2; 11274 } 11275 } 11276 11277 if (PatternType == 0) 11278 return; 11279 11280 // Generate the diagnostic. 11281 SourceLocation SL = LenArg->getBeginLoc(); 11282 SourceRange SR = LenArg->getSourceRange(); 11283 SourceManager &SM = getSourceManager(); 11284 11285 // If the function is defined as a builtin macro, do not show macro expansion. 11286 if (SM.isMacroArgExpansion(SL)) { 11287 SL = SM.getSpellingLoc(SL); 11288 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 11289 SM.getSpellingLoc(SR.getEnd())); 11290 } 11291 11292 // Check if the destination is an array (rather than a pointer to an array). 11293 QualType DstTy = DstArg->getType(); 11294 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 11295 Context); 11296 if (!isKnownSizeArray) { 11297 if (PatternType == 1) 11298 Diag(SL, diag::warn_strncat_wrong_size) << SR; 11299 else 11300 Diag(SL, diag::warn_strncat_src_size) << SR; 11301 return; 11302 } 11303 11304 if (PatternType == 1) 11305 Diag(SL, diag::warn_strncat_large_size) << SR; 11306 else 11307 Diag(SL, diag::warn_strncat_src_size) << SR; 11308 11309 SmallString<128> sizeString; 11310 llvm::raw_svector_ostream OS(sizeString); 11311 OS << "sizeof("; 11312 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11313 OS << ") - "; 11314 OS << "strlen("; 11315 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11316 OS << ") - 1"; 11317 11318 Diag(SL, diag::note_strncat_wrong_size) 11319 << FixItHint::CreateReplacement(SR, OS.str()); 11320 } 11321 11322 namespace { 11323 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 11324 const UnaryOperator *UnaryExpr, const Decl *D) { 11325 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 11326 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 11327 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 11328 return; 11329 } 11330 } 11331 11332 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 11333 const UnaryOperator *UnaryExpr) { 11334 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 11335 const Decl *D = Lvalue->getDecl(); 11336 if (isa<DeclaratorDecl>(D)) 11337 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType()) 11338 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 11339 } 11340 11341 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 11342 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 11343 Lvalue->getMemberDecl()); 11344 } 11345 11346 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 11347 const UnaryOperator *UnaryExpr) { 11348 const auto *Lambda = dyn_cast<LambdaExpr>( 11349 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 11350 if (!Lambda) 11351 return; 11352 11353 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 11354 << CalleeName << 2 /*object: lambda expression*/; 11355 } 11356 11357 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 11358 const DeclRefExpr *Lvalue) { 11359 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 11360 if (Var == nullptr) 11361 return; 11362 11363 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 11364 << CalleeName << 0 /*object: */ << Var; 11365 } 11366 11367 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 11368 const CastExpr *Cast) { 11369 SmallString<128> SizeString; 11370 llvm::raw_svector_ostream OS(SizeString); 11371 11372 clang::CastKind Kind = Cast->getCastKind(); 11373 if (Kind == clang::CK_BitCast && 11374 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 11375 return; 11376 if (Kind == clang::CK_IntegralToPointer && 11377 !isa<IntegerLiteral>( 11378 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 11379 return; 11380 11381 switch (Cast->getCastKind()) { 11382 case clang::CK_BitCast: 11383 case clang::CK_IntegralToPointer: 11384 case clang::CK_FunctionToPointerDecay: 11385 OS << '\''; 11386 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 11387 OS << '\''; 11388 break; 11389 default: 11390 return; 11391 } 11392 11393 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 11394 << CalleeName << 0 /*object: */ << OS.str(); 11395 } 11396 } // namespace 11397 11398 /// Alerts the user that they are attempting to free a non-malloc'd object. 11399 void Sema::CheckFreeArguments(const CallExpr *E) { 11400 const std::string CalleeName = 11401 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 11402 11403 { // Prefer something that doesn't involve a cast to make things simpler. 11404 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 11405 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 11406 switch (UnaryExpr->getOpcode()) { 11407 case UnaryOperator::Opcode::UO_AddrOf: 11408 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 11409 case UnaryOperator::Opcode::UO_Plus: 11410 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 11411 default: 11412 break; 11413 } 11414 11415 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 11416 if (Lvalue->getType()->isArrayType()) 11417 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 11418 11419 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 11420 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 11421 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 11422 return; 11423 } 11424 11425 if (isa<BlockExpr>(Arg)) { 11426 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 11427 << CalleeName << 1 /*object: block*/; 11428 return; 11429 } 11430 } 11431 // Maybe the cast was important, check after the other cases. 11432 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 11433 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 11434 } 11435 11436 void 11437 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 11438 SourceLocation ReturnLoc, 11439 bool isObjCMethod, 11440 const AttrVec *Attrs, 11441 const FunctionDecl *FD) { 11442 // Check if the return value is null but should not be. 11443 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 11444 (!isObjCMethod && isNonNullType(Context, lhsType))) && 11445 CheckNonNullExpr(*this, RetValExp)) 11446 Diag(ReturnLoc, diag::warn_null_ret) 11447 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 11448 11449 // C++11 [basic.stc.dynamic.allocation]p4: 11450 // If an allocation function declared with a non-throwing 11451 // exception-specification fails to allocate storage, it shall return 11452 // a null pointer. Any other allocation function that fails to allocate 11453 // storage shall indicate failure only by throwing an exception [...] 11454 if (FD) { 11455 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 11456 if (Op == OO_New || Op == OO_Array_New) { 11457 const FunctionProtoType *Proto 11458 = FD->getType()->castAs<FunctionProtoType>(); 11459 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 11460 CheckNonNullExpr(*this, RetValExp)) 11461 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 11462 << FD << getLangOpts().CPlusPlus11; 11463 } 11464 } 11465 11466 // PPC MMA non-pointer types are not allowed as return type. Checking the type 11467 // here prevent the user from using a PPC MMA type as trailing return type. 11468 if (Context.getTargetInfo().getTriple().isPPC64()) 11469 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 11470 } 11471 11472 /// Check for comparisons of floating-point values using == and !=. Issue a 11473 /// warning if the comparison is not likely to do what the programmer intended. 11474 void Sema::CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS, 11475 BinaryOperatorKind Opcode) { 11476 // Match and capture subexpressions such as "(float) X == 0.1". 11477 FloatingLiteral *FPLiteral; 11478 CastExpr *FPCast; 11479 auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) { 11480 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens()); 11481 FPCast = dyn_cast<CastExpr>(R->IgnoreParens()); 11482 return FPLiteral && FPCast; 11483 }; 11484 11485 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) { 11486 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>(); 11487 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>(); 11488 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() && 11489 TargetTy->isFloatingPoint()) { 11490 bool Lossy; 11491 llvm::APFloat TargetC = FPLiteral->getValue(); 11492 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)), 11493 llvm::APFloat::rmNearestTiesToEven, &Lossy); 11494 if (Lossy) { 11495 // If the literal cannot be represented in the source type, then a 11496 // check for == is always false and check for != is always true. 11497 Diag(Loc, diag::warn_float_compare_literal) 11498 << (Opcode == BO_EQ) << QualType(SourceTy, 0) 11499 << LHS->getSourceRange() << RHS->getSourceRange(); 11500 return; 11501 } 11502 } 11503 } 11504 11505 // Match a more general floating-point equality comparison (-Wfloat-equal). 11506 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 11507 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 11508 11509 // Special case: check for x == x (which is OK). 11510 // Do not emit warnings for such cases. 11511 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 11512 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 11513 if (DRL->getDecl() == DRR->getDecl()) 11514 return; 11515 11516 // Special case: check for comparisons against literals that can be exactly 11517 // represented by APFloat. In such cases, do not emit a warning. This 11518 // is a heuristic: often comparison against such literals are used to 11519 // detect if a value in a variable has not changed. This clearly can 11520 // lead to false negatives. 11521 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 11522 if (FLL->isExact()) 11523 return; 11524 } else 11525 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 11526 if (FLR->isExact()) 11527 return; 11528 11529 // Check for comparisons with builtin types. 11530 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 11531 if (CL->getBuiltinCallee()) 11532 return; 11533 11534 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 11535 if (CR->getBuiltinCallee()) 11536 return; 11537 11538 // Emit the diagnostic. 11539 Diag(Loc, diag::warn_floatingpoint_eq) 11540 << LHS->getSourceRange() << RHS->getSourceRange(); 11541 } 11542 11543 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 11544 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 11545 11546 namespace { 11547 11548 /// Structure recording the 'active' range of an integer-valued 11549 /// expression. 11550 struct IntRange { 11551 /// The number of bits active in the int. Note that this includes exactly one 11552 /// sign bit if !NonNegative. 11553 unsigned Width; 11554 11555 /// True if the int is known not to have negative values. If so, all leading 11556 /// bits before Width are known zero, otherwise they are known to be the 11557 /// same as the MSB within Width. 11558 bool NonNegative; 11559 11560 IntRange(unsigned Width, bool NonNegative) 11561 : Width(Width), NonNegative(NonNegative) {} 11562 11563 /// Number of bits excluding the sign bit. 11564 unsigned valueBits() const { 11565 return NonNegative ? Width : Width - 1; 11566 } 11567 11568 /// Returns the range of the bool type. 11569 static IntRange forBoolType() { 11570 return IntRange(1, true); 11571 } 11572 11573 /// Returns the range of an opaque value of the given integral type. 11574 static IntRange forValueOfType(ASTContext &C, QualType T) { 11575 return forValueOfCanonicalType(C, 11576 T->getCanonicalTypeInternal().getTypePtr()); 11577 } 11578 11579 /// Returns the range of an opaque value of a canonical integral type. 11580 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 11581 assert(T->isCanonicalUnqualified()); 11582 11583 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11584 T = VT->getElementType().getTypePtr(); 11585 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11586 T = CT->getElementType().getTypePtr(); 11587 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11588 T = AT->getValueType().getTypePtr(); 11589 11590 if (!C.getLangOpts().CPlusPlus) { 11591 // For enum types in C code, use the underlying datatype. 11592 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11593 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 11594 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 11595 // For enum types in C++, use the known bit width of the enumerators. 11596 EnumDecl *Enum = ET->getDecl(); 11597 // In C++11, enums can have a fixed underlying type. Use this type to 11598 // compute the range. 11599 if (Enum->isFixed()) { 11600 return IntRange(C.getIntWidth(QualType(T, 0)), 11601 !ET->isSignedIntegerOrEnumerationType()); 11602 } 11603 11604 unsigned NumPositive = Enum->getNumPositiveBits(); 11605 unsigned NumNegative = Enum->getNumNegativeBits(); 11606 11607 if (NumNegative == 0) 11608 return IntRange(NumPositive, true/*NonNegative*/); 11609 else 11610 return IntRange(std::max(NumPositive + 1, NumNegative), 11611 false/*NonNegative*/); 11612 } 11613 11614 if (const auto *EIT = dyn_cast<BitIntType>(T)) 11615 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11616 11617 const BuiltinType *BT = cast<BuiltinType>(T); 11618 assert(BT->isInteger()); 11619 11620 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11621 } 11622 11623 /// Returns the "target" range of a canonical integral type, i.e. 11624 /// the range of values expressible in the type. 11625 /// 11626 /// This matches forValueOfCanonicalType except that enums have the 11627 /// full range of their type, not the range of their enumerators. 11628 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 11629 assert(T->isCanonicalUnqualified()); 11630 11631 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11632 T = VT->getElementType().getTypePtr(); 11633 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11634 T = CT->getElementType().getTypePtr(); 11635 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11636 T = AT->getValueType().getTypePtr(); 11637 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11638 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 11639 11640 if (const auto *EIT = dyn_cast<BitIntType>(T)) 11641 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11642 11643 const BuiltinType *BT = cast<BuiltinType>(T); 11644 assert(BT->isInteger()); 11645 11646 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11647 } 11648 11649 /// Returns the supremum of two ranges: i.e. their conservative merge. 11650 static IntRange join(IntRange L, IntRange R) { 11651 bool Unsigned = L.NonNegative && R.NonNegative; 11652 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 11653 L.NonNegative && R.NonNegative); 11654 } 11655 11656 /// Return the range of a bitwise-AND of the two ranges. 11657 static IntRange bit_and(IntRange L, IntRange R) { 11658 unsigned Bits = std::max(L.Width, R.Width); 11659 bool NonNegative = false; 11660 if (L.NonNegative) { 11661 Bits = std::min(Bits, L.Width); 11662 NonNegative = true; 11663 } 11664 if (R.NonNegative) { 11665 Bits = std::min(Bits, R.Width); 11666 NonNegative = true; 11667 } 11668 return IntRange(Bits, NonNegative); 11669 } 11670 11671 /// Return the range of a sum of the two ranges. 11672 static IntRange sum(IntRange L, IntRange R) { 11673 bool Unsigned = L.NonNegative && R.NonNegative; 11674 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 11675 Unsigned); 11676 } 11677 11678 /// Return the range of a difference of the two ranges. 11679 static IntRange difference(IntRange L, IntRange R) { 11680 // We need a 1-bit-wider range if: 11681 // 1) LHS can be negative: least value can be reduced. 11682 // 2) RHS can be negative: greatest value can be increased. 11683 bool CanWiden = !L.NonNegative || !R.NonNegative; 11684 bool Unsigned = L.NonNegative && R.Width == 0; 11685 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 11686 !Unsigned, 11687 Unsigned); 11688 } 11689 11690 /// Return the range of a product of the two ranges. 11691 static IntRange product(IntRange L, IntRange R) { 11692 // If both LHS and RHS can be negative, we can form 11693 // -2^L * -2^R = 2^(L + R) 11694 // which requires L + R + 1 value bits to represent. 11695 bool CanWiden = !L.NonNegative && !R.NonNegative; 11696 bool Unsigned = L.NonNegative && R.NonNegative; 11697 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 11698 Unsigned); 11699 } 11700 11701 /// Return the range of a remainder operation between the two ranges. 11702 static IntRange rem(IntRange L, IntRange R) { 11703 // The result of a remainder can't be larger than the result of 11704 // either side. The sign of the result is the sign of the LHS. 11705 bool Unsigned = L.NonNegative; 11706 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 11707 Unsigned); 11708 } 11709 }; 11710 11711 } // namespace 11712 11713 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 11714 unsigned MaxWidth) { 11715 if (value.isSigned() && value.isNegative()) 11716 return IntRange(value.getMinSignedBits(), false); 11717 11718 if (value.getBitWidth() > MaxWidth) 11719 value = value.trunc(MaxWidth); 11720 11721 // isNonNegative() just checks the sign bit without considering 11722 // signedness. 11723 return IntRange(value.getActiveBits(), true); 11724 } 11725 11726 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 11727 unsigned MaxWidth) { 11728 if (result.isInt()) 11729 return GetValueRange(C, result.getInt(), MaxWidth); 11730 11731 if (result.isVector()) { 11732 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 11733 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 11734 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 11735 R = IntRange::join(R, El); 11736 } 11737 return R; 11738 } 11739 11740 if (result.isComplexInt()) { 11741 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 11742 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 11743 return IntRange::join(R, I); 11744 } 11745 11746 // This can happen with lossless casts to intptr_t of "based" lvalues. 11747 // Assume it might use arbitrary bits. 11748 // FIXME: The only reason we need to pass the type in here is to get 11749 // the sign right on this one case. It would be nice if APValue 11750 // preserved this. 11751 assert(result.isLValue() || result.isAddrLabelDiff()); 11752 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 11753 } 11754 11755 static QualType GetExprType(const Expr *E) { 11756 QualType Ty = E->getType(); 11757 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 11758 Ty = AtomicRHS->getValueType(); 11759 return Ty; 11760 } 11761 11762 /// Pseudo-evaluate the given integer expression, estimating the 11763 /// range of values it might take. 11764 /// 11765 /// \param MaxWidth The width to which the value will be truncated. 11766 /// \param Approximate If \c true, return a likely range for the result: in 11767 /// particular, assume that arithmetic on narrower types doesn't leave 11768 /// those types. If \c false, return a range including all possible 11769 /// result values. 11770 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 11771 bool InConstantContext, bool Approximate) { 11772 E = E->IgnoreParens(); 11773 11774 // Try a full evaluation first. 11775 Expr::EvalResult result; 11776 if (E->EvaluateAsRValue(result, C, InConstantContext)) 11777 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 11778 11779 // I think we only want to look through implicit casts here; if the 11780 // user has an explicit widening cast, we should treat the value as 11781 // being of the new, wider type. 11782 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 11783 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 11784 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 11785 Approximate); 11786 11787 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 11788 11789 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 11790 CE->getCastKind() == CK_BooleanToSignedIntegral; 11791 11792 // Assume that non-integer casts can span the full range of the type. 11793 if (!isIntegerCast) 11794 return OutputTypeRange; 11795 11796 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 11797 std::min(MaxWidth, OutputTypeRange.Width), 11798 InConstantContext, Approximate); 11799 11800 // Bail out if the subexpr's range is as wide as the cast type. 11801 if (SubRange.Width >= OutputTypeRange.Width) 11802 return OutputTypeRange; 11803 11804 // Otherwise, we take the smaller width, and we're non-negative if 11805 // either the output type or the subexpr is. 11806 return IntRange(SubRange.Width, 11807 SubRange.NonNegative || OutputTypeRange.NonNegative); 11808 } 11809 11810 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11811 // If we can fold the condition, just take that operand. 11812 bool CondResult; 11813 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 11814 return GetExprRange(C, 11815 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 11816 MaxWidth, InConstantContext, Approximate); 11817 11818 // Otherwise, conservatively merge. 11819 // GetExprRange requires an integer expression, but a throw expression 11820 // results in a void type. 11821 Expr *E = CO->getTrueExpr(); 11822 IntRange L = E->getType()->isVoidType() 11823 ? IntRange{0, true} 11824 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11825 E = CO->getFalseExpr(); 11826 IntRange R = E->getType()->isVoidType() 11827 ? IntRange{0, true} 11828 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11829 return IntRange::join(L, R); 11830 } 11831 11832 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11833 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 11834 11835 switch (BO->getOpcode()) { 11836 case BO_Cmp: 11837 llvm_unreachable("builtin <=> should have class type"); 11838 11839 // Boolean-valued operations are single-bit and positive. 11840 case BO_LAnd: 11841 case BO_LOr: 11842 case BO_LT: 11843 case BO_GT: 11844 case BO_LE: 11845 case BO_GE: 11846 case BO_EQ: 11847 case BO_NE: 11848 return IntRange::forBoolType(); 11849 11850 // The type of the assignments is the type of the LHS, so the RHS 11851 // is not necessarily the same type. 11852 case BO_MulAssign: 11853 case BO_DivAssign: 11854 case BO_RemAssign: 11855 case BO_AddAssign: 11856 case BO_SubAssign: 11857 case BO_XorAssign: 11858 case BO_OrAssign: 11859 // TODO: bitfields? 11860 return IntRange::forValueOfType(C, GetExprType(E)); 11861 11862 // Simple assignments just pass through the RHS, which will have 11863 // been coerced to the LHS type. 11864 case BO_Assign: 11865 // TODO: bitfields? 11866 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11867 Approximate); 11868 11869 // Operations with opaque sources are black-listed. 11870 case BO_PtrMemD: 11871 case BO_PtrMemI: 11872 return IntRange::forValueOfType(C, GetExprType(E)); 11873 11874 // Bitwise-and uses the *infinum* of the two source ranges. 11875 case BO_And: 11876 case BO_AndAssign: 11877 Combine = IntRange::bit_and; 11878 break; 11879 11880 // Left shift gets black-listed based on a judgement call. 11881 case BO_Shl: 11882 // ...except that we want to treat '1 << (blah)' as logically 11883 // positive. It's an important idiom. 11884 if (IntegerLiteral *I 11885 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11886 if (I->getValue() == 1) { 11887 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11888 return IntRange(R.Width, /*NonNegative*/ true); 11889 } 11890 } 11891 LLVM_FALLTHROUGH; 11892 11893 case BO_ShlAssign: 11894 return IntRange::forValueOfType(C, GetExprType(E)); 11895 11896 // Right shift by a constant can narrow its left argument. 11897 case BO_Shr: 11898 case BO_ShrAssign: { 11899 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11900 Approximate); 11901 11902 // If the shift amount is a positive constant, drop the width by 11903 // that much. 11904 if (Optional<llvm::APSInt> shift = 11905 BO->getRHS()->getIntegerConstantExpr(C)) { 11906 if (shift->isNonNegative()) { 11907 unsigned zext = shift->getZExtValue(); 11908 if (zext >= L.Width) 11909 L.Width = (L.NonNegative ? 0 : 1); 11910 else 11911 L.Width -= zext; 11912 } 11913 } 11914 11915 return L; 11916 } 11917 11918 // Comma acts as its right operand. 11919 case BO_Comma: 11920 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11921 Approximate); 11922 11923 case BO_Add: 11924 if (!Approximate) 11925 Combine = IntRange::sum; 11926 break; 11927 11928 case BO_Sub: 11929 if (BO->getLHS()->getType()->isPointerType()) 11930 return IntRange::forValueOfType(C, GetExprType(E)); 11931 if (!Approximate) 11932 Combine = IntRange::difference; 11933 break; 11934 11935 case BO_Mul: 11936 if (!Approximate) 11937 Combine = IntRange::product; 11938 break; 11939 11940 // The width of a division result is mostly determined by the size 11941 // of the LHS. 11942 case BO_Div: { 11943 // Don't 'pre-truncate' the operands. 11944 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11945 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11946 Approximate); 11947 11948 // If the divisor is constant, use that. 11949 if (Optional<llvm::APSInt> divisor = 11950 BO->getRHS()->getIntegerConstantExpr(C)) { 11951 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11952 if (log2 >= L.Width) 11953 L.Width = (L.NonNegative ? 0 : 1); 11954 else 11955 L.Width = std::min(L.Width - log2, MaxWidth); 11956 return L; 11957 } 11958 11959 // Otherwise, just use the LHS's width. 11960 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11961 // could be -1. 11962 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11963 Approximate); 11964 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11965 } 11966 11967 case BO_Rem: 11968 Combine = IntRange::rem; 11969 break; 11970 11971 // The default behavior is okay for these. 11972 case BO_Xor: 11973 case BO_Or: 11974 break; 11975 } 11976 11977 // Combine the two ranges, but limit the result to the type in which we 11978 // performed the computation. 11979 QualType T = GetExprType(E); 11980 unsigned opWidth = C.getIntWidth(T); 11981 IntRange L = 11982 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11983 IntRange R = 11984 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11985 IntRange C = Combine(L, R); 11986 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11987 C.Width = std::min(C.Width, MaxWidth); 11988 return C; 11989 } 11990 11991 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11992 switch (UO->getOpcode()) { 11993 // Boolean-valued operations are white-listed. 11994 case UO_LNot: 11995 return IntRange::forBoolType(); 11996 11997 // Operations with opaque sources are black-listed. 11998 case UO_Deref: 11999 case UO_AddrOf: // should be impossible 12000 return IntRange::forValueOfType(C, GetExprType(E)); 12001 12002 default: 12003 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 12004 Approximate); 12005 } 12006 } 12007 12008 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12009 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 12010 Approximate); 12011 12012 if (const auto *BitField = E->getSourceBitField()) 12013 return IntRange(BitField->getBitWidthValue(C), 12014 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 12015 12016 return IntRange::forValueOfType(C, GetExprType(E)); 12017 } 12018 12019 static IntRange GetExprRange(ASTContext &C, const Expr *E, 12020 bool InConstantContext, bool Approximate) { 12021 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 12022 Approximate); 12023 } 12024 12025 /// Checks whether the given value, which currently has the given 12026 /// source semantics, has the same value when coerced through the 12027 /// target semantics. 12028 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 12029 const llvm::fltSemantics &Src, 12030 const llvm::fltSemantics &Tgt) { 12031 llvm::APFloat truncated = value; 12032 12033 bool ignored; 12034 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 12035 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 12036 12037 return truncated.bitwiseIsEqual(value); 12038 } 12039 12040 /// Checks whether the given value, which currently has the given 12041 /// source semantics, has the same value when coerced through the 12042 /// target semantics. 12043 /// 12044 /// The value might be a vector of floats (or a complex number). 12045 static bool IsSameFloatAfterCast(const APValue &value, 12046 const llvm::fltSemantics &Src, 12047 const llvm::fltSemantics &Tgt) { 12048 if (value.isFloat()) 12049 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 12050 12051 if (value.isVector()) { 12052 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 12053 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 12054 return false; 12055 return true; 12056 } 12057 12058 assert(value.isComplexFloat()); 12059 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 12060 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 12061 } 12062 12063 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 12064 bool IsListInit = false); 12065 12066 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 12067 // Suppress cases where we are comparing against an enum constant. 12068 if (const DeclRefExpr *DR = 12069 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 12070 if (isa<EnumConstantDecl>(DR->getDecl())) 12071 return true; 12072 12073 // Suppress cases where the value is expanded from a macro, unless that macro 12074 // is how a language represents a boolean literal. This is the case in both C 12075 // and Objective-C. 12076 SourceLocation BeginLoc = E->getBeginLoc(); 12077 if (BeginLoc.isMacroID()) { 12078 StringRef MacroName = Lexer::getImmediateMacroName( 12079 BeginLoc, S.getSourceManager(), S.getLangOpts()); 12080 return MacroName != "YES" && MacroName != "NO" && 12081 MacroName != "true" && MacroName != "false"; 12082 } 12083 12084 return false; 12085 } 12086 12087 static bool isKnownToHaveUnsignedValue(Expr *E) { 12088 return E->getType()->isIntegerType() && 12089 (!E->getType()->isSignedIntegerType() || 12090 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 12091 } 12092 12093 namespace { 12094 /// The promoted range of values of a type. In general this has the 12095 /// following structure: 12096 /// 12097 /// |-----------| . . . |-----------| 12098 /// ^ ^ ^ ^ 12099 /// Min HoleMin HoleMax Max 12100 /// 12101 /// ... where there is only a hole if a signed type is promoted to unsigned 12102 /// (in which case Min and Max are the smallest and largest representable 12103 /// values). 12104 struct PromotedRange { 12105 // Min, or HoleMax if there is a hole. 12106 llvm::APSInt PromotedMin; 12107 // Max, or HoleMin if there is a hole. 12108 llvm::APSInt PromotedMax; 12109 12110 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 12111 if (R.Width == 0) 12112 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 12113 else if (R.Width >= BitWidth && !Unsigned) { 12114 // Promotion made the type *narrower*. This happens when promoting 12115 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 12116 // Treat all values of 'signed int' as being in range for now. 12117 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 12118 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 12119 } else { 12120 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 12121 .extOrTrunc(BitWidth); 12122 PromotedMin.setIsUnsigned(Unsigned); 12123 12124 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 12125 .extOrTrunc(BitWidth); 12126 PromotedMax.setIsUnsigned(Unsigned); 12127 } 12128 } 12129 12130 // Determine whether this range is contiguous (has no hole). 12131 bool isContiguous() const { return PromotedMin <= PromotedMax; } 12132 12133 // Where a constant value is within the range. 12134 enum ComparisonResult { 12135 LT = 0x1, 12136 LE = 0x2, 12137 GT = 0x4, 12138 GE = 0x8, 12139 EQ = 0x10, 12140 NE = 0x20, 12141 InRangeFlag = 0x40, 12142 12143 Less = LE | LT | NE, 12144 Min = LE | InRangeFlag, 12145 InRange = InRangeFlag, 12146 Max = GE | InRangeFlag, 12147 Greater = GE | GT | NE, 12148 12149 OnlyValue = LE | GE | EQ | InRangeFlag, 12150 InHole = NE 12151 }; 12152 12153 ComparisonResult compare(const llvm::APSInt &Value) const { 12154 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 12155 Value.isUnsigned() == PromotedMin.isUnsigned()); 12156 if (!isContiguous()) { 12157 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 12158 if (Value.isMinValue()) return Min; 12159 if (Value.isMaxValue()) return Max; 12160 if (Value >= PromotedMin) return InRange; 12161 if (Value <= PromotedMax) return InRange; 12162 return InHole; 12163 } 12164 12165 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 12166 case -1: return Less; 12167 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 12168 case 1: 12169 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 12170 case -1: return InRange; 12171 case 0: return Max; 12172 case 1: return Greater; 12173 } 12174 } 12175 12176 llvm_unreachable("impossible compare result"); 12177 } 12178 12179 static llvm::Optional<StringRef> 12180 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 12181 if (Op == BO_Cmp) { 12182 ComparisonResult LTFlag = LT, GTFlag = GT; 12183 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 12184 12185 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 12186 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 12187 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 12188 return llvm::None; 12189 } 12190 12191 ComparisonResult TrueFlag, FalseFlag; 12192 if (Op == BO_EQ) { 12193 TrueFlag = EQ; 12194 FalseFlag = NE; 12195 } else if (Op == BO_NE) { 12196 TrueFlag = NE; 12197 FalseFlag = EQ; 12198 } else { 12199 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 12200 TrueFlag = LT; 12201 FalseFlag = GE; 12202 } else { 12203 TrueFlag = GT; 12204 FalseFlag = LE; 12205 } 12206 if (Op == BO_GE || Op == BO_LE) 12207 std::swap(TrueFlag, FalseFlag); 12208 } 12209 if (R & TrueFlag) 12210 return StringRef("true"); 12211 if (R & FalseFlag) 12212 return StringRef("false"); 12213 return llvm::None; 12214 } 12215 }; 12216 } 12217 12218 static bool HasEnumType(Expr *E) { 12219 // Strip off implicit integral promotions. 12220 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12221 if (ICE->getCastKind() != CK_IntegralCast && 12222 ICE->getCastKind() != CK_NoOp) 12223 break; 12224 E = ICE->getSubExpr(); 12225 } 12226 12227 return E->getType()->isEnumeralType(); 12228 } 12229 12230 static int classifyConstantValue(Expr *Constant) { 12231 // The values of this enumeration are used in the diagnostics 12232 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 12233 enum ConstantValueKind { 12234 Miscellaneous = 0, 12235 LiteralTrue, 12236 LiteralFalse 12237 }; 12238 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 12239 return BL->getValue() ? ConstantValueKind::LiteralTrue 12240 : ConstantValueKind::LiteralFalse; 12241 return ConstantValueKind::Miscellaneous; 12242 } 12243 12244 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 12245 Expr *Constant, Expr *Other, 12246 const llvm::APSInt &Value, 12247 bool RhsConstant) { 12248 if (S.inTemplateInstantiation()) 12249 return false; 12250 12251 Expr *OriginalOther = Other; 12252 12253 Constant = Constant->IgnoreParenImpCasts(); 12254 Other = Other->IgnoreParenImpCasts(); 12255 12256 // Suppress warnings on tautological comparisons between values of the same 12257 // enumeration type. There are only two ways we could warn on this: 12258 // - If the constant is outside the range of representable values of 12259 // the enumeration. In such a case, we should warn about the cast 12260 // to enumeration type, not about the comparison. 12261 // - If the constant is the maximum / minimum in-range value. For an 12262 // enumeratin type, such comparisons can be meaningful and useful. 12263 if (Constant->getType()->isEnumeralType() && 12264 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 12265 return false; 12266 12267 IntRange OtherValueRange = GetExprRange( 12268 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 12269 12270 QualType OtherT = Other->getType(); 12271 if (const auto *AT = OtherT->getAs<AtomicType>()) 12272 OtherT = AT->getValueType(); 12273 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 12274 12275 // Special case for ObjC BOOL on targets where its a typedef for a signed char 12276 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 12277 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 12278 S.NSAPIObj->isObjCBOOLType(OtherT) && 12279 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 12280 12281 // Whether we're treating Other as being a bool because of the form of 12282 // expression despite it having another type (typically 'int' in C). 12283 bool OtherIsBooleanDespiteType = 12284 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 12285 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 12286 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 12287 12288 // Check if all values in the range of possible values of this expression 12289 // lead to the same comparison outcome. 12290 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 12291 Value.isUnsigned()); 12292 auto Cmp = OtherPromotedValueRange.compare(Value); 12293 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 12294 if (!Result) 12295 return false; 12296 12297 // Also consider the range determined by the type alone. This allows us to 12298 // classify the warning under the proper diagnostic group. 12299 bool TautologicalTypeCompare = false; 12300 { 12301 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 12302 Value.isUnsigned()); 12303 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 12304 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 12305 RhsConstant)) { 12306 TautologicalTypeCompare = true; 12307 Cmp = TypeCmp; 12308 Result = TypeResult; 12309 } 12310 } 12311 12312 // Don't warn if the non-constant operand actually always evaluates to the 12313 // same value. 12314 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 12315 return false; 12316 12317 // Suppress the diagnostic for an in-range comparison if the constant comes 12318 // from a macro or enumerator. We don't want to diagnose 12319 // 12320 // some_long_value <= INT_MAX 12321 // 12322 // when sizeof(int) == sizeof(long). 12323 bool InRange = Cmp & PromotedRange::InRangeFlag; 12324 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 12325 return false; 12326 12327 // A comparison of an unsigned bit-field against 0 is really a type problem, 12328 // even though at the type level the bit-field might promote to 'signed int'. 12329 if (Other->refersToBitField() && InRange && Value == 0 && 12330 Other->getType()->isUnsignedIntegerOrEnumerationType()) 12331 TautologicalTypeCompare = true; 12332 12333 // If this is a comparison to an enum constant, include that 12334 // constant in the diagnostic. 12335 const EnumConstantDecl *ED = nullptr; 12336 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 12337 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 12338 12339 // Should be enough for uint128 (39 decimal digits) 12340 SmallString<64> PrettySourceValue; 12341 llvm::raw_svector_ostream OS(PrettySourceValue); 12342 if (ED) { 12343 OS << '\'' << *ED << "' (" << Value << ")"; 12344 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 12345 Constant->IgnoreParenImpCasts())) { 12346 OS << (BL->getValue() ? "YES" : "NO"); 12347 } else { 12348 OS << Value; 12349 } 12350 12351 if (!TautologicalTypeCompare) { 12352 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 12353 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 12354 << E->getOpcodeStr() << OS.str() << *Result 12355 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 12356 return true; 12357 } 12358 12359 if (IsObjCSignedCharBool) { 12360 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12361 S.PDiag(diag::warn_tautological_compare_objc_bool) 12362 << OS.str() << *Result); 12363 return true; 12364 } 12365 12366 // FIXME: We use a somewhat different formatting for the in-range cases and 12367 // cases involving boolean values for historical reasons. We should pick a 12368 // consistent way of presenting these diagnostics. 12369 if (!InRange || Other->isKnownToHaveBooleanValue()) { 12370 12371 S.DiagRuntimeBehavior( 12372 E->getOperatorLoc(), E, 12373 S.PDiag(!InRange ? diag::warn_out_of_range_compare 12374 : diag::warn_tautological_bool_compare) 12375 << OS.str() << classifyConstantValue(Constant) << OtherT 12376 << OtherIsBooleanDespiteType << *Result 12377 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 12378 } else { 12379 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 12380 unsigned Diag = 12381 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 12382 ? (HasEnumType(OriginalOther) 12383 ? diag::warn_unsigned_enum_always_true_comparison 12384 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 12385 : diag::warn_unsigned_always_true_comparison) 12386 : diag::warn_tautological_constant_compare; 12387 12388 S.Diag(E->getOperatorLoc(), Diag) 12389 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 12390 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 12391 } 12392 12393 return true; 12394 } 12395 12396 /// Analyze the operands of the given comparison. Implements the 12397 /// fallback case from AnalyzeComparison. 12398 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 12399 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12400 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12401 } 12402 12403 /// Implements -Wsign-compare. 12404 /// 12405 /// \param E the binary operator to check for warnings 12406 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 12407 // The type the comparison is being performed in. 12408 QualType T = E->getLHS()->getType(); 12409 12410 // Only analyze comparison operators where both sides have been converted to 12411 // the same type. 12412 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 12413 return AnalyzeImpConvsInComparison(S, E); 12414 12415 // Don't analyze value-dependent comparisons directly. 12416 if (E->isValueDependent()) 12417 return AnalyzeImpConvsInComparison(S, E); 12418 12419 Expr *LHS = E->getLHS(); 12420 Expr *RHS = E->getRHS(); 12421 12422 if (T->isIntegralType(S.Context)) { 12423 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 12424 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 12425 12426 // We don't care about expressions whose result is a constant. 12427 if (RHSValue && LHSValue) 12428 return AnalyzeImpConvsInComparison(S, E); 12429 12430 // We only care about expressions where just one side is literal 12431 if ((bool)RHSValue ^ (bool)LHSValue) { 12432 // Is the constant on the RHS or LHS? 12433 const bool RhsConstant = (bool)RHSValue; 12434 Expr *Const = RhsConstant ? RHS : LHS; 12435 Expr *Other = RhsConstant ? LHS : RHS; 12436 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 12437 12438 // Check whether an integer constant comparison results in a value 12439 // of 'true' or 'false'. 12440 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 12441 return AnalyzeImpConvsInComparison(S, E); 12442 } 12443 } 12444 12445 if (!T->hasUnsignedIntegerRepresentation()) { 12446 // We don't do anything special if this isn't an unsigned integral 12447 // comparison: we're only interested in integral comparisons, and 12448 // signed comparisons only happen in cases we don't care to warn about. 12449 return AnalyzeImpConvsInComparison(S, E); 12450 } 12451 12452 LHS = LHS->IgnoreParenImpCasts(); 12453 RHS = RHS->IgnoreParenImpCasts(); 12454 12455 if (!S.getLangOpts().CPlusPlus) { 12456 // Avoid warning about comparison of integers with different signs when 12457 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 12458 // the type of `E`. 12459 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 12460 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12461 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 12462 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12463 } 12464 12465 // Check to see if one of the (unmodified) operands is of different 12466 // signedness. 12467 Expr *signedOperand, *unsignedOperand; 12468 if (LHS->getType()->hasSignedIntegerRepresentation()) { 12469 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 12470 "unsigned comparison between two signed integer expressions?"); 12471 signedOperand = LHS; 12472 unsignedOperand = RHS; 12473 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 12474 signedOperand = RHS; 12475 unsignedOperand = LHS; 12476 } else { 12477 return AnalyzeImpConvsInComparison(S, E); 12478 } 12479 12480 // Otherwise, calculate the effective range of the signed operand. 12481 IntRange signedRange = GetExprRange( 12482 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 12483 12484 // Go ahead and analyze implicit conversions in the operands. Note 12485 // that we skip the implicit conversions on both sides. 12486 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 12487 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 12488 12489 // If the signed range is non-negative, -Wsign-compare won't fire. 12490 if (signedRange.NonNegative) 12491 return; 12492 12493 // For (in)equality comparisons, if the unsigned operand is a 12494 // constant which cannot collide with a overflowed signed operand, 12495 // then reinterpreting the signed operand as unsigned will not 12496 // change the result of the comparison. 12497 if (E->isEqualityOp()) { 12498 unsigned comparisonWidth = S.Context.getIntWidth(T); 12499 IntRange unsignedRange = 12500 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 12501 /*Approximate*/ true); 12502 12503 // We should never be unable to prove that the unsigned operand is 12504 // non-negative. 12505 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 12506 12507 if (unsignedRange.Width < comparisonWidth) 12508 return; 12509 } 12510 12511 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12512 S.PDiag(diag::warn_mixed_sign_comparison) 12513 << LHS->getType() << RHS->getType() 12514 << LHS->getSourceRange() << RHS->getSourceRange()); 12515 } 12516 12517 /// Analyzes an attempt to assign the given value to a bitfield. 12518 /// 12519 /// Returns true if there was something fishy about the attempt. 12520 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 12521 SourceLocation InitLoc) { 12522 assert(Bitfield->isBitField()); 12523 if (Bitfield->isInvalidDecl()) 12524 return false; 12525 12526 // White-list bool bitfields. 12527 QualType BitfieldType = Bitfield->getType(); 12528 if (BitfieldType->isBooleanType()) 12529 return false; 12530 12531 if (BitfieldType->isEnumeralType()) { 12532 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 12533 // If the underlying enum type was not explicitly specified as an unsigned 12534 // type and the enum contain only positive values, MSVC++ will cause an 12535 // inconsistency by storing this as a signed type. 12536 if (S.getLangOpts().CPlusPlus11 && 12537 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 12538 BitfieldEnumDecl->getNumPositiveBits() > 0 && 12539 BitfieldEnumDecl->getNumNegativeBits() == 0) { 12540 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 12541 << BitfieldEnumDecl; 12542 } 12543 } 12544 12545 if (Bitfield->getType()->isBooleanType()) 12546 return false; 12547 12548 // Ignore value- or type-dependent expressions. 12549 if (Bitfield->getBitWidth()->isValueDependent() || 12550 Bitfield->getBitWidth()->isTypeDependent() || 12551 Init->isValueDependent() || 12552 Init->isTypeDependent()) 12553 return false; 12554 12555 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 12556 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 12557 12558 Expr::EvalResult Result; 12559 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 12560 Expr::SE_AllowSideEffects)) { 12561 // The RHS is not constant. If the RHS has an enum type, make sure the 12562 // bitfield is wide enough to hold all the values of the enum without 12563 // truncation. 12564 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 12565 EnumDecl *ED = EnumTy->getDecl(); 12566 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 12567 12568 // Enum types are implicitly signed on Windows, so check if there are any 12569 // negative enumerators to see if the enum was intended to be signed or 12570 // not. 12571 bool SignedEnum = ED->getNumNegativeBits() > 0; 12572 12573 // Check for surprising sign changes when assigning enum values to a 12574 // bitfield of different signedness. If the bitfield is signed and we 12575 // have exactly the right number of bits to store this unsigned enum, 12576 // suggest changing the enum to an unsigned type. This typically happens 12577 // on Windows where unfixed enums always use an underlying type of 'int'. 12578 unsigned DiagID = 0; 12579 if (SignedEnum && !SignedBitfield) { 12580 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 12581 } else if (SignedBitfield && !SignedEnum && 12582 ED->getNumPositiveBits() == FieldWidth) { 12583 DiagID = diag::warn_signed_bitfield_enum_conversion; 12584 } 12585 12586 if (DiagID) { 12587 S.Diag(InitLoc, DiagID) << Bitfield << ED; 12588 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 12589 SourceRange TypeRange = 12590 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 12591 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 12592 << SignedEnum << TypeRange; 12593 } 12594 12595 // Compute the required bitwidth. If the enum has negative values, we need 12596 // one more bit than the normal number of positive bits to represent the 12597 // sign bit. 12598 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 12599 ED->getNumNegativeBits()) 12600 : ED->getNumPositiveBits(); 12601 12602 // Check the bitwidth. 12603 if (BitsNeeded > FieldWidth) { 12604 Expr *WidthExpr = Bitfield->getBitWidth(); 12605 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 12606 << Bitfield << ED; 12607 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 12608 << BitsNeeded << ED << WidthExpr->getSourceRange(); 12609 } 12610 } 12611 12612 return false; 12613 } 12614 12615 llvm::APSInt Value = Result.Val.getInt(); 12616 12617 unsigned OriginalWidth = Value.getBitWidth(); 12618 12619 if (!Value.isSigned() || Value.isNegative()) 12620 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 12621 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 12622 OriginalWidth = Value.getMinSignedBits(); 12623 12624 if (OriginalWidth <= FieldWidth) 12625 return false; 12626 12627 // Compute the value which the bitfield will contain. 12628 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 12629 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 12630 12631 // Check whether the stored value is equal to the original value. 12632 TruncatedValue = TruncatedValue.extend(OriginalWidth); 12633 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 12634 return false; 12635 12636 // Special-case bitfields of width 1: booleans are naturally 0/1, and 12637 // therefore don't strictly fit into a signed bitfield of width 1. 12638 if (FieldWidth == 1 && Value == 1) 12639 return false; 12640 12641 std::string PrettyValue = toString(Value, 10); 12642 std::string PrettyTrunc = toString(TruncatedValue, 10); 12643 12644 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 12645 << PrettyValue << PrettyTrunc << OriginalInit->getType() 12646 << Init->getSourceRange(); 12647 12648 return true; 12649 } 12650 12651 /// Analyze the given simple or compound assignment for warning-worthy 12652 /// operations. 12653 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 12654 // Just recurse on the LHS. 12655 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12656 12657 // We want to recurse on the RHS as normal unless we're assigning to 12658 // a bitfield. 12659 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 12660 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 12661 E->getOperatorLoc())) { 12662 // Recurse, ignoring any implicit conversions on the RHS. 12663 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 12664 E->getOperatorLoc()); 12665 } 12666 } 12667 12668 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12669 12670 // Diagnose implicitly sequentially-consistent atomic assignment. 12671 if (E->getLHS()->getType()->isAtomicType()) 12672 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12673 } 12674 12675 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12676 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 12677 SourceLocation CContext, unsigned diag, 12678 bool pruneControlFlow = false) { 12679 if (pruneControlFlow) { 12680 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12681 S.PDiag(diag) 12682 << SourceType << T << E->getSourceRange() 12683 << SourceRange(CContext)); 12684 return; 12685 } 12686 S.Diag(E->getExprLoc(), diag) 12687 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 12688 } 12689 12690 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12691 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 12692 SourceLocation CContext, 12693 unsigned diag, bool pruneControlFlow = false) { 12694 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 12695 } 12696 12697 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 12698 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 12699 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 12700 } 12701 12702 static void adornObjCBoolConversionDiagWithTernaryFixit( 12703 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 12704 Expr *Ignored = SourceExpr->IgnoreImplicit(); 12705 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 12706 Ignored = OVE->getSourceExpr(); 12707 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 12708 isa<BinaryOperator>(Ignored) || 12709 isa<CXXOperatorCallExpr>(Ignored); 12710 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 12711 if (NeedsParens) 12712 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 12713 << FixItHint::CreateInsertion(EndLoc, ")"); 12714 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 12715 } 12716 12717 /// Diagnose an implicit cast from a floating point value to an integer value. 12718 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 12719 SourceLocation CContext) { 12720 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 12721 const bool PruneWarnings = S.inTemplateInstantiation(); 12722 12723 Expr *InnerE = E->IgnoreParenImpCasts(); 12724 // We also want to warn on, e.g., "int i = -1.234" 12725 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 12726 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 12727 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 12728 12729 const bool IsLiteral = 12730 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 12731 12732 llvm::APFloat Value(0.0); 12733 bool IsConstant = 12734 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 12735 if (!IsConstant) { 12736 if (isObjCSignedCharBool(S, T)) { 12737 return adornObjCBoolConversionDiagWithTernaryFixit( 12738 S, E, 12739 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 12740 << E->getType()); 12741 } 12742 12743 return DiagnoseImpCast(S, E, T, CContext, 12744 diag::warn_impcast_float_integer, PruneWarnings); 12745 } 12746 12747 bool isExact = false; 12748 12749 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 12750 T->hasUnsignedIntegerRepresentation()); 12751 llvm::APFloat::opStatus Result = Value.convertToInteger( 12752 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 12753 12754 // FIXME: Force the precision of the source value down so we don't print 12755 // digits which are usually useless (we don't really care here if we 12756 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 12757 // would automatically print the shortest representation, but it's a bit 12758 // tricky to implement. 12759 SmallString<16> PrettySourceValue; 12760 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 12761 precision = (precision * 59 + 195) / 196; 12762 Value.toString(PrettySourceValue, precision); 12763 12764 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 12765 return adornObjCBoolConversionDiagWithTernaryFixit( 12766 S, E, 12767 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 12768 << PrettySourceValue); 12769 } 12770 12771 if (Result == llvm::APFloat::opOK && isExact) { 12772 if (IsLiteral) return; 12773 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 12774 PruneWarnings); 12775 } 12776 12777 // Conversion of a floating-point value to a non-bool integer where the 12778 // integral part cannot be represented by the integer type is undefined. 12779 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 12780 return DiagnoseImpCast( 12781 S, E, T, CContext, 12782 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 12783 : diag::warn_impcast_float_to_integer_out_of_range, 12784 PruneWarnings); 12785 12786 unsigned DiagID = 0; 12787 if (IsLiteral) { 12788 // Warn on floating point literal to integer. 12789 DiagID = diag::warn_impcast_literal_float_to_integer; 12790 } else if (IntegerValue == 0) { 12791 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 12792 return DiagnoseImpCast(S, E, T, CContext, 12793 diag::warn_impcast_float_integer, PruneWarnings); 12794 } 12795 // Warn on non-zero to zero conversion. 12796 DiagID = diag::warn_impcast_float_to_integer_zero; 12797 } else { 12798 if (IntegerValue.isUnsigned()) { 12799 if (!IntegerValue.isMaxValue()) { 12800 return DiagnoseImpCast(S, E, T, CContext, 12801 diag::warn_impcast_float_integer, PruneWarnings); 12802 } 12803 } else { // IntegerValue.isSigned() 12804 if (!IntegerValue.isMaxSignedValue() && 12805 !IntegerValue.isMinSignedValue()) { 12806 return DiagnoseImpCast(S, E, T, CContext, 12807 diag::warn_impcast_float_integer, PruneWarnings); 12808 } 12809 } 12810 // Warn on evaluatable floating point expression to integer conversion. 12811 DiagID = diag::warn_impcast_float_to_integer; 12812 } 12813 12814 SmallString<16> PrettyTargetValue; 12815 if (IsBool) 12816 PrettyTargetValue = Value.isZero() ? "false" : "true"; 12817 else 12818 IntegerValue.toString(PrettyTargetValue); 12819 12820 if (PruneWarnings) { 12821 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12822 S.PDiag(DiagID) 12823 << E->getType() << T.getUnqualifiedType() 12824 << PrettySourceValue << PrettyTargetValue 12825 << E->getSourceRange() << SourceRange(CContext)); 12826 } else { 12827 S.Diag(E->getExprLoc(), DiagID) 12828 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 12829 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 12830 } 12831 } 12832 12833 /// Analyze the given compound assignment for the possible losing of 12834 /// floating-point precision. 12835 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 12836 assert(isa<CompoundAssignOperator>(E) && 12837 "Must be compound assignment operation"); 12838 // Recurse on the LHS and RHS in here 12839 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12840 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12841 12842 if (E->getLHS()->getType()->isAtomicType()) 12843 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 12844 12845 // Now check the outermost expression 12846 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 12847 const auto *RBT = cast<CompoundAssignOperator>(E) 12848 ->getComputationResultType() 12849 ->getAs<BuiltinType>(); 12850 12851 // The below checks assume source is floating point. 12852 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 12853 12854 // If source is floating point but target is an integer. 12855 if (ResultBT->isInteger()) 12856 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 12857 E->getExprLoc(), diag::warn_impcast_float_integer); 12858 12859 if (!ResultBT->isFloatingPoint()) 12860 return; 12861 12862 // If both source and target are floating points, warn about losing precision. 12863 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12864 QualType(ResultBT, 0), QualType(RBT, 0)); 12865 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 12866 // warn about dropping FP rank. 12867 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 12868 diag::warn_impcast_float_result_precision); 12869 } 12870 12871 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 12872 IntRange Range) { 12873 if (!Range.Width) return "0"; 12874 12875 llvm::APSInt ValueInRange = Value; 12876 ValueInRange.setIsSigned(!Range.NonNegative); 12877 ValueInRange = ValueInRange.trunc(Range.Width); 12878 return toString(ValueInRange, 10); 12879 } 12880 12881 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 12882 if (!isa<ImplicitCastExpr>(Ex)) 12883 return false; 12884 12885 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12886 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12887 const Type *Source = 12888 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12889 if (Target->isDependentType()) 12890 return false; 12891 12892 const BuiltinType *FloatCandidateBT = 12893 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12894 const Type *BoolCandidateType = ToBool ? Target : Source; 12895 12896 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12897 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12898 } 12899 12900 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12901 SourceLocation CC) { 12902 unsigned NumArgs = TheCall->getNumArgs(); 12903 for (unsigned i = 0; i < NumArgs; ++i) { 12904 Expr *CurrA = TheCall->getArg(i); 12905 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12906 continue; 12907 12908 bool IsSwapped = ((i > 0) && 12909 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12910 IsSwapped |= ((i < (NumArgs - 1)) && 12911 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12912 if (IsSwapped) { 12913 // Warn on this floating-point to bool conversion. 12914 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12915 CurrA->getType(), CC, 12916 diag::warn_impcast_floating_point_to_bool); 12917 } 12918 } 12919 } 12920 12921 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12922 SourceLocation CC) { 12923 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12924 E->getExprLoc())) 12925 return; 12926 12927 // Don't warn on functions which have return type nullptr_t. 12928 if (isa<CallExpr>(E)) 12929 return; 12930 12931 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12932 const Expr::NullPointerConstantKind NullKind = 12933 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12934 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12935 return; 12936 12937 // Return if target type is a safe conversion. 12938 if (T->isAnyPointerType() || T->isBlockPointerType() || 12939 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12940 return; 12941 12942 SourceLocation Loc = E->getSourceRange().getBegin(); 12943 12944 // Venture through the macro stacks to get to the source of macro arguments. 12945 // The new location is a better location than the complete location that was 12946 // passed in. 12947 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12948 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12949 12950 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12951 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12952 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12953 Loc, S.SourceMgr, S.getLangOpts()); 12954 if (MacroName == "NULL") 12955 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12956 } 12957 12958 // Only warn if the null and context location are in the same macro expansion. 12959 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12960 return; 12961 12962 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12963 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12964 << FixItHint::CreateReplacement(Loc, 12965 S.getFixItZeroLiteralForType(T, Loc)); 12966 } 12967 12968 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12969 ObjCArrayLiteral *ArrayLiteral); 12970 12971 static void 12972 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12973 ObjCDictionaryLiteral *DictionaryLiteral); 12974 12975 /// Check a single element within a collection literal against the 12976 /// target element type. 12977 static void checkObjCCollectionLiteralElement(Sema &S, 12978 QualType TargetElementType, 12979 Expr *Element, 12980 unsigned ElementKind) { 12981 // Skip a bitcast to 'id' or qualified 'id'. 12982 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12983 if (ICE->getCastKind() == CK_BitCast && 12984 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12985 Element = ICE->getSubExpr(); 12986 } 12987 12988 QualType ElementType = Element->getType(); 12989 ExprResult ElementResult(Element); 12990 if (ElementType->getAs<ObjCObjectPointerType>() && 12991 S.CheckSingleAssignmentConstraints(TargetElementType, 12992 ElementResult, 12993 false, false) 12994 != Sema::Compatible) { 12995 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12996 << ElementType << ElementKind << TargetElementType 12997 << Element->getSourceRange(); 12998 } 12999 13000 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 13001 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 13002 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 13003 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 13004 } 13005 13006 /// Check an Objective-C array literal being converted to the given 13007 /// target type. 13008 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 13009 ObjCArrayLiteral *ArrayLiteral) { 13010 if (!S.NSArrayDecl) 13011 return; 13012 13013 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 13014 if (!TargetObjCPtr) 13015 return; 13016 13017 if (TargetObjCPtr->isUnspecialized() || 13018 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 13019 != S.NSArrayDecl->getCanonicalDecl()) 13020 return; 13021 13022 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 13023 if (TypeArgs.size() != 1) 13024 return; 13025 13026 QualType TargetElementType = TypeArgs[0]; 13027 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 13028 checkObjCCollectionLiteralElement(S, TargetElementType, 13029 ArrayLiteral->getElement(I), 13030 0); 13031 } 13032 } 13033 13034 /// Check an Objective-C dictionary literal being converted to the given 13035 /// target type. 13036 static void 13037 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 13038 ObjCDictionaryLiteral *DictionaryLiteral) { 13039 if (!S.NSDictionaryDecl) 13040 return; 13041 13042 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 13043 if (!TargetObjCPtr) 13044 return; 13045 13046 if (TargetObjCPtr->isUnspecialized() || 13047 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 13048 != S.NSDictionaryDecl->getCanonicalDecl()) 13049 return; 13050 13051 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 13052 if (TypeArgs.size() != 2) 13053 return; 13054 13055 QualType TargetKeyType = TypeArgs[0]; 13056 QualType TargetObjectType = TypeArgs[1]; 13057 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 13058 auto Element = DictionaryLiteral->getKeyValueElement(I); 13059 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 13060 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 13061 } 13062 } 13063 13064 // Helper function to filter out cases for constant width constant conversion. 13065 // Don't warn on char array initialization or for non-decimal values. 13066 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 13067 SourceLocation CC) { 13068 // If initializing from a constant, and the constant starts with '0', 13069 // then it is a binary, octal, or hexadecimal. Allow these constants 13070 // to fill all the bits, even if there is a sign change. 13071 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 13072 const char FirstLiteralCharacter = 13073 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 13074 if (FirstLiteralCharacter == '0') 13075 return false; 13076 } 13077 13078 // If the CC location points to a '{', and the type is char, then assume 13079 // assume it is an array initialization. 13080 if (CC.isValid() && T->isCharType()) { 13081 const char FirstContextCharacter = 13082 S.getSourceManager().getCharacterData(CC)[0]; 13083 if (FirstContextCharacter == '{') 13084 return false; 13085 } 13086 13087 return true; 13088 } 13089 13090 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 13091 const auto *IL = dyn_cast<IntegerLiteral>(E); 13092 if (!IL) { 13093 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 13094 if (UO->getOpcode() == UO_Minus) 13095 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 13096 } 13097 } 13098 13099 return IL; 13100 } 13101 13102 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 13103 E = E->IgnoreParenImpCasts(); 13104 SourceLocation ExprLoc = E->getExprLoc(); 13105 13106 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 13107 BinaryOperator::Opcode Opc = BO->getOpcode(); 13108 Expr::EvalResult Result; 13109 // Do not diagnose unsigned shifts. 13110 if (Opc == BO_Shl) { 13111 const auto *LHS = getIntegerLiteral(BO->getLHS()); 13112 const auto *RHS = getIntegerLiteral(BO->getRHS()); 13113 if (LHS && LHS->getValue() == 0) 13114 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 13115 else if (!E->isValueDependent() && LHS && RHS && 13116 RHS->getValue().isNonNegative() && 13117 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 13118 S.Diag(ExprLoc, diag::warn_left_shift_always) 13119 << (Result.Val.getInt() != 0); 13120 else if (E->getType()->isSignedIntegerType()) 13121 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 13122 } 13123 } 13124 13125 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 13126 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 13127 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 13128 if (!LHS || !RHS) 13129 return; 13130 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 13131 (RHS->getValue() == 0 || RHS->getValue() == 1)) 13132 // Do not diagnose common idioms. 13133 return; 13134 if (LHS->getValue() != 0 && RHS->getValue() != 0) 13135 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 13136 } 13137 } 13138 13139 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 13140 SourceLocation CC, 13141 bool *ICContext = nullptr, 13142 bool IsListInit = false) { 13143 if (E->isTypeDependent() || E->isValueDependent()) return; 13144 13145 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 13146 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 13147 if (Source == Target) return; 13148 if (Target->isDependentType()) return; 13149 13150 // If the conversion context location is invalid don't complain. We also 13151 // don't want to emit a warning if the issue occurs from the expansion of 13152 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 13153 // delay this check as long as possible. Once we detect we are in that 13154 // scenario, we just return. 13155 if (CC.isInvalid()) 13156 return; 13157 13158 if (Source->isAtomicType()) 13159 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 13160 13161 // Diagnose implicit casts to bool. 13162 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 13163 if (isa<StringLiteral>(E)) 13164 // Warn on string literal to bool. Checks for string literals in logical 13165 // and expressions, for instance, assert(0 && "error here"), are 13166 // prevented by a check in AnalyzeImplicitConversions(). 13167 return DiagnoseImpCast(S, E, T, CC, 13168 diag::warn_impcast_string_literal_to_bool); 13169 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 13170 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 13171 // This covers the literal expressions that evaluate to Objective-C 13172 // objects. 13173 return DiagnoseImpCast(S, E, T, CC, 13174 diag::warn_impcast_objective_c_literal_to_bool); 13175 } 13176 if (Source->isPointerType() || Source->canDecayToPointerType()) { 13177 // Warn on pointer to bool conversion that is always true. 13178 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 13179 SourceRange(CC)); 13180 } 13181 } 13182 13183 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 13184 // is a typedef for signed char (macOS), then that constant value has to be 1 13185 // or 0. 13186 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 13187 Expr::EvalResult Result; 13188 if (E->EvaluateAsInt(Result, S.getASTContext(), 13189 Expr::SE_AllowSideEffects)) { 13190 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 13191 adornObjCBoolConversionDiagWithTernaryFixit( 13192 S, E, 13193 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 13194 << toString(Result.Val.getInt(), 10)); 13195 } 13196 return; 13197 } 13198 } 13199 13200 // Check implicit casts from Objective-C collection literals to specialized 13201 // collection types, e.g., NSArray<NSString *> *. 13202 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 13203 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 13204 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 13205 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 13206 13207 // Strip vector types. 13208 if (isa<VectorType>(Source)) { 13209 if (Target->isVLSTBuiltinType() && 13210 (S.Context.areCompatibleSveTypes(QualType(Target, 0), 13211 QualType(Source, 0)) || 13212 S.Context.areLaxCompatibleSveTypes(QualType(Target, 0), 13213 QualType(Source, 0)))) 13214 return; 13215 13216 if (!isa<VectorType>(Target)) { 13217 if (S.SourceMgr.isInSystemMacro(CC)) 13218 return; 13219 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 13220 } 13221 13222 // If the vector cast is cast between two vectors of the same size, it is 13223 // a bitcast, not a conversion. 13224 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 13225 return; 13226 13227 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 13228 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 13229 } 13230 if (auto VecTy = dyn_cast<VectorType>(Target)) 13231 Target = VecTy->getElementType().getTypePtr(); 13232 13233 // Strip complex types. 13234 if (isa<ComplexType>(Source)) { 13235 if (!isa<ComplexType>(Target)) { 13236 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 13237 return; 13238 13239 return DiagnoseImpCast(S, E, T, CC, 13240 S.getLangOpts().CPlusPlus 13241 ? diag::err_impcast_complex_scalar 13242 : diag::warn_impcast_complex_scalar); 13243 } 13244 13245 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 13246 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 13247 } 13248 13249 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 13250 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 13251 13252 // If the source is floating point... 13253 if (SourceBT && SourceBT->isFloatingPoint()) { 13254 // ...and the target is floating point... 13255 if (TargetBT && TargetBT->isFloatingPoint()) { 13256 // ...then warn if we're dropping FP rank. 13257 13258 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 13259 QualType(SourceBT, 0), QualType(TargetBT, 0)); 13260 if (Order > 0) { 13261 // Don't warn about float constants that are precisely 13262 // representable in the target type. 13263 Expr::EvalResult result; 13264 if (E->EvaluateAsRValue(result, S.Context)) { 13265 // Value might be a float, a float vector, or a float complex. 13266 if (IsSameFloatAfterCast(result.Val, 13267 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 13268 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 13269 return; 13270 } 13271 13272 if (S.SourceMgr.isInSystemMacro(CC)) 13273 return; 13274 13275 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 13276 } 13277 // ... or possibly if we're increasing rank, too 13278 else if (Order < 0) { 13279 if (S.SourceMgr.isInSystemMacro(CC)) 13280 return; 13281 13282 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 13283 } 13284 return; 13285 } 13286 13287 // If the target is integral, always warn. 13288 if (TargetBT && TargetBT->isInteger()) { 13289 if (S.SourceMgr.isInSystemMacro(CC)) 13290 return; 13291 13292 DiagnoseFloatingImpCast(S, E, T, CC); 13293 } 13294 13295 // Detect the case where a call result is converted from floating-point to 13296 // to bool, and the final argument to the call is converted from bool, to 13297 // discover this typo: 13298 // 13299 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 13300 // 13301 // FIXME: This is an incredibly special case; is there some more general 13302 // way to detect this class of misplaced-parentheses bug? 13303 if (Target->isBooleanType() && isa<CallExpr>(E)) { 13304 // Check last argument of function call to see if it is an 13305 // implicit cast from a type matching the type the result 13306 // is being cast to. 13307 CallExpr *CEx = cast<CallExpr>(E); 13308 if (unsigned NumArgs = CEx->getNumArgs()) { 13309 Expr *LastA = CEx->getArg(NumArgs - 1); 13310 Expr *InnerE = LastA->IgnoreParenImpCasts(); 13311 if (isa<ImplicitCastExpr>(LastA) && 13312 InnerE->getType()->isBooleanType()) { 13313 // Warn on this floating-point to bool conversion 13314 DiagnoseImpCast(S, E, T, CC, 13315 diag::warn_impcast_floating_point_to_bool); 13316 } 13317 } 13318 } 13319 return; 13320 } 13321 13322 // Valid casts involving fixed point types should be accounted for here. 13323 if (Source->isFixedPointType()) { 13324 if (Target->isUnsaturatedFixedPointType()) { 13325 Expr::EvalResult Result; 13326 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 13327 S.isConstantEvaluated())) { 13328 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 13329 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 13330 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 13331 if (Value > MaxVal || Value < MinVal) { 13332 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13333 S.PDiag(diag::warn_impcast_fixed_point_range) 13334 << Value.toString() << T 13335 << E->getSourceRange() 13336 << clang::SourceRange(CC)); 13337 return; 13338 } 13339 } 13340 } else if (Target->isIntegerType()) { 13341 Expr::EvalResult Result; 13342 if (!S.isConstantEvaluated() && 13343 E->EvaluateAsFixedPoint(Result, S.Context, 13344 Expr::SE_AllowSideEffects)) { 13345 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 13346 13347 bool Overflowed; 13348 llvm::APSInt IntResult = FXResult.convertToInt( 13349 S.Context.getIntWidth(T), 13350 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 13351 13352 if (Overflowed) { 13353 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13354 S.PDiag(diag::warn_impcast_fixed_point_range) 13355 << FXResult.toString() << T 13356 << E->getSourceRange() 13357 << clang::SourceRange(CC)); 13358 return; 13359 } 13360 } 13361 } 13362 } else if (Target->isUnsaturatedFixedPointType()) { 13363 if (Source->isIntegerType()) { 13364 Expr::EvalResult Result; 13365 if (!S.isConstantEvaluated() && 13366 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 13367 llvm::APSInt Value = Result.Val.getInt(); 13368 13369 bool Overflowed; 13370 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 13371 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 13372 13373 if (Overflowed) { 13374 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13375 S.PDiag(diag::warn_impcast_fixed_point_range) 13376 << toString(Value, /*Radix=*/10) << T 13377 << E->getSourceRange() 13378 << clang::SourceRange(CC)); 13379 return; 13380 } 13381 } 13382 } 13383 } 13384 13385 // If we are casting an integer type to a floating point type without 13386 // initialization-list syntax, we might lose accuracy if the floating 13387 // point type has a narrower significand than the integer type. 13388 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 13389 TargetBT->isFloatingType() && !IsListInit) { 13390 // Determine the number of precision bits in the source integer type. 13391 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 13392 /*Approximate*/ true); 13393 unsigned int SourcePrecision = SourceRange.Width; 13394 13395 // Determine the number of precision bits in the 13396 // target floating point type. 13397 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 13398 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13399 13400 if (SourcePrecision > 0 && TargetPrecision > 0 && 13401 SourcePrecision > TargetPrecision) { 13402 13403 if (Optional<llvm::APSInt> SourceInt = 13404 E->getIntegerConstantExpr(S.Context)) { 13405 // If the source integer is a constant, convert it to the target 13406 // floating point type. Issue a warning if the value changes 13407 // during the whole conversion. 13408 llvm::APFloat TargetFloatValue( 13409 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13410 llvm::APFloat::opStatus ConversionStatus = 13411 TargetFloatValue.convertFromAPInt( 13412 *SourceInt, SourceBT->isSignedInteger(), 13413 llvm::APFloat::rmNearestTiesToEven); 13414 13415 if (ConversionStatus != llvm::APFloat::opOK) { 13416 SmallString<32> PrettySourceValue; 13417 SourceInt->toString(PrettySourceValue, 10); 13418 SmallString<32> PrettyTargetValue; 13419 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 13420 13421 S.DiagRuntimeBehavior( 13422 E->getExprLoc(), E, 13423 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 13424 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13425 << E->getSourceRange() << clang::SourceRange(CC)); 13426 } 13427 } else { 13428 // Otherwise, the implicit conversion may lose precision. 13429 DiagnoseImpCast(S, E, T, CC, 13430 diag::warn_impcast_integer_float_precision); 13431 } 13432 } 13433 } 13434 13435 DiagnoseNullConversion(S, E, T, CC); 13436 13437 S.DiscardMisalignedMemberAddress(Target, E); 13438 13439 if (Target->isBooleanType()) 13440 DiagnoseIntInBoolContext(S, E); 13441 13442 if (!Source->isIntegerType() || !Target->isIntegerType()) 13443 return; 13444 13445 // TODO: remove this early return once the false positives for constant->bool 13446 // in templates, macros, etc, are reduced or removed. 13447 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 13448 return; 13449 13450 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 13451 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 13452 return adornObjCBoolConversionDiagWithTernaryFixit( 13453 S, E, 13454 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 13455 << E->getType()); 13456 } 13457 13458 IntRange SourceTypeRange = 13459 IntRange::forTargetOfCanonicalType(S.Context, Source); 13460 IntRange LikelySourceRange = 13461 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 13462 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 13463 13464 if (LikelySourceRange.Width > TargetRange.Width) { 13465 // If the source is a constant, use a default-on diagnostic. 13466 // TODO: this should happen for bitfield stores, too. 13467 Expr::EvalResult Result; 13468 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 13469 S.isConstantEvaluated())) { 13470 llvm::APSInt Value(32); 13471 Value = Result.Val.getInt(); 13472 13473 if (S.SourceMgr.isInSystemMacro(CC)) 13474 return; 13475 13476 std::string PrettySourceValue = toString(Value, 10); 13477 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13478 13479 S.DiagRuntimeBehavior( 13480 E->getExprLoc(), E, 13481 S.PDiag(diag::warn_impcast_integer_precision_constant) 13482 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13483 << E->getSourceRange() << SourceRange(CC)); 13484 return; 13485 } 13486 13487 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 13488 if (S.SourceMgr.isInSystemMacro(CC)) 13489 return; 13490 13491 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 13492 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 13493 /* pruneControlFlow */ true); 13494 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 13495 } 13496 13497 if (TargetRange.Width > SourceTypeRange.Width) { 13498 if (auto *UO = dyn_cast<UnaryOperator>(E)) 13499 if (UO->getOpcode() == UO_Minus) 13500 if (Source->isUnsignedIntegerType()) { 13501 if (Target->isUnsignedIntegerType()) 13502 return DiagnoseImpCast(S, E, T, CC, 13503 diag::warn_impcast_high_order_zero_bits); 13504 if (Target->isSignedIntegerType()) 13505 return DiagnoseImpCast(S, E, T, CC, 13506 diag::warn_impcast_nonnegative_result); 13507 } 13508 } 13509 13510 if (TargetRange.Width == LikelySourceRange.Width && 13511 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 13512 Source->isSignedIntegerType()) { 13513 // Warn when doing a signed to signed conversion, warn if the positive 13514 // source value is exactly the width of the target type, which will 13515 // cause a negative value to be stored. 13516 13517 Expr::EvalResult Result; 13518 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 13519 !S.SourceMgr.isInSystemMacro(CC)) { 13520 llvm::APSInt Value = Result.Val.getInt(); 13521 if (isSameWidthConstantConversion(S, E, T, CC)) { 13522 std::string PrettySourceValue = toString(Value, 10); 13523 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13524 13525 S.DiagRuntimeBehavior( 13526 E->getExprLoc(), E, 13527 S.PDiag(diag::warn_impcast_integer_precision_constant) 13528 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13529 << E->getSourceRange() << SourceRange(CC)); 13530 return; 13531 } 13532 } 13533 13534 // Fall through for non-constants to give a sign conversion warning. 13535 } 13536 13537 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 13538 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 13539 LikelySourceRange.Width == TargetRange.Width)) { 13540 if (S.SourceMgr.isInSystemMacro(CC)) 13541 return; 13542 13543 unsigned DiagID = diag::warn_impcast_integer_sign; 13544 13545 // Traditionally, gcc has warned about this under -Wsign-compare. 13546 // We also want to warn about it in -Wconversion. 13547 // So if -Wconversion is off, use a completely identical diagnostic 13548 // in the sign-compare group. 13549 // The conditional-checking code will 13550 if (ICContext) { 13551 DiagID = diag::warn_impcast_integer_sign_conditional; 13552 *ICContext = true; 13553 } 13554 13555 return DiagnoseImpCast(S, E, T, CC, DiagID); 13556 } 13557 13558 // Diagnose conversions between different enumeration types. 13559 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 13560 // type, to give us better diagnostics. 13561 QualType SourceType = E->getType(); 13562 if (!S.getLangOpts().CPlusPlus) { 13563 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13564 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 13565 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 13566 SourceType = S.Context.getTypeDeclType(Enum); 13567 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 13568 } 13569 } 13570 13571 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 13572 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 13573 if (SourceEnum->getDecl()->hasNameForLinkage() && 13574 TargetEnum->getDecl()->hasNameForLinkage() && 13575 SourceEnum != TargetEnum) { 13576 if (S.SourceMgr.isInSystemMacro(CC)) 13577 return; 13578 13579 return DiagnoseImpCast(S, E, SourceType, T, CC, 13580 diag::warn_impcast_different_enum_types); 13581 } 13582 } 13583 13584 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13585 SourceLocation CC, QualType T); 13586 13587 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 13588 SourceLocation CC, bool &ICContext) { 13589 E = E->IgnoreParenImpCasts(); 13590 13591 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 13592 return CheckConditionalOperator(S, CO, CC, T); 13593 13594 AnalyzeImplicitConversions(S, E, CC); 13595 if (E->getType() != T) 13596 return CheckImplicitConversion(S, E, T, CC, &ICContext); 13597 } 13598 13599 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13600 SourceLocation CC, QualType T) { 13601 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 13602 13603 Expr *TrueExpr = E->getTrueExpr(); 13604 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 13605 TrueExpr = BCO->getCommon(); 13606 13607 bool Suspicious = false; 13608 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 13609 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 13610 13611 if (T->isBooleanType()) 13612 DiagnoseIntInBoolContext(S, E); 13613 13614 // If -Wconversion would have warned about either of the candidates 13615 // for a signedness conversion to the context type... 13616 if (!Suspicious) return; 13617 13618 // ...but it's currently ignored... 13619 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 13620 return; 13621 13622 // ...then check whether it would have warned about either of the 13623 // candidates for a signedness conversion to the condition type. 13624 if (E->getType() == T) return; 13625 13626 Suspicious = false; 13627 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 13628 E->getType(), CC, &Suspicious); 13629 if (!Suspicious) 13630 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 13631 E->getType(), CC, &Suspicious); 13632 } 13633 13634 /// Check conversion of given expression to boolean. 13635 /// Input argument E is a logical expression. 13636 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 13637 if (S.getLangOpts().Bool) 13638 return; 13639 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 13640 return; 13641 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 13642 } 13643 13644 namespace { 13645 struct AnalyzeImplicitConversionsWorkItem { 13646 Expr *E; 13647 SourceLocation CC; 13648 bool IsListInit; 13649 }; 13650 } 13651 13652 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 13653 /// that should be visited are added to WorkList. 13654 static void AnalyzeImplicitConversions( 13655 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 13656 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 13657 Expr *OrigE = Item.E; 13658 SourceLocation CC = Item.CC; 13659 13660 QualType T = OrigE->getType(); 13661 Expr *E = OrigE->IgnoreParenImpCasts(); 13662 13663 // Propagate whether we are in a C++ list initialization expression. 13664 // If so, we do not issue warnings for implicit int-float conversion 13665 // precision loss, because C++11 narrowing already handles it. 13666 bool IsListInit = Item.IsListInit || 13667 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 13668 13669 if (E->isTypeDependent() || E->isValueDependent()) 13670 return; 13671 13672 Expr *SourceExpr = E; 13673 // Examine, but don't traverse into the source expression of an 13674 // OpaqueValueExpr, since it may have multiple parents and we don't want to 13675 // emit duplicate diagnostics. Its fine to examine the form or attempt to 13676 // evaluate it in the context of checking the specific conversion to T though. 13677 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 13678 if (auto *Src = OVE->getSourceExpr()) 13679 SourceExpr = Src; 13680 13681 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 13682 if (UO->getOpcode() == UO_Not && 13683 UO->getSubExpr()->isKnownToHaveBooleanValue()) 13684 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 13685 << OrigE->getSourceRange() << T->isBooleanType() 13686 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 13687 13688 if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) 13689 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) && 13690 BO->getLHS()->isKnownToHaveBooleanValue() && 13691 BO->getRHS()->isKnownToHaveBooleanValue() && 13692 BO->getLHS()->HasSideEffects(S.Context) && 13693 BO->getRHS()->HasSideEffects(S.Context)) { 13694 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical) 13695 << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange() 13696 << FixItHint::CreateReplacement( 13697 BO->getOperatorLoc(), 13698 (BO->getOpcode() == BO_And ? "&&" : "||")); 13699 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int); 13700 } 13701 13702 // For conditional operators, we analyze the arguments as if they 13703 // were being fed directly into the output. 13704 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 13705 CheckConditionalOperator(S, CO, CC, T); 13706 return; 13707 } 13708 13709 // Check implicit argument conversions for function calls. 13710 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 13711 CheckImplicitArgumentConversions(S, Call, CC); 13712 13713 // Go ahead and check any implicit conversions we might have skipped. 13714 // The non-canonical typecheck is just an optimization; 13715 // CheckImplicitConversion will filter out dead implicit conversions. 13716 if (SourceExpr->getType() != T) 13717 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 13718 13719 // Now continue drilling into this expression. 13720 13721 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 13722 // The bound subexpressions in a PseudoObjectExpr are not reachable 13723 // as transitive children. 13724 // FIXME: Use a more uniform representation for this. 13725 for (auto *SE : POE->semantics()) 13726 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 13727 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 13728 } 13729 13730 // Skip past explicit casts. 13731 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 13732 E = CE->getSubExpr()->IgnoreParenImpCasts(); 13733 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 13734 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 13735 WorkList.push_back({E, CC, IsListInit}); 13736 return; 13737 } 13738 13739 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13740 // Do a somewhat different check with comparison operators. 13741 if (BO->isComparisonOp()) 13742 return AnalyzeComparison(S, BO); 13743 13744 // And with simple assignments. 13745 if (BO->getOpcode() == BO_Assign) 13746 return AnalyzeAssignment(S, BO); 13747 // And with compound assignments. 13748 if (BO->isAssignmentOp()) 13749 return AnalyzeCompoundAssignment(S, BO); 13750 } 13751 13752 // These break the otherwise-useful invariant below. Fortunately, 13753 // we don't really need to recurse into them, because any internal 13754 // expressions should have been analyzed already when they were 13755 // built into statements. 13756 if (isa<StmtExpr>(E)) return; 13757 13758 // Don't descend into unevaluated contexts. 13759 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 13760 13761 // Now just recurse over the expression's children. 13762 CC = E->getExprLoc(); 13763 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 13764 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 13765 for (Stmt *SubStmt : E->children()) { 13766 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 13767 if (!ChildExpr) 13768 continue; 13769 13770 if (IsLogicalAndOperator && 13771 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 13772 // Ignore checking string literals that are in logical and operators. 13773 // This is a common pattern for asserts. 13774 continue; 13775 WorkList.push_back({ChildExpr, CC, IsListInit}); 13776 } 13777 13778 if (BO && BO->isLogicalOp()) { 13779 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 13780 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13781 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13782 13783 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 13784 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13785 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13786 } 13787 13788 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 13789 if (U->getOpcode() == UO_LNot) { 13790 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 13791 } else if (U->getOpcode() != UO_AddrOf) { 13792 if (U->getSubExpr()->getType()->isAtomicType()) 13793 S.Diag(U->getSubExpr()->getBeginLoc(), 13794 diag::warn_atomic_implicit_seq_cst); 13795 } 13796 } 13797 } 13798 13799 /// AnalyzeImplicitConversions - Find and report any interesting 13800 /// implicit conversions in the given expression. There are a couple 13801 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 13802 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 13803 bool IsListInit/*= false*/) { 13804 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 13805 WorkList.push_back({OrigE, CC, IsListInit}); 13806 while (!WorkList.empty()) 13807 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 13808 } 13809 13810 /// Diagnose integer type and any valid implicit conversion to it. 13811 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 13812 // Taking into account implicit conversions, 13813 // allow any integer. 13814 if (!E->getType()->isIntegerType()) { 13815 S.Diag(E->getBeginLoc(), 13816 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 13817 return true; 13818 } 13819 // Potentially emit standard warnings for implicit conversions if enabled 13820 // using -Wconversion. 13821 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 13822 return false; 13823 } 13824 13825 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 13826 // Returns true when emitting a warning about taking the address of a reference. 13827 static bool CheckForReference(Sema &SemaRef, const Expr *E, 13828 const PartialDiagnostic &PD) { 13829 E = E->IgnoreParenImpCasts(); 13830 13831 const FunctionDecl *FD = nullptr; 13832 13833 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13834 if (!DRE->getDecl()->getType()->isReferenceType()) 13835 return false; 13836 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13837 if (!M->getMemberDecl()->getType()->isReferenceType()) 13838 return false; 13839 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 13840 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 13841 return false; 13842 FD = Call->getDirectCallee(); 13843 } else { 13844 return false; 13845 } 13846 13847 SemaRef.Diag(E->getExprLoc(), PD); 13848 13849 // If possible, point to location of function. 13850 if (FD) { 13851 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 13852 } 13853 13854 return true; 13855 } 13856 13857 // Returns true if the SourceLocation is expanded from any macro body. 13858 // Returns false if the SourceLocation is invalid, is from not in a macro 13859 // expansion, or is from expanded from a top-level macro argument. 13860 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 13861 if (Loc.isInvalid()) 13862 return false; 13863 13864 while (Loc.isMacroID()) { 13865 if (SM.isMacroBodyExpansion(Loc)) 13866 return true; 13867 Loc = SM.getImmediateMacroCallerLoc(Loc); 13868 } 13869 13870 return false; 13871 } 13872 13873 /// Diagnose pointers that are always non-null. 13874 /// \param E the expression containing the pointer 13875 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 13876 /// compared to a null pointer 13877 /// \param IsEqual True when the comparison is equal to a null pointer 13878 /// \param Range Extra SourceRange to highlight in the diagnostic 13879 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 13880 Expr::NullPointerConstantKind NullKind, 13881 bool IsEqual, SourceRange Range) { 13882 if (!E) 13883 return; 13884 13885 // Don't warn inside macros. 13886 if (E->getExprLoc().isMacroID()) { 13887 const SourceManager &SM = getSourceManager(); 13888 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 13889 IsInAnyMacroBody(SM, Range.getBegin())) 13890 return; 13891 } 13892 E = E->IgnoreImpCasts(); 13893 13894 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 13895 13896 if (isa<CXXThisExpr>(E)) { 13897 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13898 : diag::warn_this_bool_conversion; 13899 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13900 return; 13901 } 13902 13903 bool IsAddressOf = false; 13904 13905 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13906 if (UO->getOpcode() != UO_AddrOf) 13907 return; 13908 IsAddressOf = true; 13909 E = UO->getSubExpr(); 13910 } 13911 13912 if (IsAddressOf) { 13913 unsigned DiagID = IsCompare 13914 ? diag::warn_address_of_reference_null_compare 13915 : diag::warn_address_of_reference_bool_conversion; 13916 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13917 << IsEqual; 13918 if (CheckForReference(*this, E, PD)) { 13919 return; 13920 } 13921 } 13922 13923 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13924 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13925 std::string Str; 13926 llvm::raw_string_ostream S(Str); 13927 E->printPretty(S, nullptr, getPrintingPolicy()); 13928 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13929 : diag::warn_cast_nonnull_to_bool; 13930 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13931 << E->getSourceRange() << Range << IsEqual; 13932 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13933 }; 13934 13935 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13936 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13937 if (auto *Callee = Call->getDirectCallee()) { 13938 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13939 ComplainAboutNonnullParamOrCall(A); 13940 return; 13941 } 13942 } 13943 } 13944 13945 // Expect to find a single Decl. Skip anything more complicated. 13946 ValueDecl *D = nullptr; 13947 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13948 D = R->getDecl(); 13949 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13950 D = M->getMemberDecl(); 13951 } 13952 13953 // Weak Decls can be null. 13954 if (!D || D->isWeak()) 13955 return; 13956 13957 // Check for parameter decl with nonnull attribute 13958 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13959 if (getCurFunction() && 13960 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13961 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13962 ComplainAboutNonnullParamOrCall(A); 13963 return; 13964 } 13965 13966 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13967 // Skip function template not specialized yet. 13968 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13969 return; 13970 auto ParamIter = llvm::find(FD->parameters(), PV); 13971 assert(ParamIter != FD->param_end()); 13972 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13973 13974 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13975 if (!NonNull->args_size()) { 13976 ComplainAboutNonnullParamOrCall(NonNull); 13977 return; 13978 } 13979 13980 for (const ParamIdx &ArgNo : NonNull->args()) { 13981 if (ArgNo.getASTIndex() == ParamNo) { 13982 ComplainAboutNonnullParamOrCall(NonNull); 13983 return; 13984 } 13985 } 13986 } 13987 } 13988 } 13989 } 13990 13991 QualType T = D->getType(); 13992 const bool IsArray = T->isArrayType(); 13993 const bool IsFunction = T->isFunctionType(); 13994 13995 // Address of function is used to silence the function warning. 13996 if (IsAddressOf && IsFunction) { 13997 return; 13998 } 13999 14000 // Found nothing. 14001 if (!IsAddressOf && !IsFunction && !IsArray) 14002 return; 14003 14004 // Pretty print the expression for the diagnostic. 14005 std::string Str; 14006 llvm::raw_string_ostream S(Str); 14007 E->printPretty(S, nullptr, getPrintingPolicy()); 14008 14009 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 14010 : diag::warn_impcast_pointer_to_bool; 14011 enum { 14012 AddressOf, 14013 FunctionPointer, 14014 ArrayPointer 14015 } DiagType; 14016 if (IsAddressOf) 14017 DiagType = AddressOf; 14018 else if (IsFunction) 14019 DiagType = FunctionPointer; 14020 else if (IsArray) 14021 DiagType = ArrayPointer; 14022 else 14023 llvm_unreachable("Could not determine diagnostic."); 14024 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 14025 << Range << IsEqual; 14026 14027 if (!IsFunction) 14028 return; 14029 14030 // Suggest '&' to silence the function warning. 14031 Diag(E->getExprLoc(), diag::note_function_warning_silence) 14032 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 14033 14034 // Check to see if '()' fixit should be emitted. 14035 QualType ReturnType; 14036 UnresolvedSet<4> NonTemplateOverloads; 14037 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 14038 if (ReturnType.isNull()) 14039 return; 14040 14041 if (IsCompare) { 14042 // There are two cases here. If there is null constant, the only suggest 14043 // for a pointer return type. If the null is 0, then suggest if the return 14044 // type is a pointer or an integer type. 14045 if (!ReturnType->isPointerType()) { 14046 if (NullKind == Expr::NPCK_ZeroExpression || 14047 NullKind == Expr::NPCK_ZeroLiteral) { 14048 if (!ReturnType->isIntegerType()) 14049 return; 14050 } else { 14051 return; 14052 } 14053 } 14054 } else { // !IsCompare 14055 // For function to bool, only suggest if the function pointer has bool 14056 // return type. 14057 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 14058 return; 14059 } 14060 Diag(E->getExprLoc(), diag::note_function_to_function_call) 14061 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 14062 } 14063 14064 /// Diagnoses "dangerous" implicit conversions within the given 14065 /// expression (which is a full expression). Implements -Wconversion 14066 /// and -Wsign-compare. 14067 /// 14068 /// \param CC the "context" location of the implicit conversion, i.e. 14069 /// the most location of the syntactic entity requiring the implicit 14070 /// conversion 14071 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 14072 // Don't diagnose in unevaluated contexts. 14073 if (isUnevaluatedContext()) 14074 return; 14075 14076 // Don't diagnose for value- or type-dependent expressions. 14077 if (E->isTypeDependent() || E->isValueDependent()) 14078 return; 14079 14080 // Check for array bounds violations in cases where the check isn't triggered 14081 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 14082 // ArraySubscriptExpr is on the RHS of a variable initialization. 14083 CheckArrayAccess(E); 14084 14085 // This is not the right CC for (e.g.) a variable initialization. 14086 AnalyzeImplicitConversions(*this, E, CC); 14087 } 14088 14089 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 14090 /// Input argument E is a logical expression. 14091 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 14092 ::CheckBoolLikeConversion(*this, E, CC); 14093 } 14094 14095 /// Diagnose when expression is an integer constant expression and its evaluation 14096 /// results in integer overflow 14097 void Sema::CheckForIntOverflow (Expr *E) { 14098 // Use a work list to deal with nested struct initializers. 14099 SmallVector<Expr *, 2> Exprs(1, E); 14100 14101 do { 14102 Expr *OriginalE = Exprs.pop_back_val(); 14103 Expr *E = OriginalE->IgnoreParenCasts(); 14104 14105 if (isa<BinaryOperator>(E)) { 14106 E->EvaluateForOverflow(Context); 14107 continue; 14108 } 14109 14110 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 14111 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 14112 else if (isa<ObjCBoxedExpr>(OriginalE)) 14113 E->EvaluateForOverflow(Context); 14114 else if (auto Call = dyn_cast<CallExpr>(E)) 14115 Exprs.append(Call->arg_begin(), Call->arg_end()); 14116 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 14117 Exprs.append(Message->arg_begin(), Message->arg_end()); 14118 } while (!Exprs.empty()); 14119 } 14120 14121 namespace { 14122 14123 /// Visitor for expressions which looks for unsequenced operations on the 14124 /// same object. 14125 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 14126 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 14127 14128 /// A tree of sequenced regions within an expression. Two regions are 14129 /// unsequenced if one is an ancestor or a descendent of the other. When we 14130 /// finish processing an expression with sequencing, such as a comma 14131 /// expression, we fold its tree nodes into its parent, since they are 14132 /// unsequenced with respect to nodes we will visit later. 14133 class SequenceTree { 14134 struct Value { 14135 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 14136 unsigned Parent : 31; 14137 unsigned Merged : 1; 14138 }; 14139 SmallVector<Value, 8> Values; 14140 14141 public: 14142 /// A region within an expression which may be sequenced with respect 14143 /// to some other region. 14144 class Seq { 14145 friend class SequenceTree; 14146 14147 unsigned Index; 14148 14149 explicit Seq(unsigned N) : Index(N) {} 14150 14151 public: 14152 Seq() : Index(0) {} 14153 }; 14154 14155 SequenceTree() { Values.push_back(Value(0)); } 14156 Seq root() const { return Seq(0); } 14157 14158 /// Create a new sequence of operations, which is an unsequenced 14159 /// subset of \p Parent. This sequence of operations is sequenced with 14160 /// respect to other children of \p Parent. 14161 Seq allocate(Seq Parent) { 14162 Values.push_back(Value(Parent.Index)); 14163 return Seq(Values.size() - 1); 14164 } 14165 14166 /// Merge a sequence of operations into its parent. 14167 void merge(Seq S) { 14168 Values[S.Index].Merged = true; 14169 } 14170 14171 /// Determine whether two operations are unsequenced. This operation 14172 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 14173 /// should have been merged into its parent as appropriate. 14174 bool isUnsequenced(Seq Cur, Seq Old) { 14175 unsigned C = representative(Cur.Index); 14176 unsigned Target = representative(Old.Index); 14177 while (C >= Target) { 14178 if (C == Target) 14179 return true; 14180 C = Values[C].Parent; 14181 } 14182 return false; 14183 } 14184 14185 private: 14186 /// Pick a representative for a sequence. 14187 unsigned representative(unsigned K) { 14188 if (Values[K].Merged) 14189 // Perform path compression as we go. 14190 return Values[K].Parent = representative(Values[K].Parent); 14191 return K; 14192 } 14193 }; 14194 14195 /// An object for which we can track unsequenced uses. 14196 using Object = const NamedDecl *; 14197 14198 /// Different flavors of object usage which we track. We only track the 14199 /// least-sequenced usage of each kind. 14200 enum UsageKind { 14201 /// A read of an object. Multiple unsequenced reads are OK. 14202 UK_Use, 14203 14204 /// A modification of an object which is sequenced before the value 14205 /// computation of the expression, such as ++n in C++. 14206 UK_ModAsValue, 14207 14208 /// A modification of an object which is not sequenced before the value 14209 /// computation of the expression, such as n++. 14210 UK_ModAsSideEffect, 14211 14212 UK_Count = UK_ModAsSideEffect + 1 14213 }; 14214 14215 /// Bundle together a sequencing region and the expression corresponding 14216 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 14217 struct Usage { 14218 const Expr *UsageExpr; 14219 SequenceTree::Seq Seq; 14220 14221 Usage() : UsageExpr(nullptr) {} 14222 }; 14223 14224 struct UsageInfo { 14225 Usage Uses[UK_Count]; 14226 14227 /// Have we issued a diagnostic for this object already? 14228 bool Diagnosed; 14229 14230 UsageInfo() : Diagnosed(false) {} 14231 }; 14232 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 14233 14234 Sema &SemaRef; 14235 14236 /// Sequenced regions within the expression. 14237 SequenceTree Tree; 14238 14239 /// Declaration modifications and references which we have seen. 14240 UsageInfoMap UsageMap; 14241 14242 /// The region we are currently within. 14243 SequenceTree::Seq Region; 14244 14245 /// Filled in with declarations which were modified as a side-effect 14246 /// (that is, post-increment operations). 14247 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 14248 14249 /// Expressions to check later. We defer checking these to reduce 14250 /// stack usage. 14251 SmallVectorImpl<const Expr *> &WorkList; 14252 14253 /// RAII object wrapping the visitation of a sequenced subexpression of an 14254 /// expression. At the end of this process, the side-effects of the evaluation 14255 /// become sequenced with respect to the value computation of the result, so 14256 /// we downgrade any UK_ModAsSideEffect within the evaluation to 14257 /// UK_ModAsValue. 14258 struct SequencedSubexpression { 14259 SequencedSubexpression(SequenceChecker &Self) 14260 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 14261 Self.ModAsSideEffect = &ModAsSideEffect; 14262 } 14263 14264 ~SequencedSubexpression() { 14265 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 14266 // Add a new usage with usage kind UK_ModAsValue, and then restore 14267 // the previous usage with UK_ModAsSideEffect (thus clearing it if 14268 // the previous one was empty). 14269 UsageInfo &UI = Self.UsageMap[M.first]; 14270 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 14271 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 14272 SideEffectUsage = M.second; 14273 } 14274 Self.ModAsSideEffect = OldModAsSideEffect; 14275 } 14276 14277 SequenceChecker &Self; 14278 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 14279 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 14280 }; 14281 14282 /// RAII object wrapping the visitation of a subexpression which we might 14283 /// choose to evaluate as a constant. If any subexpression is evaluated and 14284 /// found to be non-constant, this allows us to suppress the evaluation of 14285 /// the outer expression. 14286 class EvaluationTracker { 14287 public: 14288 EvaluationTracker(SequenceChecker &Self) 14289 : Self(Self), Prev(Self.EvalTracker) { 14290 Self.EvalTracker = this; 14291 } 14292 14293 ~EvaluationTracker() { 14294 Self.EvalTracker = Prev; 14295 if (Prev) 14296 Prev->EvalOK &= EvalOK; 14297 } 14298 14299 bool evaluate(const Expr *E, bool &Result) { 14300 if (!EvalOK || E->isValueDependent()) 14301 return false; 14302 EvalOK = E->EvaluateAsBooleanCondition( 14303 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 14304 return EvalOK; 14305 } 14306 14307 private: 14308 SequenceChecker &Self; 14309 EvaluationTracker *Prev; 14310 bool EvalOK = true; 14311 } *EvalTracker = nullptr; 14312 14313 /// Find the object which is produced by the specified expression, 14314 /// if any. 14315 Object getObject(const Expr *E, bool Mod) const { 14316 E = E->IgnoreParenCasts(); 14317 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 14318 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 14319 return getObject(UO->getSubExpr(), Mod); 14320 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 14321 if (BO->getOpcode() == BO_Comma) 14322 return getObject(BO->getRHS(), Mod); 14323 if (Mod && BO->isAssignmentOp()) 14324 return getObject(BO->getLHS(), Mod); 14325 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14326 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 14327 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 14328 return ME->getMemberDecl(); 14329 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 14330 // FIXME: If this is a reference, map through to its value. 14331 return DRE->getDecl(); 14332 return nullptr; 14333 } 14334 14335 /// Note that an object \p O was modified or used by an expression 14336 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 14337 /// the object \p O as obtained via the \p UsageMap. 14338 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 14339 // Get the old usage for the given object and usage kind. 14340 Usage &U = UI.Uses[UK]; 14341 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 14342 // If we have a modification as side effect and are in a sequenced 14343 // subexpression, save the old Usage so that we can restore it later 14344 // in SequencedSubexpression::~SequencedSubexpression. 14345 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 14346 ModAsSideEffect->push_back(std::make_pair(O, U)); 14347 // Then record the new usage with the current sequencing region. 14348 U.UsageExpr = UsageExpr; 14349 U.Seq = Region; 14350 } 14351 } 14352 14353 /// Check whether a modification or use of an object \p O in an expression 14354 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 14355 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 14356 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 14357 /// usage and false we are checking for a mod-use unsequenced usage. 14358 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 14359 UsageKind OtherKind, bool IsModMod) { 14360 if (UI.Diagnosed) 14361 return; 14362 14363 const Usage &U = UI.Uses[OtherKind]; 14364 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 14365 return; 14366 14367 const Expr *Mod = U.UsageExpr; 14368 const Expr *ModOrUse = UsageExpr; 14369 if (OtherKind == UK_Use) 14370 std::swap(Mod, ModOrUse); 14371 14372 SemaRef.DiagRuntimeBehavior( 14373 Mod->getExprLoc(), {Mod, ModOrUse}, 14374 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 14375 : diag::warn_unsequenced_mod_use) 14376 << O << SourceRange(ModOrUse->getExprLoc())); 14377 UI.Diagnosed = true; 14378 } 14379 14380 // A note on note{Pre, Post}{Use, Mod}: 14381 // 14382 // (It helps to follow the algorithm with an expression such as 14383 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 14384 // operations before C++17 and both are well-defined in C++17). 14385 // 14386 // When visiting a node which uses/modify an object we first call notePreUse 14387 // or notePreMod before visiting its sub-expression(s). At this point the 14388 // children of the current node have not yet been visited and so the eventual 14389 // uses/modifications resulting from the children of the current node have not 14390 // been recorded yet. 14391 // 14392 // We then visit the children of the current node. After that notePostUse or 14393 // notePostMod is called. These will 1) detect an unsequenced modification 14394 // as side effect (as in "k++ + k") and 2) add a new usage with the 14395 // appropriate usage kind. 14396 // 14397 // We also have to be careful that some operation sequences modification as 14398 // side effect as well (for example: || or ,). To account for this we wrap 14399 // the visitation of such a sub-expression (for example: the LHS of || or ,) 14400 // with SequencedSubexpression. SequencedSubexpression is an RAII object 14401 // which record usages which are modifications as side effect, and then 14402 // downgrade them (or more accurately restore the previous usage which was a 14403 // modification as side effect) when exiting the scope of the sequenced 14404 // subexpression. 14405 14406 void notePreUse(Object O, const Expr *UseExpr) { 14407 UsageInfo &UI = UsageMap[O]; 14408 // Uses conflict with other modifications. 14409 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 14410 } 14411 14412 void notePostUse(Object O, const Expr *UseExpr) { 14413 UsageInfo &UI = UsageMap[O]; 14414 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 14415 /*IsModMod=*/false); 14416 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 14417 } 14418 14419 void notePreMod(Object O, const Expr *ModExpr) { 14420 UsageInfo &UI = UsageMap[O]; 14421 // Modifications conflict with other modifications and with uses. 14422 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 14423 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 14424 } 14425 14426 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 14427 UsageInfo &UI = UsageMap[O]; 14428 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 14429 /*IsModMod=*/true); 14430 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 14431 } 14432 14433 public: 14434 SequenceChecker(Sema &S, const Expr *E, 14435 SmallVectorImpl<const Expr *> &WorkList) 14436 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 14437 Visit(E); 14438 // Silence a -Wunused-private-field since WorkList is now unused. 14439 // TODO: Evaluate if it can be used, and if not remove it. 14440 (void)this->WorkList; 14441 } 14442 14443 void VisitStmt(const Stmt *S) { 14444 // Skip all statements which aren't expressions for now. 14445 } 14446 14447 void VisitExpr(const Expr *E) { 14448 // By default, just recurse to evaluated subexpressions. 14449 Base::VisitStmt(E); 14450 } 14451 14452 void VisitCastExpr(const CastExpr *E) { 14453 Object O = Object(); 14454 if (E->getCastKind() == CK_LValueToRValue) 14455 O = getObject(E->getSubExpr(), false); 14456 14457 if (O) 14458 notePreUse(O, E); 14459 VisitExpr(E); 14460 if (O) 14461 notePostUse(O, E); 14462 } 14463 14464 void VisitSequencedExpressions(const Expr *SequencedBefore, 14465 const Expr *SequencedAfter) { 14466 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 14467 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 14468 SequenceTree::Seq OldRegion = Region; 14469 14470 { 14471 SequencedSubexpression SeqBefore(*this); 14472 Region = BeforeRegion; 14473 Visit(SequencedBefore); 14474 } 14475 14476 Region = AfterRegion; 14477 Visit(SequencedAfter); 14478 14479 Region = OldRegion; 14480 14481 Tree.merge(BeforeRegion); 14482 Tree.merge(AfterRegion); 14483 } 14484 14485 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 14486 // C++17 [expr.sub]p1: 14487 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 14488 // expression E1 is sequenced before the expression E2. 14489 if (SemaRef.getLangOpts().CPlusPlus17) 14490 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 14491 else { 14492 Visit(ASE->getLHS()); 14493 Visit(ASE->getRHS()); 14494 } 14495 } 14496 14497 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14498 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14499 void VisitBinPtrMem(const BinaryOperator *BO) { 14500 // C++17 [expr.mptr.oper]p4: 14501 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 14502 // the expression E1 is sequenced before the expression E2. 14503 if (SemaRef.getLangOpts().CPlusPlus17) 14504 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14505 else { 14506 Visit(BO->getLHS()); 14507 Visit(BO->getRHS()); 14508 } 14509 } 14510 14511 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14512 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14513 void VisitBinShlShr(const BinaryOperator *BO) { 14514 // C++17 [expr.shift]p4: 14515 // The expression E1 is sequenced before the expression E2. 14516 if (SemaRef.getLangOpts().CPlusPlus17) 14517 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14518 else { 14519 Visit(BO->getLHS()); 14520 Visit(BO->getRHS()); 14521 } 14522 } 14523 14524 void VisitBinComma(const BinaryOperator *BO) { 14525 // C++11 [expr.comma]p1: 14526 // Every value computation and side effect associated with the left 14527 // expression is sequenced before every value computation and side 14528 // effect associated with the right expression. 14529 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14530 } 14531 14532 void VisitBinAssign(const BinaryOperator *BO) { 14533 SequenceTree::Seq RHSRegion; 14534 SequenceTree::Seq LHSRegion; 14535 if (SemaRef.getLangOpts().CPlusPlus17) { 14536 RHSRegion = Tree.allocate(Region); 14537 LHSRegion = Tree.allocate(Region); 14538 } else { 14539 RHSRegion = Region; 14540 LHSRegion = Region; 14541 } 14542 SequenceTree::Seq OldRegion = Region; 14543 14544 // C++11 [expr.ass]p1: 14545 // [...] the assignment is sequenced after the value computation 14546 // of the right and left operands, [...] 14547 // 14548 // so check it before inspecting the operands and update the 14549 // map afterwards. 14550 Object O = getObject(BO->getLHS(), /*Mod=*/true); 14551 if (O) 14552 notePreMod(O, BO); 14553 14554 if (SemaRef.getLangOpts().CPlusPlus17) { 14555 // C++17 [expr.ass]p1: 14556 // [...] The right operand is sequenced before the left operand. [...] 14557 { 14558 SequencedSubexpression SeqBefore(*this); 14559 Region = RHSRegion; 14560 Visit(BO->getRHS()); 14561 } 14562 14563 Region = LHSRegion; 14564 Visit(BO->getLHS()); 14565 14566 if (O && isa<CompoundAssignOperator>(BO)) 14567 notePostUse(O, BO); 14568 14569 } else { 14570 // C++11 does not specify any sequencing between the LHS and RHS. 14571 Region = LHSRegion; 14572 Visit(BO->getLHS()); 14573 14574 if (O && isa<CompoundAssignOperator>(BO)) 14575 notePostUse(O, BO); 14576 14577 Region = RHSRegion; 14578 Visit(BO->getRHS()); 14579 } 14580 14581 // C++11 [expr.ass]p1: 14582 // the assignment is sequenced [...] before the value computation of the 14583 // assignment expression. 14584 // C11 6.5.16/3 has no such rule. 14585 Region = OldRegion; 14586 if (O) 14587 notePostMod(O, BO, 14588 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14589 : UK_ModAsSideEffect); 14590 if (SemaRef.getLangOpts().CPlusPlus17) { 14591 Tree.merge(RHSRegion); 14592 Tree.merge(LHSRegion); 14593 } 14594 } 14595 14596 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 14597 VisitBinAssign(CAO); 14598 } 14599 14600 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14601 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14602 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 14603 Object O = getObject(UO->getSubExpr(), true); 14604 if (!O) 14605 return VisitExpr(UO); 14606 14607 notePreMod(O, UO); 14608 Visit(UO->getSubExpr()); 14609 // C++11 [expr.pre.incr]p1: 14610 // the expression ++x is equivalent to x+=1 14611 notePostMod(O, UO, 14612 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14613 : UK_ModAsSideEffect); 14614 } 14615 14616 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14617 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14618 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 14619 Object O = getObject(UO->getSubExpr(), true); 14620 if (!O) 14621 return VisitExpr(UO); 14622 14623 notePreMod(O, UO); 14624 Visit(UO->getSubExpr()); 14625 notePostMod(O, UO, UK_ModAsSideEffect); 14626 } 14627 14628 void VisitBinLOr(const BinaryOperator *BO) { 14629 // C++11 [expr.log.or]p2: 14630 // If the second expression is evaluated, every value computation and 14631 // side effect associated with the first expression is sequenced before 14632 // every value computation and side effect associated with the 14633 // second expression. 14634 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14635 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14636 SequenceTree::Seq OldRegion = Region; 14637 14638 EvaluationTracker Eval(*this); 14639 { 14640 SequencedSubexpression Sequenced(*this); 14641 Region = LHSRegion; 14642 Visit(BO->getLHS()); 14643 } 14644 14645 // C++11 [expr.log.or]p1: 14646 // [...] the second operand is not evaluated if the first operand 14647 // evaluates to true. 14648 bool EvalResult = false; 14649 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14650 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 14651 if (ShouldVisitRHS) { 14652 Region = RHSRegion; 14653 Visit(BO->getRHS()); 14654 } 14655 14656 Region = OldRegion; 14657 Tree.merge(LHSRegion); 14658 Tree.merge(RHSRegion); 14659 } 14660 14661 void VisitBinLAnd(const BinaryOperator *BO) { 14662 // C++11 [expr.log.and]p2: 14663 // If the second expression is evaluated, every value computation and 14664 // side effect associated with the first expression is sequenced before 14665 // every value computation and side effect associated with the 14666 // second expression. 14667 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14668 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14669 SequenceTree::Seq OldRegion = Region; 14670 14671 EvaluationTracker Eval(*this); 14672 { 14673 SequencedSubexpression Sequenced(*this); 14674 Region = LHSRegion; 14675 Visit(BO->getLHS()); 14676 } 14677 14678 // C++11 [expr.log.and]p1: 14679 // [...] the second operand is not evaluated if the first operand is false. 14680 bool EvalResult = false; 14681 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14682 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 14683 if (ShouldVisitRHS) { 14684 Region = RHSRegion; 14685 Visit(BO->getRHS()); 14686 } 14687 14688 Region = OldRegion; 14689 Tree.merge(LHSRegion); 14690 Tree.merge(RHSRegion); 14691 } 14692 14693 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 14694 // C++11 [expr.cond]p1: 14695 // [...] Every value computation and side effect associated with the first 14696 // expression is sequenced before every value computation and side effect 14697 // associated with the second or third expression. 14698 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 14699 14700 // No sequencing is specified between the true and false expression. 14701 // However since exactly one of both is going to be evaluated we can 14702 // consider them to be sequenced. This is needed to avoid warning on 14703 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 14704 // both the true and false expressions because we can't evaluate x. 14705 // This will still allow us to detect an expression like (pre C++17) 14706 // "(x ? y += 1 : y += 2) = y". 14707 // 14708 // We don't wrap the visitation of the true and false expression with 14709 // SequencedSubexpression because we don't want to downgrade modifications 14710 // as side effect in the true and false expressions after the visition 14711 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 14712 // not warn between the two "y++", but we should warn between the "y++" 14713 // and the "y". 14714 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 14715 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 14716 SequenceTree::Seq OldRegion = Region; 14717 14718 EvaluationTracker Eval(*this); 14719 { 14720 SequencedSubexpression Sequenced(*this); 14721 Region = ConditionRegion; 14722 Visit(CO->getCond()); 14723 } 14724 14725 // C++11 [expr.cond]p1: 14726 // [...] The first expression is contextually converted to bool (Clause 4). 14727 // It is evaluated and if it is true, the result of the conditional 14728 // expression is the value of the second expression, otherwise that of the 14729 // third expression. Only one of the second and third expressions is 14730 // evaluated. [...] 14731 bool EvalResult = false; 14732 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 14733 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 14734 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 14735 if (ShouldVisitTrueExpr) { 14736 Region = TrueRegion; 14737 Visit(CO->getTrueExpr()); 14738 } 14739 if (ShouldVisitFalseExpr) { 14740 Region = FalseRegion; 14741 Visit(CO->getFalseExpr()); 14742 } 14743 14744 Region = OldRegion; 14745 Tree.merge(ConditionRegion); 14746 Tree.merge(TrueRegion); 14747 Tree.merge(FalseRegion); 14748 } 14749 14750 void VisitCallExpr(const CallExpr *CE) { 14751 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 14752 14753 if (CE->isUnevaluatedBuiltinCall(Context)) 14754 return; 14755 14756 // C++11 [intro.execution]p15: 14757 // When calling a function [...], every value computation and side effect 14758 // associated with any argument expression, or with the postfix expression 14759 // designating the called function, is sequenced before execution of every 14760 // expression or statement in the body of the function [and thus before 14761 // the value computation of its result]. 14762 SequencedSubexpression Sequenced(*this); 14763 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 14764 // C++17 [expr.call]p5 14765 // The postfix-expression is sequenced before each expression in the 14766 // expression-list and any default argument. [...] 14767 SequenceTree::Seq CalleeRegion; 14768 SequenceTree::Seq OtherRegion; 14769 if (SemaRef.getLangOpts().CPlusPlus17) { 14770 CalleeRegion = Tree.allocate(Region); 14771 OtherRegion = Tree.allocate(Region); 14772 } else { 14773 CalleeRegion = Region; 14774 OtherRegion = Region; 14775 } 14776 SequenceTree::Seq OldRegion = Region; 14777 14778 // Visit the callee expression first. 14779 Region = CalleeRegion; 14780 if (SemaRef.getLangOpts().CPlusPlus17) { 14781 SequencedSubexpression Sequenced(*this); 14782 Visit(CE->getCallee()); 14783 } else { 14784 Visit(CE->getCallee()); 14785 } 14786 14787 // Then visit the argument expressions. 14788 Region = OtherRegion; 14789 for (const Expr *Argument : CE->arguments()) 14790 Visit(Argument); 14791 14792 Region = OldRegion; 14793 if (SemaRef.getLangOpts().CPlusPlus17) { 14794 Tree.merge(CalleeRegion); 14795 Tree.merge(OtherRegion); 14796 } 14797 }); 14798 } 14799 14800 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 14801 // C++17 [over.match.oper]p2: 14802 // [...] the operator notation is first transformed to the equivalent 14803 // function-call notation as summarized in Table 12 (where @ denotes one 14804 // of the operators covered in the specified subclause). However, the 14805 // operands are sequenced in the order prescribed for the built-in 14806 // operator (Clause 8). 14807 // 14808 // From the above only overloaded binary operators and overloaded call 14809 // operators have sequencing rules in C++17 that we need to handle 14810 // separately. 14811 if (!SemaRef.getLangOpts().CPlusPlus17 || 14812 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 14813 return VisitCallExpr(CXXOCE); 14814 14815 enum { 14816 NoSequencing, 14817 LHSBeforeRHS, 14818 RHSBeforeLHS, 14819 LHSBeforeRest 14820 } SequencingKind; 14821 switch (CXXOCE->getOperator()) { 14822 case OO_Equal: 14823 case OO_PlusEqual: 14824 case OO_MinusEqual: 14825 case OO_StarEqual: 14826 case OO_SlashEqual: 14827 case OO_PercentEqual: 14828 case OO_CaretEqual: 14829 case OO_AmpEqual: 14830 case OO_PipeEqual: 14831 case OO_LessLessEqual: 14832 case OO_GreaterGreaterEqual: 14833 SequencingKind = RHSBeforeLHS; 14834 break; 14835 14836 case OO_LessLess: 14837 case OO_GreaterGreater: 14838 case OO_AmpAmp: 14839 case OO_PipePipe: 14840 case OO_Comma: 14841 case OO_ArrowStar: 14842 case OO_Subscript: 14843 SequencingKind = LHSBeforeRHS; 14844 break; 14845 14846 case OO_Call: 14847 SequencingKind = LHSBeforeRest; 14848 break; 14849 14850 default: 14851 SequencingKind = NoSequencing; 14852 break; 14853 } 14854 14855 if (SequencingKind == NoSequencing) 14856 return VisitCallExpr(CXXOCE); 14857 14858 // This is a call, so all subexpressions are sequenced before the result. 14859 SequencedSubexpression Sequenced(*this); 14860 14861 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 14862 assert(SemaRef.getLangOpts().CPlusPlus17 && 14863 "Should only get there with C++17 and above!"); 14864 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 14865 "Should only get there with an overloaded binary operator" 14866 " or an overloaded call operator!"); 14867 14868 if (SequencingKind == LHSBeforeRest) { 14869 assert(CXXOCE->getOperator() == OO_Call && 14870 "We should only have an overloaded call operator here!"); 14871 14872 // This is very similar to VisitCallExpr, except that we only have the 14873 // C++17 case. The postfix-expression is the first argument of the 14874 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 14875 // are in the following arguments. 14876 // 14877 // Note that we intentionally do not visit the callee expression since 14878 // it is just a decayed reference to a function. 14879 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 14880 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 14881 SequenceTree::Seq OldRegion = Region; 14882 14883 assert(CXXOCE->getNumArgs() >= 1 && 14884 "An overloaded call operator must have at least one argument" 14885 " for the postfix-expression!"); 14886 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 14887 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 14888 CXXOCE->getNumArgs() - 1); 14889 14890 // Visit the postfix-expression first. 14891 { 14892 Region = PostfixExprRegion; 14893 SequencedSubexpression Sequenced(*this); 14894 Visit(PostfixExpr); 14895 } 14896 14897 // Then visit the argument expressions. 14898 Region = ArgsRegion; 14899 for (const Expr *Arg : Args) 14900 Visit(Arg); 14901 14902 Region = OldRegion; 14903 Tree.merge(PostfixExprRegion); 14904 Tree.merge(ArgsRegion); 14905 } else { 14906 assert(CXXOCE->getNumArgs() == 2 && 14907 "Should only have two arguments here!"); 14908 assert((SequencingKind == LHSBeforeRHS || 14909 SequencingKind == RHSBeforeLHS) && 14910 "Unexpected sequencing kind!"); 14911 14912 // We do not visit the callee expression since it is just a decayed 14913 // reference to a function. 14914 const Expr *E1 = CXXOCE->getArg(0); 14915 const Expr *E2 = CXXOCE->getArg(1); 14916 if (SequencingKind == RHSBeforeLHS) 14917 std::swap(E1, E2); 14918 14919 return VisitSequencedExpressions(E1, E2); 14920 } 14921 }); 14922 } 14923 14924 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14925 // This is a call, so all subexpressions are sequenced before the result. 14926 SequencedSubexpression Sequenced(*this); 14927 14928 if (!CCE->isListInitialization()) 14929 return VisitExpr(CCE); 14930 14931 // In C++11, list initializations are sequenced. 14932 SmallVector<SequenceTree::Seq, 32> Elts; 14933 SequenceTree::Seq Parent = Region; 14934 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14935 E = CCE->arg_end(); 14936 I != E; ++I) { 14937 Region = Tree.allocate(Parent); 14938 Elts.push_back(Region); 14939 Visit(*I); 14940 } 14941 14942 // Forget that the initializers are sequenced. 14943 Region = Parent; 14944 for (unsigned I = 0; I < Elts.size(); ++I) 14945 Tree.merge(Elts[I]); 14946 } 14947 14948 void VisitInitListExpr(const InitListExpr *ILE) { 14949 if (!SemaRef.getLangOpts().CPlusPlus11) 14950 return VisitExpr(ILE); 14951 14952 // In C++11, list initializations are sequenced. 14953 SmallVector<SequenceTree::Seq, 32> Elts; 14954 SequenceTree::Seq Parent = Region; 14955 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14956 const Expr *E = ILE->getInit(I); 14957 if (!E) 14958 continue; 14959 Region = Tree.allocate(Parent); 14960 Elts.push_back(Region); 14961 Visit(E); 14962 } 14963 14964 // Forget that the initializers are sequenced. 14965 Region = Parent; 14966 for (unsigned I = 0; I < Elts.size(); ++I) 14967 Tree.merge(Elts[I]); 14968 } 14969 }; 14970 14971 } // namespace 14972 14973 void Sema::CheckUnsequencedOperations(const Expr *E) { 14974 SmallVector<const Expr *, 8> WorkList; 14975 WorkList.push_back(E); 14976 while (!WorkList.empty()) { 14977 const Expr *Item = WorkList.pop_back_val(); 14978 SequenceChecker(*this, Item, WorkList); 14979 } 14980 } 14981 14982 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14983 bool IsConstexpr) { 14984 llvm::SaveAndRestore<bool> ConstantContext( 14985 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14986 CheckImplicitConversions(E, CheckLoc); 14987 if (!E->isInstantiationDependent()) 14988 CheckUnsequencedOperations(E); 14989 if (!IsConstexpr && !E->isValueDependent()) 14990 CheckForIntOverflow(E); 14991 DiagnoseMisalignedMembers(); 14992 } 14993 14994 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14995 FieldDecl *BitField, 14996 Expr *Init) { 14997 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14998 } 14999 15000 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 15001 SourceLocation Loc) { 15002 if (!PType->isVariablyModifiedType()) 15003 return; 15004 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 15005 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 15006 return; 15007 } 15008 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 15009 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 15010 return; 15011 } 15012 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 15013 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 15014 return; 15015 } 15016 15017 const ArrayType *AT = S.Context.getAsArrayType(PType); 15018 if (!AT) 15019 return; 15020 15021 if (AT->getSizeModifier() != ArrayType::Star) { 15022 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 15023 return; 15024 } 15025 15026 S.Diag(Loc, diag::err_array_star_in_function_definition); 15027 } 15028 15029 /// CheckParmsForFunctionDef - Check that the parameters of the given 15030 /// function are appropriate for the definition of a function. This 15031 /// takes care of any checks that cannot be performed on the 15032 /// declaration itself, e.g., that the types of each of the function 15033 /// parameters are complete. 15034 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 15035 bool CheckParameterNames) { 15036 bool HasInvalidParm = false; 15037 for (ParmVarDecl *Param : Parameters) { 15038 // C99 6.7.5.3p4: the parameters in a parameter type list in a 15039 // function declarator that is part of a function definition of 15040 // that function shall not have incomplete type. 15041 // 15042 // This is also C++ [dcl.fct]p6. 15043 if (!Param->isInvalidDecl() && 15044 RequireCompleteType(Param->getLocation(), Param->getType(), 15045 diag::err_typecheck_decl_incomplete_type)) { 15046 Param->setInvalidDecl(); 15047 HasInvalidParm = true; 15048 } 15049 15050 // C99 6.9.1p5: If the declarator includes a parameter type list, the 15051 // declaration of each parameter shall include an identifier. 15052 if (CheckParameterNames && Param->getIdentifier() == nullptr && 15053 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 15054 // Diagnose this as an extension in C17 and earlier. 15055 if (!getLangOpts().C2x) 15056 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15057 } 15058 15059 // C99 6.7.5.3p12: 15060 // If the function declarator is not part of a definition of that 15061 // function, parameters may have incomplete type and may use the [*] 15062 // notation in their sequences of declarator specifiers to specify 15063 // variable length array types. 15064 QualType PType = Param->getOriginalType(); 15065 // FIXME: This diagnostic should point the '[*]' if source-location 15066 // information is added for it. 15067 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 15068 15069 // If the parameter is a c++ class type and it has to be destructed in the 15070 // callee function, declare the destructor so that it can be called by the 15071 // callee function. Do not perform any direct access check on the dtor here. 15072 if (!Param->isInvalidDecl()) { 15073 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 15074 if (!ClassDecl->isInvalidDecl() && 15075 !ClassDecl->hasIrrelevantDestructor() && 15076 !ClassDecl->isDependentContext() && 15077 ClassDecl->isParamDestroyedInCallee()) { 15078 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15079 MarkFunctionReferenced(Param->getLocation(), Destructor); 15080 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 15081 } 15082 } 15083 } 15084 15085 // Parameters with the pass_object_size attribute only need to be marked 15086 // constant at function definitions. Because we lack information about 15087 // whether we're on a declaration or definition when we're instantiating the 15088 // attribute, we need to check for constness here. 15089 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 15090 if (!Param->getType().isConstQualified()) 15091 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 15092 << Attr->getSpelling() << 1; 15093 15094 // Check for parameter names shadowing fields from the class. 15095 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 15096 // The owning context for the parameter should be the function, but we 15097 // want to see if this function's declaration context is a record. 15098 DeclContext *DC = Param->getDeclContext(); 15099 if (DC && DC->isFunctionOrMethod()) { 15100 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 15101 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 15102 RD, /*DeclIsField*/ false); 15103 } 15104 } 15105 } 15106 15107 return HasInvalidParm; 15108 } 15109 15110 Optional<std::pair<CharUnits, CharUnits>> 15111 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 15112 15113 /// Compute the alignment and offset of the base class object given the 15114 /// derived-to-base cast expression and the alignment and offset of the derived 15115 /// class object. 15116 static std::pair<CharUnits, CharUnits> 15117 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 15118 CharUnits BaseAlignment, CharUnits Offset, 15119 ASTContext &Ctx) { 15120 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 15121 ++PathI) { 15122 const CXXBaseSpecifier *Base = *PathI; 15123 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 15124 if (Base->isVirtual()) { 15125 // The complete object may have a lower alignment than the non-virtual 15126 // alignment of the base, in which case the base may be misaligned. Choose 15127 // the smaller of the non-virtual alignment and BaseAlignment, which is a 15128 // conservative lower bound of the complete object alignment. 15129 CharUnits NonVirtualAlignment = 15130 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 15131 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 15132 Offset = CharUnits::Zero(); 15133 } else { 15134 const ASTRecordLayout &RL = 15135 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 15136 Offset += RL.getBaseClassOffset(BaseDecl); 15137 } 15138 DerivedType = Base->getType(); 15139 } 15140 15141 return std::make_pair(BaseAlignment, Offset); 15142 } 15143 15144 /// Compute the alignment and offset of a binary additive operator. 15145 static Optional<std::pair<CharUnits, CharUnits>> 15146 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 15147 bool IsSub, ASTContext &Ctx) { 15148 QualType PointeeType = PtrE->getType()->getPointeeType(); 15149 15150 if (!PointeeType->isConstantSizeType()) 15151 return llvm::None; 15152 15153 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 15154 15155 if (!P) 15156 return llvm::None; 15157 15158 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 15159 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 15160 CharUnits Offset = EltSize * IdxRes->getExtValue(); 15161 if (IsSub) 15162 Offset = -Offset; 15163 return std::make_pair(P->first, P->second + Offset); 15164 } 15165 15166 // If the integer expression isn't a constant expression, compute the lower 15167 // bound of the alignment using the alignment and offset of the pointer 15168 // expression and the element size. 15169 return std::make_pair( 15170 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 15171 CharUnits::Zero()); 15172 } 15173 15174 /// This helper function takes an lvalue expression and returns the alignment of 15175 /// a VarDecl and a constant offset from the VarDecl. 15176 Optional<std::pair<CharUnits, CharUnits>> 15177 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 15178 E = E->IgnoreParens(); 15179 switch (E->getStmtClass()) { 15180 default: 15181 break; 15182 case Stmt::CStyleCastExprClass: 15183 case Stmt::CXXStaticCastExprClass: 15184 case Stmt::ImplicitCastExprClass: { 15185 auto *CE = cast<CastExpr>(E); 15186 const Expr *From = CE->getSubExpr(); 15187 switch (CE->getCastKind()) { 15188 default: 15189 break; 15190 case CK_NoOp: 15191 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 15192 case CK_UncheckedDerivedToBase: 15193 case CK_DerivedToBase: { 15194 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 15195 if (!P) 15196 break; 15197 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 15198 P->second, Ctx); 15199 } 15200 } 15201 break; 15202 } 15203 case Stmt::ArraySubscriptExprClass: { 15204 auto *ASE = cast<ArraySubscriptExpr>(E); 15205 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 15206 false, Ctx); 15207 } 15208 case Stmt::DeclRefExprClass: { 15209 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 15210 // FIXME: If VD is captured by copy or is an escaping __block variable, 15211 // use the alignment of VD's type. 15212 if (!VD->getType()->isReferenceType()) 15213 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 15214 if (VD->hasInit()) 15215 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 15216 } 15217 break; 15218 } 15219 case Stmt::MemberExprClass: { 15220 auto *ME = cast<MemberExpr>(E); 15221 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 15222 if (!FD || FD->getType()->isReferenceType() || 15223 FD->getParent()->isInvalidDecl()) 15224 break; 15225 Optional<std::pair<CharUnits, CharUnits>> P; 15226 if (ME->isArrow()) 15227 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 15228 else 15229 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 15230 if (!P) 15231 break; 15232 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 15233 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 15234 return std::make_pair(P->first, 15235 P->second + CharUnits::fromQuantity(Offset)); 15236 } 15237 case Stmt::UnaryOperatorClass: { 15238 auto *UO = cast<UnaryOperator>(E); 15239 switch (UO->getOpcode()) { 15240 default: 15241 break; 15242 case UO_Deref: 15243 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 15244 } 15245 break; 15246 } 15247 case Stmt::BinaryOperatorClass: { 15248 auto *BO = cast<BinaryOperator>(E); 15249 auto Opcode = BO->getOpcode(); 15250 switch (Opcode) { 15251 default: 15252 break; 15253 case BO_Comma: 15254 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 15255 } 15256 break; 15257 } 15258 } 15259 return llvm::None; 15260 } 15261 15262 /// This helper function takes a pointer expression and returns the alignment of 15263 /// a VarDecl and a constant offset from the VarDecl. 15264 Optional<std::pair<CharUnits, CharUnits>> 15265 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 15266 E = E->IgnoreParens(); 15267 switch (E->getStmtClass()) { 15268 default: 15269 break; 15270 case Stmt::CStyleCastExprClass: 15271 case Stmt::CXXStaticCastExprClass: 15272 case Stmt::ImplicitCastExprClass: { 15273 auto *CE = cast<CastExpr>(E); 15274 const Expr *From = CE->getSubExpr(); 15275 switch (CE->getCastKind()) { 15276 default: 15277 break; 15278 case CK_NoOp: 15279 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 15280 case CK_ArrayToPointerDecay: 15281 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 15282 case CK_UncheckedDerivedToBase: 15283 case CK_DerivedToBase: { 15284 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 15285 if (!P) 15286 break; 15287 return getDerivedToBaseAlignmentAndOffset( 15288 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 15289 } 15290 } 15291 break; 15292 } 15293 case Stmt::CXXThisExprClass: { 15294 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 15295 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 15296 return std::make_pair(Alignment, CharUnits::Zero()); 15297 } 15298 case Stmt::UnaryOperatorClass: { 15299 auto *UO = cast<UnaryOperator>(E); 15300 if (UO->getOpcode() == UO_AddrOf) 15301 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 15302 break; 15303 } 15304 case Stmt::BinaryOperatorClass: { 15305 auto *BO = cast<BinaryOperator>(E); 15306 auto Opcode = BO->getOpcode(); 15307 switch (Opcode) { 15308 default: 15309 break; 15310 case BO_Add: 15311 case BO_Sub: { 15312 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 15313 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 15314 std::swap(LHS, RHS); 15315 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 15316 Ctx); 15317 } 15318 case BO_Comma: 15319 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 15320 } 15321 break; 15322 } 15323 } 15324 return llvm::None; 15325 } 15326 15327 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 15328 // See if we can compute the alignment of a VarDecl and an offset from it. 15329 Optional<std::pair<CharUnits, CharUnits>> P = 15330 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 15331 15332 if (P) 15333 return P->first.alignmentAtOffset(P->second); 15334 15335 // If that failed, return the type's alignment. 15336 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 15337 } 15338 15339 /// CheckCastAlign - Implements -Wcast-align, which warns when a 15340 /// pointer cast increases the alignment requirements. 15341 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 15342 // This is actually a lot of work to potentially be doing on every 15343 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 15344 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 15345 return; 15346 15347 // Ignore dependent types. 15348 if (T->isDependentType() || Op->getType()->isDependentType()) 15349 return; 15350 15351 // Require that the destination be a pointer type. 15352 const PointerType *DestPtr = T->getAs<PointerType>(); 15353 if (!DestPtr) return; 15354 15355 // If the destination has alignment 1, we're done. 15356 QualType DestPointee = DestPtr->getPointeeType(); 15357 if (DestPointee->isIncompleteType()) return; 15358 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 15359 if (DestAlign.isOne()) return; 15360 15361 // Require that the source be a pointer type. 15362 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 15363 if (!SrcPtr) return; 15364 QualType SrcPointee = SrcPtr->getPointeeType(); 15365 15366 // Explicitly allow casts from cv void*. We already implicitly 15367 // allowed casts to cv void*, since they have alignment 1. 15368 // Also allow casts involving incomplete types, which implicitly 15369 // includes 'void'. 15370 if (SrcPointee->isIncompleteType()) return; 15371 15372 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 15373 15374 if (SrcAlign >= DestAlign) return; 15375 15376 Diag(TRange.getBegin(), diag::warn_cast_align) 15377 << Op->getType() << T 15378 << static_cast<unsigned>(SrcAlign.getQuantity()) 15379 << static_cast<unsigned>(DestAlign.getQuantity()) 15380 << TRange << Op->getSourceRange(); 15381 } 15382 15383 /// Check whether this array fits the idiom of a size-one tail padded 15384 /// array member of a struct. 15385 /// 15386 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 15387 /// commonly used to emulate flexible arrays in C89 code. 15388 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 15389 const NamedDecl *ND) { 15390 if (Size != 1 || !ND) return false; 15391 15392 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 15393 if (!FD) return false; 15394 15395 // Don't consider sizes resulting from macro expansions or template argument 15396 // substitution to form C89 tail-padded arrays. 15397 15398 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 15399 while (TInfo) { 15400 TypeLoc TL = TInfo->getTypeLoc(); 15401 // Look through typedefs. 15402 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 15403 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 15404 TInfo = TDL->getTypeSourceInfo(); 15405 continue; 15406 } 15407 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 15408 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 15409 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 15410 return false; 15411 } 15412 break; 15413 } 15414 15415 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 15416 if (!RD) return false; 15417 if (RD->isUnion()) return false; 15418 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15419 if (!CRD->isStandardLayout()) return false; 15420 } 15421 15422 // See if this is the last field decl in the record. 15423 const Decl *D = FD; 15424 while ((D = D->getNextDeclInContext())) 15425 if (isa<FieldDecl>(D)) 15426 return false; 15427 return true; 15428 } 15429 15430 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 15431 const ArraySubscriptExpr *ASE, 15432 bool AllowOnePastEnd, bool IndexNegated) { 15433 // Already diagnosed by the constant evaluator. 15434 if (isConstantEvaluated()) 15435 return; 15436 15437 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 15438 if (IndexExpr->isValueDependent()) 15439 return; 15440 15441 const Type *EffectiveType = 15442 BaseExpr->getType()->getPointeeOrArrayElementType(); 15443 BaseExpr = BaseExpr->IgnoreParenCasts(); 15444 const ConstantArrayType *ArrayTy = 15445 Context.getAsConstantArrayType(BaseExpr->getType()); 15446 15447 const Type *BaseType = 15448 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 15449 bool IsUnboundedArray = (BaseType == nullptr); 15450 if (EffectiveType->isDependentType() || 15451 (!IsUnboundedArray && BaseType->isDependentType())) 15452 return; 15453 15454 Expr::EvalResult Result; 15455 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 15456 return; 15457 15458 llvm::APSInt index = Result.Val.getInt(); 15459 if (IndexNegated) { 15460 index.setIsUnsigned(false); 15461 index = -index; 15462 } 15463 15464 const NamedDecl *ND = nullptr; 15465 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15466 ND = DRE->getDecl(); 15467 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 15468 ND = ME->getMemberDecl(); 15469 15470 if (IsUnboundedArray) { 15471 if (index.isUnsigned() || !index.isNegative()) { 15472 const auto &ASTC = getASTContext(); 15473 unsigned AddrBits = 15474 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 15475 EffectiveType->getCanonicalTypeInternal())); 15476 if (index.getBitWidth() < AddrBits) 15477 index = index.zext(AddrBits); 15478 Optional<CharUnits> ElemCharUnits = 15479 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 15480 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 15481 // pointer) bounds-checking isn't meaningful. 15482 if (!ElemCharUnits) 15483 return; 15484 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 15485 // If index has more active bits than address space, we already know 15486 // we have a bounds violation to warn about. Otherwise, compute 15487 // address of (index + 1)th element, and warn about bounds violation 15488 // only if that address exceeds address space. 15489 if (index.getActiveBits() <= AddrBits) { 15490 bool Overflow; 15491 llvm::APInt Product(index); 15492 Product += 1; 15493 Product = Product.umul_ov(ElemBytes, Overflow); 15494 if (!Overflow && Product.getActiveBits() <= AddrBits) 15495 return; 15496 } 15497 15498 // Need to compute max possible elements in address space, since that 15499 // is included in diag message. 15500 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 15501 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 15502 MaxElems += 1; 15503 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 15504 MaxElems = MaxElems.udiv(ElemBytes); 15505 15506 unsigned DiagID = 15507 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 15508 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 15509 15510 // Diag message shows element size in bits and in "bytes" (platform- 15511 // dependent CharUnits) 15512 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15513 PDiag(DiagID) 15514 << toString(index, 10, true) << AddrBits 15515 << (unsigned)ASTC.toBits(*ElemCharUnits) 15516 << toString(ElemBytes, 10, false) 15517 << toString(MaxElems, 10, false) 15518 << (unsigned)MaxElems.getLimitedValue(~0U) 15519 << IndexExpr->getSourceRange()); 15520 15521 if (!ND) { 15522 // Try harder to find a NamedDecl to point at in the note. 15523 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15524 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15525 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15526 ND = DRE->getDecl(); 15527 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15528 ND = ME->getMemberDecl(); 15529 } 15530 15531 if (ND) 15532 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15533 PDiag(diag::note_array_declared_here) << ND); 15534 } 15535 return; 15536 } 15537 15538 if (index.isUnsigned() || !index.isNegative()) { 15539 // It is possible that the type of the base expression after 15540 // IgnoreParenCasts is incomplete, even though the type of the base 15541 // expression before IgnoreParenCasts is complete (see PR39746 for an 15542 // example). In this case we have no information about whether the array 15543 // access exceeds the array bounds. However we can still diagnose an array 15544 // access which precedes the array bounds. 15545 if (BaseType->isIncompleteType()) 15546 return; 15547 15548 llvm::APInt size = ArrayTy->getSize(); 15549 if (!size.isStrictlyPositive()) 15550 return; 15551 15552 if (BaseType != EffectiveType) { 15553 // Make sure we're comparing apples to apples when comparing index to size 15554 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 15555 uint64_t array_typesize = Context.getTypeSize(BaseType); 15556 // Handle ptrarith_typesize being zero, such as when casting to void* 15557 if (!ptrarith_typesize) ptrarith_typesize = 1; 15558 if (ptrarith_typesize != array_typesize) { 15559 // There's a cast to a different size type involved 15560 uint64_t ratio = array_typesize / ptrarith_typesize; 15561 // TODO: Be smarter about handling cases where array_typesize is not a 15562 // multiple of ptrarith_typesize 15563 if (ptrarith_typesize * ratio == array_typesize) 15564 size *= llvm::APInt(size.getBitWidth(), ratio); 15565 } 15566 } 15567 15568 if (size.getBitWidth() > index.getBitWidth()) 15569 index = index.zext(size.getBitWidth()); 15570 else if (size.getBitWidth() < index.getBitWidth()) 15571 size = size.zext(index.getBitWidth()); 15572 15573 // For array subscripting the index must be less than size, but for pointer 15574 // arithmetic also allow the index (offset) to be equal to size since 15575 // computing the next address after the end of the array is legal and 15576 // commonly done e.g. in C++ iterators and range-based for loops. 15577 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 15578 return; 15579 15580 // Also don't warn for arrays of size 1 which are members of some 15581 // structure. These are often used to approximate flexible arrays in C89 15582 // code. 15583 if (IsTailPaddedMemberArray(*this, size, ND)) 15584 return; 15585 15586 // Suppress the warning if the subscript expression (as identified by the 15587 // ']' location) and the index expression are both from macro expansions 15588 // within a system header. 15589 if (ASE) { 15590 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 15591 ASE->getRBracketLoc()); 15592 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 15593 SourceLocation IndexLoc = 15594 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 15595 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 15596 return; 15597 } 15598 } 15599 15600 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 15601 : diag::warn_ptr_arith_exceeds_bounds; 15602 15603 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15604 PDiag(DiagID) << toString(index, 10, true) 15605 << toString(size, 10, true) 15606 << (unsigned)size.getLimitedValue(~0U) 15607 << IndexExpr->getSourceRange()); 15608 } else { 15609 unsigned DiagID = diag::warn_array_index_precedes_bounds; 15610 if (!ASE) { 15611 DiagID = diag::warn_ptr_arith_precedes_bounds; 15612 if (index.isNegative()) index = -index; 15613 } 15614 15615 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15616 PDiag(DiagID) << toString(index, 10, true) 15617 << IndexExpr->getSourceRange()); 15618 } 15619 15620 if (!ND) { 15621 // Try harder to find a NamedDecl to point at in the note. 15622 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15623 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15624 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15625 ND = DRE->getDecl(); 15626 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15627 ND = ME->getMemberDecl(); 15628 } 15629 15630 if (ND) 15631 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15632 PDiag(diag::note_array_declared_here) << ND); 15633 } 15634 15635 void Sema::CheckArrayAccess(const Expr *expr) { 15636 int AllowOnePastEnd = 0; 15637 while (expr) { 15638 expr = expr->IgnoreParenImpCasts(); 15639 switch (expr->getStmtClass()) { 15640 case Stmt::ArraySubscriptExprClass: { 15641 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 15642 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 15643 AllowOnePastEnd > 0); 15644 expr = ASE->getBase(); 15645 break; 15646 } 15647 case Stmt::MemberExprClass: { 15648 expr = cast<MemberExpr>(expr)->getBase(); 15649 break; 15650 } 15651 case Stmt::OMPArraySectionExprClass: { 15652 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 15653 if (ASE->getLowerBound()) 15654 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 15655 /*ASE=*/nullptr, AllowOnePastEnd > 0); 15656 return; 15657 } 15658 case Stmt::UnaryOperatorClass: { 15659 // Only unwrap the * and & unary operators 15660 const UnaryOperator *UO = cast<UnaryOperator>(expr); 15661 expr = UO->getSubExpr(); 15662 switch (UO->getOpcode()) { 15663 case UO_AddrOf: 15664 AllowOnePastEnd++; 15665 break; 15666 case UO_Deref: 15667 AllowOnePastEnd--; 15668 break; 15669 default: 15670 return; 15671 } 15672 break; 15673 } 15674 case Stmt::ConditionalOperatorClass: { 15675 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 15676 if (const Expr *lhs = cond->getLHS()) 15677 CheckArrayAccess(lhs); 15678 if (const Expr *rhs = cond->getRHS()) 15679 CheckArrayAccess(rhs); 15680 return; 15681 } 15682 case Stmt::CXXOperatorCallExprClass: { 15683 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 15684 for (const auto *Arg : OCE->arguments()) 15685 CheckArrayAccess(Arg); 15686 return; 15687 } 15688 default: 15689 return; 15690 } 15691 } 15692 } 15693 15694 //===--- CHECK: Objective-C retain cycles ----------------------------------// 15695 15696 namespace { 15697 15698 struct RetainCycleOwner { 15699 VarDecl *Variable = nullptr; 15700 SourceRange Range; 15701 SourceLocation Loc; 15702 bool Indirect = false; 15703 15704 RetainCycleOwner() = default; 15705 15706 void setLocsFrom(Expr *e) { 15707 Loc = e->getExprLoc(); 15708 Range = e->getSourceRange(); 15709 } 15710 }; 15711 15712 } // namespace 15713 15714 /// Consider whether capturing the given variable can possibly lead to 15715 /// a retain cycle. 15716 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 15717 // In ARC, it's captured strongly iff the variable has __strong 15718 // lifetime. In MRR, it's captured strongly if the variable is 15719 // __block and has an appropriate type. 15720 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15721 return false; 15722 15723 owner.Variable = var; 15724 if (ref) 15725 owner.setLocsFrom(ref); 15726 return true; 15727 } 15728 15729 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 15730 while (true) { 15731 e = e->IgnoreParens(); 15732 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 15733 switch (cast->getCastKind()) { 15734 case CK_BitCast: 15735 case CK_LValueBitCast: 15736 case CK_LValueToRValue: 15737 case CK_ARCReclaimReturnedObject: 15738 e = cast->getSubExpr(); 15739 continue; 15740 15741 default: 15742 return false; 15743 } 15744 } 15745 15746 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 15747 ObjCIvarDecl *ivar = ref->getDecl(); 15748 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15749 return false; 15750 15751 // Try to find a retain cycle in the base. 15752 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 15753 return false; 15754 15755 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 15756 owner.Indirect = true; 15757 return true; 15758 } 15759 15760 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 15761 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 15762 if (!var) return false; 15763 return considerVariable(var, ref, owner); 15764 } 15765 15766 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 15767 if (member->isArrow()) return false; 15768 15769 // Don't count this as an indirect ownership. 15770 e = member->getBase(); 15771 continue; 15772 } 15773 15774 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 15775 // Only pay attention to pseudo-objects on property references. 15776 ObjCPropertyRefExpr *pre 15777 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 15778 ->IgnoreParens()); 15779 if (!pre) return false; 15780 if (pre->isImplicitProperty()) return false; 15781 ObjCPropertyDecl *property = pre->getExplicitProperty(); 15782 if (!property->isRetaining() && 15783 !(property->getPropertyIvarDecl() && 15784 property->getPropertyIvarDecl()->getType() 15785 .getObjCLifetime() == Qualifiers::OCL_Strong)) 15786 return false; 15787 15788 owner.Indirect = true; 15789 if (pre->isSuperReceiver()) { 15790 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 15791 if (!owner.Variable) 15792 return false; 15793 owner.Loc = pre->getLocation(); 15794 owner.Range = pre->getSourceRange(); 15795 return true; 15796 } 15797 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 15798 ->getSourceExpr()); 15799 continue; 15800 } 15801 15802 // Array ivars? 15803 15804 return false; 15805 } 15806 } 15807 15808 namespace { 15809 15810 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 15811 ASTContext &Context; 15812 VarDecl *Variable; 15813 Expr *Capturer = nullptr; 15814 bool VarWillBeReased = false; 15815 15816 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 15817 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 15818 Context(Context), Variable(variable) {} 15819 15820 void VisitDeclRefExpr(DeclRefExpr *ref) { 15821 if (ref->getDecl() == Variable && !Capturer) 15822 Capturer = ref; 15823 } 15824 15825 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 15826 if (Capturer) return; 15827 Visit(ref->getBase()); 15828 if (Capturer && ref->isFreeIvar()) 15829 Capturer = ref; 15830 } 15831 15832 void VisitBlockExpr(BlockExpr *block) { 15833 // Look inside nested blocks 15834 if (block->getBlockDecl()->capturesVariable(Variable)) 15835 Visit(block->getBlockDecl()->getBody()); 15836 } 15837 15838 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 15839 if (Capturer) return; 15840 if (OVE->getSourceExpr()) 15841 Visit(OVE->getSourceExpr()); 15842 } 15843 15844 void VisitBinaryOperator(BinaryOperator *BinOp) { 15845 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 15846 return; 15847 Expr *LHS = BinOp->getLHS(); 15848 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 15849 if (DRE->getDecl() != Variable) 15850 return; 15851 if (Expr *RHS = BinOp->getRHS()) { 15852 RHS = RHS->IgnoreParenCasts(); 15853 Optional<llvm::APSInt> Value; 15854 VarWillBeReased = 15855 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 15856 *Value == 0); 15857 } 15858 } 15859 } 15860 }; 15861 15862 } // namespace 15863 15864 /// Check whether the given argument is a block which captures a 15865 /// variable. 15866 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 15867 assert(owner.Variable && owner.Loc.isValid()); 15868 15869 e = e->IgnoreParenCasts(); 15870 15871 // Look through [^{...} copy] and Block_copy(^{...}). 15872 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 15873 Selector Cmd = ME->getSelector(); 15874 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 15875 e = ME->getInstanceReceiver(); 15876 if (!e) 15877 return nullptr; 15878 e = e->IgnoreParenCasts(); 15879 } 15880 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 15881 if (CE->getNumArgs() == 1) { 15882 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 15883 if (Fn) { 15884 const IdentifierInfo *FnI = Fn->getIdentifier(); 15885 if (FnI && FnI->isStr("_Block_copy")) { 15886 e = CE->getArg(0)->IgnoreParenCasts(); 15887 } 15888 } 15889 } 15890 } 15891 15892 BlockExpr *block = dyn_cast<BlockExpr>(e); 15893 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 15894 return nullptr; 15895 15896 FindCaptureVisitor visitor(S.Context, owner.Variable); 15897 visitor.Visit(block->getBlockDecl()->getBody()); 15898 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15899 } 15900 15901 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15902 RetainCycleOwner &owner) { 15903 assert(capturer); 15904 assert(owner.Variable && owner.Loc.isValid()); 15905 15906 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15907 << owner.Variable << capturer->getSourceRange(); 15908 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15909 << owner.Indirect << owner.Range; 15910 } 15911 15912 /// Check for a keyword selector that starts with the word 'add' or 15913 /// 'set'. 15914 static bool isSetterLikeSelector(Selector sel) { 15915 if (sel.isUnarySelector()) return false; 15916 15917 StringRef str = sel.getNameForSlot(0); 15918 while (!str.empty() && str.front() == '_') str = str.substr(1); 15919 if (str.startswith("set")) 15920 str = str.substr(3); 15921 else if (str.startswith("add")) { 15922 // Specially allow 'addOperationWithBlock:'. 15923 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15924 return false; 15925 str = str.substr(3); 15926 } 15927 else 15928 return false; 15929 15930 if (str.empty()) return true; 15931 return !isLowercase(str.front()); 15932 } 15933 15934 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15935 ObjCMessageExpr *Message) { 15936 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15937 Message->getReceiverInterface(), 15938 NSAPI::ClassId_NSMutableArray); 15939 if (!IsMutableArray) { 15940 return None; 15941 } 15942 15943 Selector Sel = Message->getSelector(); 15944 15945 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15946 S.NSAPIObj->getNSArrayMethodKind(Sel); 15947 if (!MKOpt) { 15948 return None; 15949 } 15950 15951 NSAPI::NSArrayMethodKind MK = *MKOpt; 15952 15953 switch (MK) { 15954 case NSAPI::NSMutableArr_addObject: 15955 case NSAPI::NSMutableArr_insertObjectAtIndex: 15956 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15957 return 0; 15958 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15959 return 1; 15960 15961 default: 15962 return None; 15963 } 15964 15965 return None; 15966 } 15967 15968 static 15969 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15970 ObjCMessageExpr *Message) { 15971 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15972 Message->getReceiverInterface(), 15973 NSAPI::ClassId_NSMutableDictionary); 15974 if (!IsMutableDictionary) { 15975 return None; 15976 } 15977 15978 Selector Sel = Message->getSelector(); 15979 15980 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 15981 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 15982 if (!MKOpt) { 15983 return None; 15984 } 15985 15986 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 15987 15988 switch (MK) { 15989 case NSAPI::NSMutableDict_setObjectForKey: 15990 case NSAPI::NSMutableDict_setValueForKey: 15991 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 15992 return 0; 15993 15994 default: 15995 return None; 15996 } 15997 15998 return None; 15999 } 16000 16001 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 16002 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 16003 Message->getReceiverInterface(), 16004 NSAPI::ClassId_NSMutableSet); 16005 16006 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 16007 Message->getReceiverInterface(), 16008 NSAPI::ClassId_NSMutableOrderedSet); 16009 if (!IsMutableSet && !IsMutableOrderedSet) { 16010 return None; 16011 } 16012 16013 Selector Sel = Message->getSelector(); 16014 16015 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 16016 if (!MKOpt) { 16017 return None; 16018 } 16019 16020 NSAPI::NSSetMethodKind MK = *MKOpt; 16021 16022 switch (MK) { 16023 case NSAPI::NSMutableSet_addObject: 16024 case NSAPI::NSOrderedSet_setObjectAtIndex: 16025 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 16026 case NSAPI::NSOrderedSet_insertObjectAtIndex: 16027 return 0; 16028 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 16029 return 1; 16030 } 16031 16032 return None; 16033 } 16034 16035 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 16036 if (!Message->isInstanceMessage()) { 16037 return; 16038 } 16039 16040 Optional<int> ArgOpt; 16041 16042 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 16043 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 16044 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 16045 return; 16046 } 16047 16048 int ArgIndex = *ArgOpt; 16049 16050 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 16051 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 16052 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 16053 } 16054 16055 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 16056 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 16057 if (ArgRE->isObjCSelfExpr()) { 16058 Diag(Message->getSourceRange().getBegin(), 16059 diag::warn_objc_circular_container) 16060 << ArgRE->getDecl() << StringRef("'super'"); 16061 } 16062 } 16063 } else { 16064 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 16065 16066 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 16067 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 16068 } 16069 16070 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 16071 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 16072 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 16073 ValueDecl *Decl = ReceiverRE->getDecl(); 16074 Diag(Message->getSourceRange().getBegin(), 16075 diag::warn_objc_circular_container) 16076 << Decl << Decl; 16077 if (!ArgRE->isObjCSelfExpr()) { 16078 Diag(Decl->getLocation(), 16079 diag::note_objc_circular_container_declared_here) 16080 << Decl; 16081 } 16082 } 16083 } 16084 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 16085 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 16086 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 16087 ObjCIvarDecl *Decl = IvarRE->getDecl(); 16088 Diag(Message->getSourceRange().getBegin(), 16089 diag::warn_objc_circular_container) 16090 << Decl << Decl; 16091 Diag(Decl->getLocation(), 16092 diag::note_objc_circular_container_declared_here) 16093 << Decl; 16094 } 16095 } 16096 } 16097 } 16098 } 16099 16100 /// Check a message send to see if it's likely to cause a retain cycle. 16101 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 16102 // Only check instance methods whose selector looks like a setter. 16103 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 16104 return; 16105 16106 // Try to find a variable that the receiver is strongly owned by. 16107 RetainCycleOwner owner; 16108 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 16109 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 16110 return; 16111 } else { 16112 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 16113 owner.Variable = getCurMethodDecl()->getSelfDecl(); 16114 owner.Loc = msg->getSuperLoc(); 16115 owner.Range = msg->getSuperLoc(); 16116 } 16117 16118 // Check whether the receiver is captured by any of the arguments. 16119 const ObjCMethodDecl *MD = msg->getMethodDecl(); 16120 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 16121 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 16122 // noescape blocks should not be retained by the method. 16123 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 16124 continue; 16125 return diagnoseRetainCycle(*this, capturer, owner); 16126 } 16127 } 16128 } 16129 16130 /// Check a property assign to see if it's likely to cause a retain cycle. 16131 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 16132 RetainCycleOwner owner; 16133 if (!findRetainCycleOwner(*this, receiver, owner)) 16134 return; 16135 16136 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 16137 diagnoseRetainCycle(*this, capturer, owner); 16138 } 16139 16140 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 16141 RetainCycleOwner Owner; 16142 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 16143 return; 16144 16145 // Because we don't have an expression for the variable, we have to set the 16146 // location explicitly here. 16147 Owner.Loc = Var->getLocation(); 16148 Owner.Range = Var->getSourceRange(); 16149 16150 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 16151 diagnoseRetainCycle(*this, Capturer, Owner); 16152 } 16153 16154 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 16155 Expr *RHS, bool isProperty) { 16156 // Check if RHS is an Objective-C object literal, which also can get 16157 // immediately zapped in a weak reference. Note that we explicitly 16158 // allow ObjCStringLiterals, since those are designed to never really die. 16159 RHS = RHS->IgnoreParenImpCasts(); 16160 16161 // This enum needs to match with the 'select' in 16162 // warn_objc_arc_literal_assign (off-by-1). 16163 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 16164 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 16165 return false; 16166 16167 S.Diag(Loc, diag::warn_arc_literal_assign) 16168 << (unsigned) Kind 16169 << (isProperty ? 0 : 1) 16170 << RHS->getSourceRange(); 16171 16172 return true; 16173 } 16174 16175 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 16176 Qualifiers::ObjCLifetime LT, 16177 Expr *RHS, bool isProperty) { 16178 // Strip off any implicit cast added to get to the one ARC-specific. 16179 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 16180 if (cast->getCastKind() == CK_ARCConsumeObject) { 16181 S.Diag(Loc, diag::warn_arc_retained_assign) 16182 << (LT == Qualifiers::OCL_ExplicitNone) 16183 << (isProperty ? 0 : 1) 16184 << RHS->getSourceRange(); 16185 return true; 16186 } 16187 RHS = cast->getSubExpr(); 16188 } 16189 16190 if (LT == Qualifiers::OCL_Weak && 16191 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 16192 return true; 16193 16194 return false; 16195 } 16196 16197 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 16198 QualType LHS, Expr *RHS) { 16199 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 16200 16201 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 16202 return false; 16203 16204 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 16205 return true; 16206 16207 return false; 16208 } 16209 16210 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 16211 Expr *LHS, Expr *RHS) { 16212 QualType LHSType; 16213 // PropertyRef on LHS type need be directly obtained from 16214 // its declaration as it has a PseudoType. 16215 ObjCPropertyRefExpr *PRE 16216 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 16217 if (PRE && !PRE->isImplicitProperty()) { 16218 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 16219 if (PD) 16220 LHSType = PD->getType(); 16221 } 16222 16223 if (LHSType.isNull()) 16224 LHSType = LHS->getType(); 16225 16226 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 16227 16228 if (LT == Qualifiers::OCL_Weak) { 16229 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 16230 getCurFunction()->markSafeWeakUse(LHS); 16231 } 16232 16233 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 16234 return; 16235 16236 // FIXME. Check for other life times. 16237 if (LT != Qualifiers::OCL_None) 16238 return; 16239 16240 if (PRE) { 16241 if (PRE->isImplicitProperty()) 16242 return; 16243 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 16244 if (!PD) 16245 return; 16246 16247 unsigned Attributes = PD->getPropertyAttributes(); 16248 if (Attributes & ObjCPropertyAttribute::kind_assign) { 16249 // when 'assign' attribute was not explicitly specified 16250 // by user, ignore it and rely on property type itself 16251 // for lifetime info. 16252 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 16253 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 16254 LHSType->isObjCRetainableType()) 16255 return; 16256 16257 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 16258 if (cast->getCastKind() == CK_ARCConsumeObject) { 16259 Diag(Loc, diag::warn_arc_retained_property_assign) 16260 << RHS->getSourceRange(); 16261 return; 16262 } 16263 RHS = cast->getSubExpr(); 16264 } 16265 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 16266 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 16267 return; 16268 } 16269 } 16270 } 16271 16272 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 16273 16274 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 16275 SourceLocation StmtLoc, 16276 const NullStmt *Body) { 16277 // Do not warn if the body is a macro that expands to nothing, e.g: 16278 // 16279 // #define CALL(x) 16280 // if (condition) 16281 // CALL(0); 16282 if (Body->hasLeadingEmptyMacro()) 16283 return false; 16284 16285 // Get line numbers of statement and body. 16286 bool StmtLineInvalid; 16287 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 16288 &StmtLineInvalid); 16289 if (StmtLineInvalid) 16290 return false; 16291 16292 bool BodyLineInvalid; 16293 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 16294 &BodyLineInvalid); 16295 if (BodyLineInvalid) 16296 return false; 16297 16298 // Warn if null statement and body are on the same line. 16299 if (StmtLine != BodyLine) 16300 return false; 16301 16302 return true; 16303 } 16304 16305 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 16306 const Stmt *Body, 16307 unsigned DiagID) { 16308 // Since this is a syntactic check, don't emit diagnostic for template 16309 // instantiations, this just adds noise. 16310 if (CurrentInstantiationScope) 16311 return; 16312 16313 // The body should be a null statement. 16314 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 16315 if (!NBody) 16316 return; 16317 16318 // Do the usual checks. 16319 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 16320 return; 16321 16322 Diag(NBody->getSemiLoc(), DiagID); 16323 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 16324 } 16325 16326 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 16327 const Stmt *PossibleBody) { 16328 assert(!CurrentInstantiationScope); // Ensured by caller 16329 16330 SourceLocation StmtLoc; 16331 const Stmt *Body; 16332 unsigned DiagID; 16333 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 16334 StmtLoc = FS->getRParenLoc(); 16335 Body = FS->getBody(); 16336 DiagID = diag::warn_empty_for_body; 16337 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 16338 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 16339 Body = WS->getBody(); 16340 DiagID = diag::warn_empty_while_body; 16341 } else 16342 return; // Neither `for' nor `while'. 16343 16344 // The body should be a null statement. 16345 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 16346 if (!NBody) 16347 return; 16348 16349 // Skip expensive checks if diagnostic is disabled. 16350 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 16351 return; 16352 16353 // Do the usual checks. 16354 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 16355 return; 16356 16357 // `for(...);' and `while(...);' are popular idioms, so in order to keep 16358 // noise level low, emit diagnostics only if for/while is followed by a 16359 // CompoundStmt, e.g.: 16360 // for (int i = 0; i < n; i++); 16361 // { 16362 // a(i); 16363 // } 16364 // or if for/while is followed by a statement with more indentation 16365 // than for/while itself: 16366 // for (int i = 0; i < n; i++); 16367 // a(i); 16368 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 16369 if (!ProbableTypo) { 16370 bool BodyColInvalid; 16371 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 16372 PossibleBody->getBeginLoc(), &BodyColInvalid); 16373 if (BodyColInvalid) 16374 return; 16375 16376 bool StmtColInvalid; 16377 unsigned StmtCol = 16378 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 16379 if (StmtColInvalid) 16380 return; 16381 16382 if (BodyCol > StmtCol) 16383 ProbableTypo = true; 16384 } 16385 16386 if (ProbableTypo) { 16387 Diag(NBody->getSemiLoc(), DiagID); 16388 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 16389 } 16390 } 16391 16392 //===--- CHECK: Warn on self move with std::move. -------------------------===// 16393 16394 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 16395 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 16396 SourceLocation OpLoc) { 16397 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 16398 return; 16399 16400 if (inTemplateInstantiation()) 16401 return; 16402 16403 // Strip parens and casts away. 16404 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 16405 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 16406 16407 // Check for a call expression 16408 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 16409 if (!CE || CE->getNumArgs() != 1) 16410 return; 16411 16412 // Check for a call to std::move 16413 if (!CE->isCallToStdMove()) 16414 return; 16415 16416 // Get argument from std::move 16417 RHSExpr = CE->getArg(0); 16418 16419 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 16420 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 16421 16422 // Two DeclRefExpr's, check that the decls are the same. 16423 if (LHSDeclRef && RHSDeclRef) { 16424 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16425 return; 16426 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16427 RHSDeclRef->getDecl()->getCanonicalDecl()) 16428 return; 16429 16430 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16431 << LHSExpr->getSourceRange() 16432 << RHSExpr->getSourceRange(); 16433 return; 16434 } 16435 16436 // Member variables require a different approach to check for self moves. 16437 // MemberExpr's are the same if every nested MemberExpr refers to the same 16438 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 16439 // the base Expr's are CXXThisExpr's. 16440 const Expr *LHSBase = LHSExpr; 16441 const Expr *RHSBase = RHSExpr; 16442 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 16443 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 16444 if (!LHSME || !RHSME) 16445 return; 16446 16447 while (LHSME && RHSME) { 16448 if (LHSME->getMemberDecl()->getCanonicalDecl() != 16449 RHSME->getMemberDecl()->getCanonicalDecl()) 16450 return; 16451 16452 LHSBase = LHSME->getBase(); 16453 RHSBase = RHSME->getBase(); 16454 LHSME = dyn_cast<MemberExpr>(LHSBase); 16455 RHSME = dyn_cast<MemberExpr>(RHSBase); 16456 } 16457 16458 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 16459 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 16460 if (LHSDeclRef && RHSDeclRef) { 16461 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16462 return; 16463 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16464 RHSDeclRef->getDecl()->getCanonicalDecl()) 16465 return; 16466 16467 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16468 << LHSExpr->getSourceRange() 16469 << RHSExpr->getSourceRange(); 16470 return; 16471 } 16472 16473 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 16474 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16475 << LHSExpr->getSourceRange() 16476 << RHSExpr->getSourceRange(); 16477 } 16478 16479 //===--- Layout compatibility ----------------------------------------------// 16480 16481 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 16482 16483 /// Check if two enumeration types are layout-compatible. 16484 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 16485 // C++11 [dcl.enum] p8: 16486 // Two enumeration types are layout-compatible if they have the same 16487 // underlying type. 16488 return ED1->isComplete() && ED2->isComplete() && 16489 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 16490 } 16491 16492 /// Check if two fields are layout-compatible. 16493 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 16494 FieldDecl *Field2) { 16495 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 16496 return false; 16497 16498 if (Field1->isBitField() != Field2->isBitField()) 16499 return false; 16500 16501 if (Field1->isBitField()) { 16502 // Make sure that the bit-fields are the same length. 16503 unsigned Bits1 = Field1->getBitWidthValue(C); 16504 unsigned Bits2 = Field2->getBitWidthValue(C); 16505 16506 if (Bits1 != Bits2) 16507 return false; 16508 } 16509 16510 return true; 16511 } 16512 16513 /// Check if two standard-layout structs are layout-compatible. 16514 /// (C++11 [class.mem] p17) 16515 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 16516 RecordDecl *RD2) { 16517 // If both records are C++ classes, check that base classes match. 16518 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 16519 // If one of records is a CXXRecordDecl we are in C++ mode, 16520 // thus the other one is a CXXRecordDecl, too. 16521 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 16522 // Check number of base classes. 16523 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 16524 return false; 16525 16526 // Check the base classes. 16527 for (CXXRecordDecl::base_class_const_iterator 16528 Base1 = D1CXX->bases_begin(), 16529 BaseEnd1 = D1CXX->bases_end(), 16530 Base2 = D2CXX->bases_begin(); 16531 Base1 != BaseEnd1; 16532 ++Base1, ++Base2) { 16533 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 16534 return false; 16535 } 16536 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 16537 // If only RD2 is a C++ class, it should have zero base classes. 16538 if (D2CXX->getNumBases() > 0) 16539 return false; 16540 } 16541 16542 // Check the fields. 16543 RecordDecl::field_iterator Field2 = RD2->field_begin(), 16544 Field2End = RD2->field_end(), 16545 Field1 = RD1->field_begin(), 16546 Field1End = RD1->field_end(); 16547 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 16548 if (!isLayoutCompatible(C, *Field1, *Field2)) 16549 return false; 16550 } 16551 if (Field1 != Field1End || Field2 != Field2End) 16552 return false; 16553 16554 return true; 16555 } 16556 16557 /// Check if two standard-layout unions are layout-compatible. 16558 /// (C++11 [class.mem] p18) 16559 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 16560 RecordDecl *RD2) { 16561 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 16562 for (auto *Field2 : RD2->fields()) 16563 UnmatchedFields.insert(Field2); 16564 16565 for (auto *Field1 : RD1->fields()) { 16566 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 16567 I = UnmatchedFields.begin(), 16568 E = UnmatchedFields.end(); 16569 16570 for ( ; I != E; ++I) { 16571 if (isLayoutCompatible(C, Field1, *I)) { 16572 bool Result = UnmatchedFields.erase(*I); 16573 (void) Result; 16574 assert(Result); 16575 break; 16576 } 16577 } 16578 if (I == E) 16579 return false; 16580 } 16581 16582 return UnmatchedFields.empty(); 16583 } 16584 16585 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 16586 RecordDecl *RD2) { 16587 if (RD1->isUnion() != RD2->isUnion()) 16588 return false; 16589 16590 if (RD1->isUnion()) 16591 return isLayoutCompatibleUnion(C, RD1, RD2); 16592 else 16593 return isLayoutCompatibleStruct(C, RD1, RD2); 16594 } 16595 16596 /// Check if two types are layout-compatible in C++11 sense. 16597 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 16598 if (T1.isNull() || T2.isNull()) 16599 return false; 16600 16601 // C++11 [basic.types] p11: 16602 // If two types T1 and T2 are the same type, then T1 and T2 are 16603 // layout-compatible types. 16604 if (C.hasSameType(T1, T2)) 16605 return true; 16606 16607 T1 = T1.getCanonicalType().getUnqualifiedType(); 16608 T2 = T2.getCanonicalType().getUnqualifiedType(); 16609 16610 const Type::TypeClass TC1 = T1->getTypeClass(); 16611 const Type::TypeClass TC2 = T2->getTypeClass(); 16612 16613 if (TC1 != TC2) 16614 return false; 16615 16616 if (TC1 == Type::Enum) { 16617 return isLayoutCompatible(C, 16618 cast<EnumType>(T1)->getDecl(), 16619 cast<EnumType>(T2)->getDecl()); 16620 } else if (TC1 == Type::Record) { 16621 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 16622 return false; 16623 16624 return isLayoutCompatible(C, 16625 cast<RecordType>(T1)->getDecl(), 16626 cast<RecordType>(T2)->getDecl()); 16627 } 16628 16629 return false; 16630 } 16631 16632 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 16633 16634 /// Given a type tag expression find the type tag itself. 16635 /// 16636 /// \param TypeExpr Type tag expression, as it appears in user's code. 16637 /// 16638 /// \param VD Declaration of an identifier that appears in a type tag. 16639 /// 16640 /// \param MagicValue Type tag magic value. 16641 /// 16642 /// \param isConstantEvaluated whether the evalaution should be performed in 16643 16644 /// constant context. 16645 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 16646 const ValueDecl **VD, uint64_t *MagicValue, 16647 bool isConstantEvaluated) { 16648 while(true) { 16649 if (!TypeExpr) 16650 return false; 16651 16652 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 16653 16654 switch (TypeExpr->getStmtClass()) { 16655 case Stmt::UnaryOperatorClass: { 16656 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 16657 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 16658 TypeExpr = UO->getSubExpr(); 16659 continue; 16660 } 16661 return false; 16662 } 16663 16664 case Stmt::DeclRefExprClass: { 16665 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 16666 *VD = DRE->getDecl(); 16667 return true; 16668 } 16669 16670 case Stmt::IntegerLiteralClass: { 16671 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 16672 llvm::APInt MagicValueAPInt = IL->getValue(); 16673 if (MagicValueAPInt.getActiveBits() <= 64) { 16674 *MagicValue = MagicValueAPInt.getZExtValue(); 16675 return true; 16676 } else 16677 return false; 16678 } 16679 16680 case Stmt::BinaryConditionalOperatorClass: 16681 case Stmt::ConditionalOperatorClass: { 16682 const AbstractConditionalOperator *ACO = 16683 cast<AbstractConditionalOperator>(TypeExpr); 16684 bool Result; 16685 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 16686 isConstantEvaluated)) { 16687 if (Result) 16688 TypeExpr = ACO->getTrueExpr(); 16689 else 16690 TypeExpr = ACO->getFalseExpr(); 16691 continue; 16692 } 16693 return false; 16694 } 16695 16696 case Stmt::BinaryOperatorClass: { 16697 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 16698 if (BO->getOpcode() == BO_Comma) { 16699 TypeExpr = BO->getRHS(); 16700 continue; 16701 } 16702 return false; 16703 } 16704 16705 default: 16706 return false; 16707 } 16708 } 16709 } 16710 16711 /// Retrieve the C type corresponding to type tag TypeExpr. 16712 /// 16713 /// \param TypeExpr Expression that specifies a type tag. 16714 /// 16715 /// \param MagicValues Registered magic values. 16716 /// 16717 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 16718 /// kind. 16719 /// 16720 /// \param TypeInfo Information about the corresponding C type. 16721 /// 16722 /// \param isConstantEvaluated whether the evalaution should be performed in 16723 /// constant context. 16724 /// 16725 /// \returns true if the corresponding C type was found. 16726 static bool GetMatchingCType( 16727 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 16728 const ASTContext &Ctx, 16729 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 16730 *MagicValues, 16731 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 16732 bool isConstantEvaluated) { 16733 FoundWrongKind = false; 16734 16735 // Variable declaration that has type_tag_for_datatype attribute. 16736 const ValueDecl *VD = nullptr; 16737 16738 uint64_t MagicValue; 16739 16740 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 16741 return false; 16742 16743 if (VD) { 16744 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 16745 if (I->getArgumentKind() != ArgumentKind) { 16746 FoundWrongKind = true; 16747 return false; 16748 } 16749 TypeInfo.Type = I->getMatchingCType(); 16750 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 16751 TypeInfo.MustBeNull = I->getMustBeNull(); 16752 return true; 16753 } 16754 return false; 16755 } 16756 16757 if (!MagicValues) 16758 return false; 16759 16760 llvm::DenseMap<Sema::TypeTagMagicValue, 16761 Sema::TypeTagData>::const_iterator I = 16762 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 16763 if (I == MagicValues->end()) 16764 return false; 16765 16766 TypeInfo = I->second; 16767 return true; 16768 } 16769 16770 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 16771 uint64_t MagicValue, QualType Type, 16772 bool LayoutCompatible, 16773 bool MustBeNull) { 16774 if (!TypeTagForDatatypeMagicValues) 16775 TypeTagForDatatypeMagicValues.reset( 16776 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 16777 16778 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 16779 (*TypeTagForDatatypeMagicValues)[Magic] = 16780 TypeTagData(Type, LayoutCompatible, MustBeNull); 16781 } 16782 16783 static bool IsSameCharType(QualType T1, QualType T2) { 16784 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 16785 if (!BT1) 16786 return false; 16787 16788 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 16789 if (!BT2) 16790 return false; 16791 16792 BuiltinType::Kind T1Kind = BT1->getKind(); 16793 BuiltinType::Kind T2Kind = BT2->getKind(); 16794 16795 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 16796 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 16797 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 16798 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 16799 } 16800 16801 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 16802 const ArrayRef<const Expr *> ExprArgs, 16803 SourceLocation CallSiteLoc) { 16804 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 16805 bool IsPointerAttr = Attr->getIsPointer(); 16806 16807 // Retrieve the argument representing the 'type_tag'. 16808 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 16809 if (TypeTagIdxAST >= ExprArgs.size()) { 16810 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16811 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 16812 return; 16813 } 16814 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 16815 bool FoundWrongKind; 16816 TypeTagData TypeInfo; 16817 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 16818 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 16819 TypeInfo, isConstantEvaluated())) { 16820 if (FoundWrongKind) 16821 Diag(TypeTagExpr->getExprLoc(), 16822 diag::warn_type_tag_for_datatype_wrong_kind) 16823 << TypeTagExpr->getSourceRange(); 16824 return; 16825 } 16826 16827 // Retrieve the argument representing the 'arg_idx'. 16828 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 16829 if (ArgumentIdxAST >= ExprArgs.size()) { 16830 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16831 << 1 << Attr->getArgumentIdx().getSourceIndex(); 16832 return; 16833 } 16834 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 16835 if (IsPointerAttr) { 16836 // Skip implicit cast of pointer to `void *' (as a function argument). 16837 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 16838 if (ICE->getType()->isVoidPointerType() && 16839 ICE->getCastKind() == CK_BitCast) 16840 ArgumentExpr = ICE->getSubExpr(); 16841 } 16842 QualType ArgumentType = ArgumentExpr->getType(); 16843 16844 // Passing a `void*' pointer shouldn't trigger a warning. 16845 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 16846 return; 16847 16848 if (TypeInfo.MustBeNull) { 16849 // Type tag with matching void type requires a null pointer. 16850 if (!ArgumentExpr->isNullPointerConstant(Context, 16851 Expr::NPC_ValueDependentIsNotNull)) { 16852 Diag(ArgumentExpr->getExprLoc(), 16853 diag::warn_type_safety_null_pointer_required) 16854 << ArgumentKind->getName() 16855 << ArgumentExpr->getSourceRange() 16856 << TypeTagExpr->getSourceRange(); 16857 } 16858 return; 16859 } 16860 16861 QualType RequiredType = TypeInfo.Type; 16862 if (IsPointerAttr) 16863 RequiredType = Context.getPointerType(RequiredType); 16864 16865 bool mismatch = false; 16866 if (!TypeInfo.LayoutCompatible) { 16867 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 16868 16869 // C++11 [basic.fundamental] p1: 16870 // Plain char, signed char, and unsigned char are three distinct types. 16871 // 16872 // But we treat plain `char' as equivalent to `signed char' or `unsigned 16873 // char' depending on the current char signedness mode. 16874 if (mismatch) 16875 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 16876 RequiredType->getPointeeType())) || 16877 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 16878 mismatch = false; 16879 } else 16880 if (IsPointerAttr) 16881 mismatch = !isLayoutCompatible(Context, 16882 ArgumentType->getPointeeType(), 16883 RequiredType->getPointeeType()); 16884 else 16885 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 16886 16887 if (mismatch) 16888 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 16889 << ArgumentType << ArgumentKind 16890 << TypeInfo.LayoutCompatible << RequiredType 16891 << ArgumentExpr->getSourceRange() 16892 << TypeTagExpr->getSourceRange(); 16893 } 16894 16895 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 16896 CharUnits Alignment) { 16897 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16898 } 16899 16900 void Sema::DiagnoseMisalignedMembers() { 16901 for (MisalignedMember &m : MisalignedMembers) { 16902 const NamedDecl *ND = m.RD; 16903 if (ND->getName().empty()) { 16904 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16905 ND = TD; 16906 } 16907 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16908 << m.MD << ND << m.E->getSourceRange(); 16909 } 16910 MisalignedMembers.clear(); 16911 } 16912 16913 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16914 E = E->IgnoreParens(); 16915 if (!T->isPointerType() && !T->isIntegerType()) 16916 return; 16917 if (isa<UnaryOperator>(E) && 16918 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16919 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16920 if (isa<MemberExpr>(Op)) { 16921 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16922 if (MA != MisalignedMembers.end() && 16923 (T->isIntegerType() || 16924 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16925 Context.getTypeAlignInChars( 16926 T->getPointeeType()) <= MA->Alignment)))) 16927 MisalignedMembers.erase(MA); 16928 } 16929 } 16930 } 16931 16932 void Sema::RefersToMemberWithReducedAlignment( 16933 Expr *E, 16934 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16935 Action) { 16936 const auto *ME = dyn_cast<MemberExpr>(E); 16937 if (!ME) 16938 return; 16939 16940 // No need to check expressions with an __unaligned-qualified type. 16941 if (E->getType().getQualifiers().hasUnaligned()) 16942 return; 16943 16944 // For a chain of MemberExpr like "a.b.c.d" this list 16945 // will keep FieldDecl's like [d, c, b]. 16946 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16947 const MemberExpr *TopME = nullptr; 16948 bool AnyIsPacked = false; 16949 do { 16950 QualType BaseType = ME->getBase()->getType(); 16951 if (BaseType->isDependentType()) 16952 return; 16953 if (ME->isArrow()) 16954 BaseType = BaseType->getPointeeType(); 16955 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16956 if (RD->isInvalidDecl()) 16957 return; 16958 16959 ValueDecl *MD = ME->getMemberDecl(); 16960 auto *FD = dyn_cast<FieldDecl>(MD); 16961 // We do not care about non-data members. 16962 if (!FD || FD->isInvalidDecl()) 16963 return; 16964 16965 AnyIsPacked = 16966 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16967 ReverseMemberChain.push_back(FD); 16968 16969 TopME = ME; 16970 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16971 } while (ME); 16972 assert(TopME && "We did not compute a topmost MemberExpr!"); 16973 16974 // Not the scope of this diagnostic. 16975 if (!AnyIsPacked) 16976 return; 16977 16978 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 16979 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 16980 // TODO: The innermost base of the member expression may be too complicated. 16981 // For now, just disregard these cases. This is left for future 16982 // improvement. 16983 if (!DRE && !isa<CXXThisExpr>(TopBase)) 16984 return; 16985 16986 // Alignment expected by the whole expression. 16987 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 16988 16989 // No need to do anything else with this case. 16990 if (ExpectedAlignment.isOne()) 16991 return; 16992 16993 // Synthesize offset of the whole access. 16994 CharUnits Offset; 16995 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain)) 16996 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD)); 16997 16998 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 16999 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 17000 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 17001 17002 // The base expression of the innermost MemberExpr may give 17003 // stronger guarantees than the class containing the member. 17004 if (DRE && !TopME->isArrow()) { 17005 const ValueDecl *VD = DRE->getDecl(); 17006 if (!VD->getType()->isReferenceType()) 17007 CompleteObjectAlignment = 17008 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 17009 } 17010 17011 // Check if the synthesized offset fulfills the alignment. 17012 if (Offset % ExpectedAlignment != 0 || 17013 // It may fulfill the offset it but the effective alignment may still be 17014 // lower than the expected expression alignment. 17015 CompleteObjectAlignment < ExpectedAlignment) { 17016 // If this happens, we want to determine a sensible culprit of this. 17017 // Intuitively, watching the chain of member expressions from right to 17018 // left, we start with the required alignment (as required by the field 17019 // type) but some packed attribute in that chain has reduced the alignment. 17020 // It may happen that another packed structure increases it again. But if 17021 // we are here such increase has not been enough. So pointing the first 17022 // FieldDecl that either is packed or else its RecordDecl is, 17023 // seems reasonable. 17024 FieldDecl *FD = nullptr; 17025 CharUnits Alignment; 17026 for (FieldDecl *FDI : ReverseMemberChain) { 17027 if (FDI->hasAttr<PackedAttr>() || 17028 FDI->getParent()->hasAttr<PackedAttr>()) { 17029 FD = FDI; 17030 Alignment = std::min( 17031 Context.getTypeAlignInChars(FD->getType()), 17032 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 17033 break; 17034 } 17035 } 17036 assert(FD && "We did not find a packed FieldDecl!"); 17037 Action(E, FD->getParent(), FD, Alignment); 17038 } 17039 } 17040 17041 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 17042 using namespace std::placeholders; 17043 17044 RefersToMemberWithReducedAlignment( 17045 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 17046 _2, _3, _4)); 17047 } 17048 17049 // Check if \p Ty is a valid type for the elementwise math builtins. If it is 17050 // not a valid type, emit an error message and return true. Otherwise return 17051 // false. 17052 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, 17053 QualType Ty) { 17054 if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) { 17055 S.Diag(Loc, diag::err_builtin_invalid_arg_type) 17056 << 1 << /* vector, integer or float ty*/ 0 << Ty; 17057 return true; 17058 } 17059 return false; 17060 } 17061 17062 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) { 17063 if (checkArgCount(*this, TheCall, 1)) 17064 return true; 17065 17066 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 17067 if (A.isInvalid()) 17068 return true; 17069 17070 TheCall->setArg(0, A.get()); 17071 QualType TyA = A.get()->getType(); 17072 17073 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA)) 17074 return true; 17075 17076 TheCall->setType(TyA); 17077 return false; 17078 } 17079 17080 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) { 17081 if (checkArgCount(*this, TheCall, 2)) 17082 return true; 17083 17084 ExprResult A = TheCall->getArg(0); 17085 ExprResult B = TheCall->getArg(1); 17086 // Do standard promotions between the two arguments, returning their common 17087 // type. 17088 QualType Res = 17089 UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison); 17090 if (A.isInvalid() || B.isInvalid()) 17091 return true; 17092 17093 QualType TyA = A.get()->getType(); 17094 QualType TyB = B.get()->getType(); 17095 17096 if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType()) 17097 return Diag(A.get()->getBeginLoc(), 17098 diag::err_typecheck_call_different_arg_types) 17099 << TyA << TyB; 17100 17101 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA)) 17102 return true; 17103 17104 TheCall->setArg(0, A.get()); 17105 TheCall->setArg(1, B.get()); 17106 TheCall->setType(Res); 17107 return false; 17108 } 17109 17110 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) { 17111 if (checkArgCount(*this, TheCall, 1)) 17112 return true; 17113 17114 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 17115 if (A.isInvalid()) 17116 return true; 17117 17118 TheCall->setArg(0, A.get()); 17119 return false; 17120 } 17121 17122 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 17123 ExprResult CallResult) { 17124 if (checkArgCount(*this, TheCall, 1)) 17125 return ExprError(); 17126 17127 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 17128 if (MatrixArg.isInvalid()) 17129 return MatrixArg; 17130 Expr *Matrix = MatrixArg.get(); 17131 17132 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 17133 if (!MType) { 17134 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17135 << 1 << /* matrix ty*/ 1 << Matrix->getType(); 17136 return ExprError(); 17137 } 17138 17139 // Create returned matrix type by swapping rows and columns of the argument 17140 // matrix type. 17141 QualType ResultType = Context.getConstantMatrixType( 17142 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 17143 17144 // Change the return type to the type of the returned matrix. 17145 TheCall->setType(ResultType); 17146 17147 // Update call argument to use the possibly converted matrix argument. 17148 TheCall->setArg(0, Matrix); 17149 return CallResult; 17150 } 17151 17152 // Get and verify the matrix dimensions. 17153 static llvm::Optional<unsigned> 17154 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 17155 SourceLocation ErrorPos; 17156 Optional<llvm::APSInt> Value = 17157 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 17158 if (!Value) { 17159 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 17160 << Name; 17161 return {}; 17162 } 17163 uint64_t Dim = Value->getZExtValue(); 17164 if (!ConstantMatrixType::isDimensionValid(Dim)) { 17165 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 17166 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 17167 return {}; 17168 } 17169 return Dim; 17170 } 17171 17172 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 17173 ExprResult CallResult) { 17174 if (!getLangOpts().MatrixTypes) { 17175 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 17176 return ExprError(); 17177 } 17178 17179 if (checkArgCount(*this, TheCall, 4)) 17180 return ExprError(); 17181 17182 unsigned PtrArgIdx = 0; 17183 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 17184 Expr *RowsExpr = TheCall->getArg(1); 17185 Expr *ColumnsExpr = TheCall->getArg(2); 17186 Expr *StrideExpr = TheCall->getArg(3); 17187 17188 bool ArgError = false; 17189 17190 // Check pointer argument. 17191 { 17192 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 17193 if (PtrConv.isInvalid()) 17194 return PtrConv; 17195 PtrExpr = PtrConv.get(); 17196 TheCall->setArg(0, PtrExpr); 17197 if (PtrExpr->isTypeDependent()) { 17198 TheCall->setType(Context.DependentTy); 17199 return TheCall; 17200 } 17201 } 17202 17203 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 17204 QualType ElementTy; 17205 if (!PtrTy) { 17206 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17207 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 17208 ArgError = true; 17209 } else { 17210 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 17211 17212 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 17213 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17214 << PtrArgIdx + 1 << /* pointer to element ty*/ 2 17215 << PtrExpr->getType(); 17216 ArgError = true; 17217 } 17218 } 17219 17220 // Apply default Lvalue conversions and convert the expression to size_t. 17221 auto ApplyArgumentConversions = [this](Expr *E) { 17222 ExprResult Conv = DefaultLvalueConversion(E); 17223 if (Conv.isInvalid()) 17224 return Conv; 17225 17226 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 17227 }; 17228 17229 // Apply conversion to row and column expressions. 17230 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 17231 if (!RowsConv.isInvalid()) { 17232 RowsExpr = RowsConv.get(); 17233 TheCall->setArg(1, RowsExpr); 17234 } else 17235 RowsExpr = nullptr; 17236 17237 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 17238 if (!ColumnsConv.isInvalid()) { 17239 ColumnsExpr = ColumnsConv.get(); 17240 TheCall->setArg(2, ColumnsExpr); 17241 } else 17242 ColumnsExpr = nullptr; 17243 17244 // If any any part of the result matrix type is still pending, just use 17245 // Context.DependentTy, until all parts are resolved. 17246 if ((RowsExpr && RowsExpr->isTypeDependent()) || 17247 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 17248 TheCall->setType(Context.DependentTy); 17249 return CallResult; 17250 } 17251 17252 // Check row and column dimensions. 17253 llvm::Optional<unsigned> MaybeRows; 17254 if (RowsExpr) 17255 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 17256 17257 llvm::Optional<unsigned> MaybeColumns; 17258 if (ColumnsExpr) 17259 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 17260 17261 // Check stride argument. 17262 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 17263 if (StrideConv.isInvalid()) 17264 return ExprError(); 17265 StrideExpr = StrideConv.get(); 17266 TheCall->setArg(3, StrideExpr); 17267 17268 if (MaybeRows) { 17269 if (Optional<llvm::APSInt> Value = 17270 StrideExpr->getIntegerConstantExpr(Context)) { 17271 uint64_t Stride = Value->getZExtValue(); 17272 if (Stride < *MaybeRows) { 17273 Diag(StrideExpr->getBeginLoc(), 17274 diag::err_builtin_matrix_stride_too_small); 17275 ArgError = true; 17276 } 17277 } 17278 } 17279 17280 if (ArgError || !MaybeRows || !MaybeColumns) 17281 return ExprError(); 17282 17283 TheCall->setType( 17284 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 17285 return CallResult; 17286 } 17287 17288 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 17289 ExprResult CallResult) { 17290 if (checkArgCount(*this, TheCall, 3)) 17291 return ExprError(); 17292 17293 unsigned PtrArgIdx = 1; 17294 Expr *MatrixExpr = TheCall->getArg(0); 17295 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 17296 Expr *StrideExpr = TheCall->getArg(2); 17297 17298 bool ArgError = false; 17299 17300 { 17301 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 17302 if (MatrixConv.isInvalid()) 17303 return MatrixConv; 17304 MatrixExpr = MatrixConv.get(); 17305 TheCall->setArg(0, MatrixExpr); 17306 } 17307 if (MatrixExpr->isTypeDependent()) { 17308 TheCall->setType(Context.DependentTy); 17309 return TheCall; 17310 } 17311 17312 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 17313 if (!MatrixTy) { 17314 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17315 << 1 << /*matrix ty */ 1 << MatrixExpr->getType(); 17316 ArgError = true; 17317 } 17318 17319 { 17320 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 17321 if (PtrConv.isInvalid()) 17322 return PtrConv; 17323 PtrExpr = PtrConv.get(); 17324 TheCall->setArg(1, PtrExpr); 17325 if (PtrExpr->isTypeDependent()) { 17326 TheCall->setType(Context.DependentTy); 17327 return TheCall; 17328 } 17329 } 17330 17331 // Check pointer argument. 17332 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 17333 if (!PtrTy) { 17334 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17335 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 17336 ArgError = true; 17337 } else { 17338 QualType ElementTy = PtrTy->getPointeeType(); 17339 if (ElementTy.isConstQualified()) { 17340 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 17341 ArgError = true; 17342 } 17343 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 17344 if (MatrixTy && 17345 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 17346 Diag(PtrExpr->getBeginLoc(), 17347 diag::err_builtin_matrix_pointer_arg_mismatch) 17348 << ElementTy << MatrixTy->getElementType(); 17349 ArgError = true; 17350 } 17351 } 17352 17353 // Apply default Lvalue conversions and convert the stride expression to 17354 // size_t. 17355 { 17356 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 17357 if (StrideConv.isInvalid()) 17358 return StrideConv; 17359 17360 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 17361 if (StrideConv.isInvalid()) 17362 return StrideConv; 17363 StrideExpr = StrideConv.get(); 17364 TheCall->setArg(2, StrideExpr); 17365 } 17366 17367 // Check stride argument. 17368 if (MatrixTy) { 17369 if (Optional<llvm::APSInt> Value = 17370 StrideExpr->getIntegerConstantExpr(Context)) { 17371 uint64_t Stride = Value->getZExtValue(); 17372 if (Stride < MatrixTy->getNumRows()) { 17373 Diag(StrideExpr->getBeginLoc(), 17374 diag::err_builtin_matrix_stride_too_small); 17375 ArgError = true; 17376 } 17377 } 17378 } 17379 17380 if (ArgError) 17381 return ExprError(); 17382 17383 return CallResult; 17384 } 17385 17386 /// \brief Enforce the bounds of a TCB 17387 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 17388 /// directly calls other functions in the same TCB as marked by the enforce_tcb 17389 /// and enforce_tcb_leaf attributes. 17390 void Sema::CheckTCBEnforcement(const SourceLocation CallExprLoc, 17391 const NamedDecl *Callee) { 17392 const NamedDecl *Caller = getCurFunctionOrMethodDecl(); 17393 17394 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>()) 17395 return; 17396 17397 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 17398 // all TCBs the callee is a part of. 17399 llvm::StringSet<> CalleeTCBs; 17400 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 17401 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 17402 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 17403 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 17404 17405 // Go through the TCBs the caller is a part of and emit warnings if Caller 17406 // is in a TCB that the Callee is not. 17407 for_each( 17408 Caller->specific_attrs<EnforceTCBAttr>(), 17409 [&](const auto *A) { 17410 StringRef CallerTCB = A->getTCBName(); 17411 if (CalleeTCBs.count(CallerTCB) == 0) { 17412 this->Diag(CallExprLoc, diag::warn_tcb_enforcement_violation) 17413 << Callee << CallerTCB; 17414 } 17415 }); 17416 } 17417