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 // Check if byteselect is in [0, 3] 4102 case RISCV::BI__builtin_riscv_aes32dsi_32: 4103 case RISCV::BI__builtin_riscv_aes32dsmi_32: 4104 case RISCV::BI__builtin_riscv_aes32esi_32: 4105 case RISCV::BI__builtin_riscv_aes32esmi_32: 4106 case RISCV::BI__builtin_riscv_sm4ks: 4107 case RISCV::BI__builtin_riscv_sm4ed: 4108 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 4109 // Check if rnum is in [0, 10] 4110 case RISCV::BI__builtin_riscv_aes64ks1i_64: 4111 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 10); 4112 } 4113 4114 return false; 4115 } 4116 4117 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 4118 CallExpr *TheCall) { 4119 if (BuiltinID == SystemZ::BI__builtin_tabort) { 4120 Expr *Arg = TheCall->getArg(0); 4121 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 4122 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 4123 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 4124 << Arg->getSourceRange(); 4125 } 4126 4127 // For intrinsics which take an immediate value as part of the instruction, 4128 // range check them here. 4129 unsigned i = 0, l = 0, u = 0; 4130 switch (BuiltinID) { 4131 default: return false; 4132 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 4133 case SystemZ::BI__builtin_s390_verimb: 4134 case SystemZ::BI__builtin_s390_verimh: 4135 case SystemZ::BI__builtin_s390_verimf: 4136 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 4137 case SystemZ::BI__builtin_s390_vfaeb: 4138 case SystemZ::BI__builtin_s390_vfaeh: 4139 case SystemZ::BI__builtin_s390_vfaef: 4140 case SystemZ::BI__builtin_s390_vfaebs: 4141 case SystemZ::BI__builtin_s390_vfaehs: 4142 case SystemZ::BI__builtin_s390_vfaefs: 4143 case SystemZ::BI__builtin_s390_vfaezb: 4144 case SystemZ::BI__builtin_s390_vfaezh: 4145 case SystemZ::BI__builtin_s390_vfaezf: 4146 case SystemZ::BI__builtin_s390_vfaezbs: 4147 case SystemZ::BI__builtin_s390_vfaezhs: 4148 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 4149 case SystemZ::BI__builtin_s390_vfisb: 4150 case SystemZ::BI__builtin_s390_vfidb: 4151 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 4152 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 4153 case SystemZ::BI__builtin_s390_vftcisb: 4154 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 4155 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 4156 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 4157 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 4158 case SystemZ::BI__builtin_s390_vstrcb: 4159 case SystemZ::BI__builtin_s390_vstrch: 4160 case SystemZ::BI__builtin_s390_vstrcf: 4161 case SystemZ::BI__builtin_s390_vstrczb: 4162 case SystemZ::BI__builtin_s390_vstrczh: 4163 case SystemZ::BI__builtin_s390_vstrczf: 4164 case SystemZ::BI__builtin_s390_vstrcbs: 4165 case SystemZ::BI__builtin_s390_vstrchs: 4166 case SystemZ::BI__builtin_s390_vstrcfs: 4167 case SystemZ::BI__builtin_s390_vstrczbs: 4168 case SystemZ::BI__builtin_s390_vstrczhs: 4169 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 4170 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 4171 case SystemZ::BI__builtin_s390_vfminsb: 4172 case SystemZ::BI__builtin_s390_vfmaxsb: 4173 case SystemZ::BI__builtin_s390_vfmindb: 4174 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 4175 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 4176 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 4177 case SystemZ::BI__builtin_s390_vclfnhs: 4178 case SystemZ::BI__builtin_s390_vclfnls: 4179 case SystemZ::BI__builtin_s390_vcfn: 4180 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break; 4181 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break; 4182 } 4183 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 4184 } 4185 4186 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 4187 /// This checks that the target supports __builtin_cpu_supports and 4188 /// that the string argument is constant and valid. 4189 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 4190 CallExpr *TheCall) { 4191 Expr *Arg = TheCall->getArg(0); 4192 4193 // Check if the argument is a string literal. 4194 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4195 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 4196 << Arg->getSourceRange(); 4197 4198 // Check the contents of the string. 4199 StringRef Feature = 4200 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4201 if (!TI.validateCpuSupports(Feature)) 4202 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 4203 << Arg->getSourceRange(); 4204 return false; 4205 } 4206 4207 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 4208 /// This checks that the target supports __builtin_cpu_is and 4209 /// that the string argument is constant and valid. 4210 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 4211 Expr *Arg = TheCall->getArg(0); 4212 4213 // Check if the argument is a string literal. 4214 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 4215 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 4216 << Arg->getSourceRange(); 4217 4218 // Check the contents of the string. 4219 StringRef Feature = 4220 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 4221 if (!TI.validateCpuIs(Feature)) 4222 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 4223 << Arg->getSourceRange(); 4224 return false; 4225 } 4226 4227 // Check if the rounding mode is legal. 4228 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 4229 // Indicates if this instruction has rounding control or just SAE. 4230 bool HasRC = false; 4231 4232 unsigned ArgNum = 0; 4233 switch (BuiltinID) { 4234 default: 4235 return false; 4236 case X86::BI__builtin_ia32_vcvttsd2si32: 4237 case X86::BI__builtin_ia32_vcvttsd2si64: 4238 case X86::BI__builtin_ia32_vcvttsd2usi32: 4239 case X86::BI__builtin_ia32_vcvttsd2usi64: 4240 case X86::BI__builtin_ia32_vcvttss2si32: 4241 case X86::BI__builtin_ia32_vcvttss2si64: 4242 case X86::BI__builtin_ia32_vcvttss2usi32: 4243 case X86::BI__builtin_ia32_vcvttss2usi64: 4244 case X86::BI__builtin_ia32_vcvttsh2si32: 4245 case X86::BI__builtin_ia32_vcvttsh2si64: 4246 case X86::BI__builtin_ia32_vcvttsh2usi32: 4247 case X86::BI__builtin_ia32_vcvttsh2usi64: 4248 ArgNum = 1; 4249 break; 4250 case X86::BI__builtin_ia32_maxpd512: 4251 case X86::BI__builtin_ia32_maxps512: 4252 case X86::BI__builtin_ia32_minpd512: 4253 case X86::BI__builtin_ia32_minps512: 4254 case X86::BI__builtin_ia32_maxph512: 4255 case X86::BI__builtin_ia32_minph512: 4256 ArgNum = 2; 4257 break; 4258 case X86::BI__builtin_ia32_vcvtph2pd512_mask: 4259 case X86::BI__builtin_ia32_vcvtph2psx512_mask: 4260 case X86::BI__builtin_ia32_cvtps2pd512_mask: 4261 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 4262 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 4263 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 4264 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 4265 case X86::BI__builtin_ia32_cvttps2dq512_mask: 4266 case X86::BI__builtin_ia32_cvttps2qq512_mask: 4267 case X86::BI__builtin_ia32_cvttps2udq512_mask: 4268 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 4269 case X86::BI__builtin_ia32_vcvttph2w512_mask: 4270 case X86::BI__builtin_ia32_vcvttph2uw512_mask: 4271 case X86::BI__builtin_ia32_vcvttph2dq512_mask: 4272 case X86::BI__builtin_ia32_vcvttph2udq512_mask: 4273 case X86::BI__builtin_ia32_vcvttph2qq512_mask: 4274 case X86::BI__builtin_ia32_vcvttph2uqq512_mask: 4275 case X86::BI__builtin_ia32_exp2pd_mask: 4276 case X86::BI__builtin_ia32_exp2ps_mask: 4277 case X86::BI__builtin_ia32_getexppd512_mask: 4278 case X86::BI__builtin_ia32_getexpps512_mask: 4279 case X86::BI__builtin_ia32_getexpph512_mask: 4280 case X86::BI__builtin_ia32_rcp28pd_mask: 4281 case X86::BI__builtin_ia32_rcp28ps_mask: 4282 case X86::BI__builtin_ia32_rsqrt28pd_mask: 4283 case X86::BI__builtin_ia32_rsqrt28ps_mask: 4284 case X86::BI__builtin_ia32_vcomisd: 4285 case X86::BI__builtin_ia32_vcomiss: 4286 case X86::BI__builtin_ia32_vcomish: 4287 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 4288 ArgNum = 3; 4289 break; 4290 case X86::BI__builtin_ia32_cmppd512_mask: 4291 case X86::BI__builtin_ia32_cmpps512_mask: 4292 case X86::BI__builtin_ia32_cmpsd_mask: 4293 case X86::BI__builtin_ia32_cmpss_mask: 4294 case X86::BI__builtin_ia32_cmpsh_mask: 4295 case X86::BI__builtin_ia32_vcvtsh2sd_round_mask: 4296 case X86::BI__builtin_ia32_vcvtsh2ss_round_mask: 4297 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 4298 case X86::BI__builtin_ia32_getexpsd128_round_mask: 4299 case X86::BI__builtin_ia32_getexpss128_round_mask: 4300 case X86::BI__builtin_ia32_getexpsh128_round_mask: 4301 case X86::BI__builtin_ia32_getmantpd512_mask: 4302 case X86::BI__builtin_ia32_getmantps512_mask: 4303 case X86::BI__builtin_ia32_getmantph512_mask: 4304 case X86::BI__builtin_ia32_maxsd_round_mask: 4305 case X86::BI__builtin_ia32_maxss_round_mask: 4306 case X86::BI__builtin_ia32_maxsh_round_mask: 4307 case X86::BI__builtin_ia32_minsd_round_mask: 4308 case X86::BI__builtin_ia32_minss_round_mask: 4309 case X86::BI__builtin_ia32_minsh_round_mask: 4310 case X86::BI__builtin_ia32_rcp28sd_round_mask: 4311 case X86::BI__builtin_ia32_rcp28ss_round_mask: 4312 case X86::BI__builtin_ia32_reducepd512_mask: 4313 case X86::BI__builtin_ia32_reduceps512_mask: 4314 case X86::BI__builtin_ia32_reduceph512_mask: 4315 case X86::BI__builtin_ia32_rndscalepd_mask: 4316 case X86::BI__builtin_ia32_rndscaleps_mask: 4317 case X86::BI__builtin_ia32_rndscaleph_mask: 4318 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 4319 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 4320 ArgNum = 4; 4321 break; 4322 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4323 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4324 case X86::BI__builtin_ia32_fixupimmps512_mask: 4325 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4326 case X86::BI__builtin_ia32_fixupimmsd_mask: 4327 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4328 case X86::BI__builtin_ia32_fixupimmss_mask: 4329 case X86::BI__builtin_ia32_fixupimmss_maskz: 4330 case X86::BI__builtin_ia32_getmantsd_round_mask: 4331 case X86::BI__builtin_ia32_getmantss_round_mask: 4332 case X86::BI__builtin_ia32_getmantsh_round_mask: 4333 case X86::BI__builtin_ia32_rangepd512_mask: 4334 case X86::BI__builtin_ia32_rangeps512_mask: 4335 case X86::BI__builtin_ia32_rangesd128_round_mask: 4336 case X86::BI__builtin_ia32_rangess128_round_mask: 4337 case X86::BI__builtin_ia32_reducesd_mask: 4338 case X86::BI__builtin_ia32_reducess_mask: 4339 case X86::BI__builtin_ia32_reducesh_mask: 4340 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4341 case X86::BI__builtin_ia32_rndscaless_round_mask: 4342 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4343 ArgNum = 5; 4344 break; 4345 case X86::BI__builtin_ia32_vcvtsd2si64: 4346 case X86::BI__builtin_ia32_vcvtsd2si32: 4347 case X86::BI__builtin_ia32_vcvtsd2usi32: 4348 case X86::BI__builtin_ia32_vcvtsd2usi64: 4349 case X86::BI__builtin_ia32_vcvtss2si32: 4350 case X86::BI__builtin_ia32_vcvtss2si64: 4351 case X86::BI__builtin_ia32_vcvtss2usi32: 4352 case X86::BI__builtin_ia32_vcvtss2usi64: 4353 case X86::BI__builtin_ia32_vcvtsh2si32: 4354 case X86::BI__builtin_ia32_vcvtsh2si64: 4355 case X86::BI__builtin_ia32_vcvtsh2usi32: 4356 case X86::BI__builtin_ia32_vcvtsh2usi64: 4357 case X86::BI__builtin_ia32_sqrtpd512: 4358 case X86::BI__builtin_ia32_sqrtps512: 4359 case X86::BI__builtin_ia32_sqrtph512: 4360 ArgNum = 1; 4361 HasRC = true; 4362 break; 4363 case X86::BI__builtin_ia32_addph512: 4364 case X86::BI__builtin_ia32_divph512: 4365 case X86::BI__builtin_ia32_mulph512: 4366 case X86::BI__builtin_ia32_subph512: 4367 case X86::BI__builtin_ia32_addpd512: 4368 case X86::BI__builtin_ia32_addps512: 4369 case X86::BI__builtin_ia32_divpd512: 4370 case X86::BI__builtin_ia32_divps512: 4371 case X86::BI__builtin_ia32_mulpd512: 4372 case X86::BI__builtin_ia32_mulps512: 4373 case X86::BI__builtin_ia32_subpd512: 4374 case X86::BI__builtin_ia32_subps512: 4375 case X86::BI__builtin_ia32_cvtsi2sd64: 4376 case X86::BI__builtin_ia32_cvtsi2ss32: 4377 case X86::BI__builtin_ia32_cvtsi2ss64: 4378 case X86::BI__builtin_ia32_cvtusi2sd64: 4379 case X86::BI__builtin_ia32_cvtusi2ss32: 4380 case X86::BI__builtin_ia32_cvtusi2ss64: 4381 case X86::BI__builtin_ia32_vcvtusi2sh: 4382 case X86::BI__builtin_ia32_vcvtusi642sh: 4383 case X86::BI__builtin_ia32_vcvtsi2sh: 4384 case X86::BI__builtin_ia32_vcvtsi642sh: 4385 ArgNum = 2; 4386 HasRC = true; 4387 break; 4388 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 4389 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 4390 case X86::BI__builtin_ia32_vcvtpd2ph512_mask: 4391 case X86::BI__builtin_ia32_vcvtps2phx512_mask: 4392 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 4393 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 4394 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 4395 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 4396 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 4397 case X86::BI__builtin_ia32_cvtps2dq512_mask: 4398 case X86::BI__builtin_ia32_cvtps2qq512_mask: 4399 case X86::BI__builtin_ia32_cvtps2udq512_mask: 4400 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 4401 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 4402 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 4403 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 4404 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 4405 case X86::BI__builtin_ia32_vcvtdq2ph512_mask: 4406 case X86::BI__builtin_ia32_vcvtudq2ph512_mask: 4407 case X86::BI__builtin_ia32_vcvtw2ph512_mask: 4408 case X86::BI__builtin_ia32_vcvtuw2ph512_mask: 4409 case X86::BI__builtin_ia32_vcvtph2w512_mask: 4410 case X86::BI__builtin_ia32_vcvtph2uw512_mask: 4411 case X86::BI__builtin_ia32_vcvtph2dq512_mask: 4412 case X86::BI__builtin_ia32_vcvtph2udq512_mask: 4413 case X86::BI__builtin_ia32_vcvtph2qq512_mask: 4414 case X86::BI__builtin_ia32_vcvtph2uqq512_mask: 4415 case X86::BI__builtin_ia32_vcvtqq2ph512_mask: 4416 case X86::BI__builtin_ia32_vcvtuqq2ph512_mask: 4417 ArgNum = 3; 4418 HasRC = true; 4419 break; 4420 case X86::BI__builtin_ia32_addsh_round_mask: 4421 case X86::BI__builtin_ia32_addss_round_mask: 4422 case X86::BI__builtin_ia32_addsd_round_mask: 4423 case X86::BI__builtin_ia32_divsh_round_mask: 4424 case X86::BI__builtin_ia32_divss_round_mask: 4425 case X86::BI__builtin_ia32_divsd_round_mask: 4426 case X86::BI__builtin_ia32_mulsh_round_mask: 4427 case X86::BI__builtin_ia32_mulss_round_mask: 4428 case X86::BI__builtin_ia32_mulsd_round_mask: 4429 case X86::BI__builtin_ia32_subsh_round_mask: 4430 case X86::BI__builtin_ia32_subss_round_mask: 4431 case X86::BI__builtin_ia32_subsd_round_mask: 4432 case X86::BI__builtin_ia32_scalefph512_mask: 4433 case X86::BI__builtin_ia32_scalefpd512_mask: 4434 case X86::BI__builtin_ia32_scalefps512_mask: 4435 case X86::BI__builtin_ia32_scalefsd_round_mask: 4436 case X86::BI__builtin_ia32_scalefss_round_mask: 4437 case X86::BI__builtin_ia32_scalefsh_round_mask: 4438 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 4439 case X86::BI__builtin_ia32_vcvtss2sh_round_mask: 4440 case X86::BI__builtin_ia32_vcvtsd2sh_round_mask: 4441 case X86::BI__builtin_ia32_sqrtsd_round_mask: 4442 case X86::BI__builtin_ia32_sqrtss_round_mask: 4443 case X86::BI__builtin_ia32_sqrtsh_round_mask: 4444 case X86::BI__builtin_ia32_vfmaddsd3_mask: 4445 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 4446 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 4447 case X86::BI__builtin_ia32_vfmaddss3_mask: 4448 case X86::BI__builtin_ia32_vfmaddss3_maskz: 4449 case X86::BI__builtin_ia32_vfmaddss3_mask3: 4450 case X86::BI__builtin_ia32_vfmaddsh3_mask: 4451 case X86::BI__builtin_ia32_vfmaddsh3_maskz: 4452 case X86::BI__builtin_ia32_vfmaddsh3_mask3: 4453 case X86::BI__builtin_ia32_vfmaddpd512_mask: 4454 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 4455 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 4456 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 4457 case X86::BI__builtin_ia32_vfmaddps512_mask: 4458 case X86::BI__builtin_ia32_vfmaddps512_maskz: 4459 case X86::BI__builtin_ia32_vfmaddps512_mask3: 4460 case X86::BI__builtin_ia32_vfmsubps512_mask3: 4461 case X86::BI__builtin_ia32_vfmaddph512_mask: 4462 case X86::BI__builtin_ia32_vfmaddph512_maskz: 4463 case X86::BI__builtin_ia32_vfmaddph512_mask3: 4464 case X86::BI__builtin_ia32_vfmsubph512_mask3: 4465 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 4466 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 4467 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 4468 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 4469 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 4470 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 4471 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 4472 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 4473 case X86::BI__builtin_ia32_vfmaddsubph512_mask: 4474 case X86::BI__builtin_ia32_vfmaddsubph512_maskz: 4475 case X86::BI__builtin_ia32_vfmaddsubph512_mask3: 4476 case X86::BI__builtin_ia32_vfmsubaddph512_mask3: 4477 case X86::BI__builtin_ia32_vfmaddcsh_mask: 4478 case X86::BI__builtin_ia32_vfmaddcsh_round_mask: 4479 case X86::BI__builtin_ia32_vfmaddcsh_round_mask3: 4480 case X86::BI__builtin_ia32_vfmaddcph512_mask: 4481 case X86::BI__builtin_ia32_vfmaddcph512_maskz: 4482 case X86::BI__builtin_ia32_vfmaddcph512_mask3: 4483 case X86::BI__builtin_ia32_vfcmaddcsh_mask: 4484 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask: 4485 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3: 4486 case X86::BI__builtin_ia32_vfcmaddcph512_mask: 4487 case X86::BI__builtin_ia32_vfcmaddcph512_maskz: 4488 case X86::BI__builtin_ia32_vfcmaddcph512_mask3: 4489 case X86::BI__builtin_ia32_vfmulcsh_mask: 4490 case X86::BI__builtin_ia32_vfmulcph512_mask: 4491 case X86::BI__builtin_ia32_vfcmulcsh_mask: 4492 case X86::BI__builtin_ia32_vfcmulcph512_mask: 4493 ArgNum = 4; 4494 HasRC = true; 4495 break; 4496 } 4497 4498 llvm::APSInt Result; 4499 4500 // We can't check the value of a dependent argument. 4501 Expr *Arg = TheCall->getArg(ArgNum); 4502 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4503 return false; 4504 4505 // Check constant-ness first. 4506 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4507 return true; 4508 4509 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 4510 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 4511 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 4512 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 4513 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 4514 Result == 8/*ROUND_NO_EXC*/ || 4515 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 4516 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 4517 return false; 4518 4519 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 4520 << Arg->getSourceRange(); 4521 } 4522 4523 // Check if the gather/scatter scale is legal. 4524 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 4525 CallExpr *TheCall) { 4526 unsigned ArgNum = 0; 4527 switch (BuiltinID) { 4528 default: 4529 return false; 4530 case X86::BI__builtin_ia32_gatherpfdpd: 4531 case X86::BI__builtin_ia32_gatherpfdps: 4532 case X86::BI__builtin_ia32_gatherpfqpd: 4533 case X86::BI__builtin_ia32_gatherpfqps: 4534 case X86::BI__builtin_ia32_scatterpfdpd: 4535 case X86::BI__builtin_ia32_scatterpfdps: 4536 case X86::BI__builtin_ia32_scatterpfqpd: 4537 case X86::BI__builtin_ia32_scatterpfqps: 4538 ArgNum = 3; 4539 break; 4540 case X86::BI__builtin_ia32_gatherd_pd: 4541 case X86::BI__builtin_ia32_gatherd_pd256: 4542 case X86::BI__builtin_ia32_gatherq_pd: 4543 case X86::BI__builtin_ia32_gatherq_pd256: 4544 case X86::BI__builtin_ia32_gatherd_ps: 4545 case X86::BI__builtin_ia32_gatherd_ps256: 4546 case X86::BI__builtin_ia32_gatherq_ps: 4547 case X86::BI__builtin_ia32_gatherq_ps256: 4548 case X86::BI__builtin_ia32_gatherd_q: 4549 case X86::BI__builtin_ia32_gatherd_q256: 4550 case X86::BI__builtin_ia32_gatherq_q: 4551 case X86::BI__builtin_ia32_gatherq_q256: 4552 case X86::BI__builtin_ia32_gatherd_d: 4553 case X86::BI__builtin_ia32_gatherd_d256: 4554 case X86::BI__builtin_ia32_gatherq_d: 4555 case X86::BI__builtin_ia32_gatherq_d256: 4556 case X86::BI__builtin_ia32_gather3div2df: 4557 case X86::BI__builtin_ia32_gather3div2di: 4558 case X86::BI__builtin_ia32_gather3div4df: 4559 case X86::BI__builtin_ia32_gather3div4di: 4560 case X86::BI__builtin_ia32_gather3div4sf: 4561 case X86::BI__builtin_ia32_gather3div4si: 4562 case X86::BI__builtin_ia32_gather3div8sf: 4563 case X86::BI__builtin_ia32_gather3div8si: 4564 case X86::BI__builtin_ia32_gather3siv2df: 4565 case X86::BI__builtin_ia32_gather3siv2di: 4566 case X86::BI__builtin_ia32_gather3siv4df: 4567 case X86::BI__builtin_ia32_gather3siv4di: 4568 case X86::BI__builtin_ia32_gather3siv4sf: 4569 case X86::BI__builtin_ia32_gather3siv4si: 4570 case X86::BI__builtin_ia32_gather3siv8sf: 4571 case X86::BI__builtin_ia32_gather3siv8si: 4572 case X86::BI__builtin_ia32_gathersiv8df: 4573 case X86::BI__builtin_ia32_gathersiv16sf: 4574 case X86::BI__builtin_ia32_gatherdiv8df: 4575 case X86::BI__builtin_ia32_gatherdiv16sf: 4576 case X86::BI__builtin_ia32_gathersiv8di: 4577 case X86::BI__builtin_ia32_gathersiv16si: 4578 case X86::BI__builtin_ia32_gatherdiv8di: 4579 case X86::BI__builtin_ia32_gatherdiv16si: 4580 case X86::BI__builtin_ia32_scatterdiv2df: 4581 case X86::BI__builtin_ia32_scatterdiv2di: 4582 case X86::BI__builtin_ia32_scatterdiv4df: 4583 case X86::BI__builtin_ia32_scatterdiv4di: 4584 case X86::BI__builtin_ia32_scatterdiv4sf: 4585 case X86::BI__builtin_ia32_scatterdiv4si: 4586 case X86::BI__builtin_ia32_scatterdiv8sf: 4587 case X86::BI__builtin_ia32_scatterdiv8si: 4588 case X86::BI__builtin_ia32_scattersiv2df: 4589 case X86::BI__builtin_ia32_scattersiv2di: 4590 case X86::BI__builtin_ia32_scattersiv4df: 4591 case X86::BI__builtin_ia32_scattersiv4di: 4592 case X86::BI__builtin_ia32_scattersiv4sf: 4593 case X86::BI__builtin_ia32_scattersiv4si: 4594 case X86::BI__builtin_ia32_scattersiv8sf: 4595 case X86::BI__builtin_ia32_scattersiv8si: 4596 case X86::BI__builtin_ia32_scattersiv8df: 4597 case X86::BI__builtin_ia32_scattersiv16sf: 4598 case X86::BI__builtin_ia32_scatterdiv8df: 4599 case X86::BI__builtin_ia32_scatterdiv16sf: 4600 case X86::BI__builtin_ia32_scattersiv8di: 4601 case X86::BI__builtin_ia32_scattersiv16si: 4602 case X86::BI__builtin_ia32_scatterdiv8di: 4603 case X86::BI__builtin_ia32_scatterdiv16si: 4604 ArgNum = 4; 4605 break; 4606 } 4607 4608 llvm::APSInt Result; 4609 4610 // We can't check the value of a dependent argument. 4611 Expr *Arg = TheCall->getArg(ArgNum); 4612 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4613 return false; 4614 4615 // Check constant-ness first. 4616 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4617 return true; 4618 4619 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4620 return false; 4621 4622 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4623 << Arg->getSourceRange(); 4624 } 4625 4626 enum { TileRegLow = 0, TileRegHigh = 7 }; 4627 4628 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4629 ArrayRef<int> ArgNums) { 4630 for (int ArgNum : ArgNums) { 4631 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4632 return true; 4633 } 4634 return false; 4635 } 4636 4637 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4638 ArrayRef<int> ArgNums) { 4639 // Because the max number of tile register is TileRegHigh + 1, so here we use 4640 // each bit to represent the usage of them in bitset. 4641 std::bitset<TileRegHigh + 1> ArgValues; 4642 for (int ArgNum : ArgNums) { 4643 Expr *Arg = TheCall->getArg(ArgNum); 4644 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4645 continue; 4646 4647 llvm::APSInt Result; 4648 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4649 return true; 4650 int ArgExtValue = Result.getExtValue(); 4651 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4652 "Incorrect tile register num."); 4653 if (ArgValues.test(ArgExtValue)) 4654 return Diag(TheCall->getBeginLoc(), 4655 diag::err_x86_builtin_tile_arg_duplicate) 4656 << TheCall->getArg(ArgNum)->getSourceRange(); 4657 ArgValues.set(ArgExtValue); 4658 } 4659 return false; 4660 } 4661 4662 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 4663 ArrayRef<int> ArgNums) { 4664 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 4665 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 4666 } 4667 4668 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 4669 switch (BuiltinID) { 4670 default: 4671 return false; 4672 case X86::BI__builtin_ia32_tileloadd64: 4673 case X86::BI__builtin_ia32_tileloaddt164: 4674 case X86::BI__builtin_ia32_tilestored64: 4675 case X86::BI__builtin_ia32_tilezero: 4676 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 4677 case X86::BI__builtin_ia32_tdpbssd: 4678 case X86::BI__builtin_ia32_tdpbsud: 4679 case X86::BI__builtin_ia32_tdpbusd: 4680 case X86::BI__builtin_ia32_tdpbuud: 4681 case X86::BI__builtin_ia32_tdpbf16ps: 4682 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 4683 } 4684 } 4685 static bool isX86_32Builtin(unsigned BuiltinID) { 4686 // These builtins only work on x86-32 targets. 4687 switch (BuiltinID) { 4688 case X86::BI__builtin_ia32_readeflags_u32: 4689 case X86::BI__builtin_ia32_writeeflags_u32: 4690 return true; 4691 } 4692 4693 return false; 4694 } 4695 4696 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 4697 CallExpr *TheCall) { 4698 if (BuiltinID == X86::BI__builtin_cpu_supports) 4699 return SemaBuiltinCpuSupports(*this, TI, TheCall); 4700 4701 if (BuiltinID == X86::BI__builtin_cpu_is) 4702 return SemaBuiltinCpuIs(*this, TI, TheCall); 4703 4704 // Check for 32-bit only builtins on a 64-bit target. 4705 const llvm::Triple &TT = TI.getTriple(); 4706 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 4707 return Diag(TheCall->getCallee()->getBeginLoc(), 4708 diag::err_32_bit_builtin_64_bit_tgt); 4709 4710 // If the intrinsic has rounding or SAE make sure its valid. 4711 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 4712 return true; 4713 4714 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 4715 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 4716 return true; 4717 4718 // If the intrinsic has a tile arguments, make sure they are valid. 4719 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4720 return true; 4721 4722 // For intrinsics which take an immediate value as part of the instruction, 4723 // range check them here. 4724 int i = 0, l = 0, u = 0; 4725 switch (BuiltinID) { 4726 default: 4727 return false; 4728 case X86::BI__builtin_ia32_vec_ext_v2si: 4729 case X86::BI__builtin_ia32_vec_ext_v2di: 4730 case X86::BI__builtin_ia32_vextractf128_pd256: 4731 case X86::BI__builtin_ia32_vextractf128_ps256: 4732 case X86::BI__builtin_ia32_vextractf128_si256: 4733 case X86::BI__builtin_ia32_extract128i256: 4734 case X86::BI__builtin_ia32_extractf64x4_mask: 4735 case X86::BI__builtin_ia32_extracti64x4_mask: 4736 case X86::BI__builtin_ia32_extractf32x8_mask: 4737 case X86::BI__builtin_ia32_extracti32x8_mask: 4738 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4739 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4740 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4741 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4742 i = 1; l = 0; u = 1; 4743 break; 4744 case X86::BI__builtin_ia32_vec_set_v2di: 4745 case X86::BI__builtin_ia32_vinsertf128_pd256: 4746 case X86::BI__builtin_ia32_vinsertf128_ps256: 4747 case X86::BI__builtin_ia32_vinsertf128_si256: 4748 case X86::BI__builtin_ia32_insert128i256: 4749 case X86::BI__builtin_ia32_insertf32x8: 4750 case X86::BI__builtin_ia32_inserti32x8: 4751 case X86::BI__builtin_ia32_insertf64x4: 4752 case X86::BI__builtin_ia32_inserti64x4: 4753 case X86::BI__builtin_ia32_insertf64x2_256: 4754 case X86::BI__builtin_ia32_inserti64x2_256: 4755 case X86::BI__builtin_ia32_insertf32x4_256: 4756 case X86::BI__builtin_ia32_inserti32x4_256: 4757 i = 2; l = 0; u = 1; 4758 break; 4759 case X86::BI__builtin_ia32_vpermilpd: 4760 case X86::BI__builtin_ia32_vec_ext_v4hi: 4761 case X86::BI__builtin_ia32_vec_ext_v4si: 4762 case X86::BI__builtin_ia32_vec_ext_v4sf: 4763 case X86::BI__builtin_ia32_vec_ext_v4di: 4764 case X86::BI__builtin_ia32_extractf32x4_mask: 4765 case X86::BI__builtin_ia32_extracti32x4_mask: 4766 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4767 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4768 i = 1; l = 0; u = 3; 4769 break; 4770 case X86::BI_mm_prefetch: 4771 case X86::BI__builtin_ia32_vec_ext_v8hi: 4772 case X86::BI__builtin_ia32_vec_ext_v8si: 4773 i = 1; l = 0; u = 7; 4774 break; 4775 case X86::BI__builtin_ia32_sha1rnds4: 4776 case X86::BI__builtin_ia32_blendpd: 4777 case X86::BI__builtin_ia32_shufpd: 4778 case X86::BI__builtin_ia32_vec_set_v4hi: 4779 case X86::BI__builtin_ia32_vec_set_v4si: 4780 case X86::BI__builtin_ia32_vec_set_v4di: 4781 case X86::BI__builtin_ia32_shuf_f32x4_256: 4782 case X86::BI__builtin_ia32_shuf_f64x2_256: 4783 case X86::BI__builtin_ia32_shuf_i32x4_256: 4784 case X86::BI__builtin_ia32_shuf_i64x2_256: 4785 case X86::BI__builtin_ia32_insertf64x2_512: 4786 case X86::BI__builtin_ia32_inserti64x2_512: 4787 case X86::BI__builtin_ia32_insertf32x4: 4788 case X86::BI__builtin_ia32_inserti32x4: 4789 i = 2; l = 0; u = 3; 4790 break; 4791 case X86::BI__builtin_ia32_vpermil2pd: 4792 case X86::BI__builtin_ia32_vpermil2pd256: 4793 case X86::BI__builtin_ia32_vpermil2ps: 4794 case X86::BI__builtin_ia32_vpermil2ps256: 4795 i = 3; l = 0; u = 3; 4796 break; 4797 case X86::BI__builtin_ia32_cmpb128_mask: 4798 case X86::BI__builtin_ia32_cmpw128_mask: 4799 case X86::BI__builtin_ia32_cmpd128_mask: 4800 case X86::BI__builtin_ia32_cmpq128_mask: 4801 case X86::BI__builtin_ia32_cmpb256_mask: 4802 case X86::BI__builtin_ia32_cmpw256_mask: 4803 case X86::BI__builtin_ia32_cmpd256_mask: 4804 case X86::BI__builtin_ia32_cmpq256_mask: 4805 case X86::BI__builtin_ia32_cmpb512_mask: 4806 case X86::BI__builtin_ia32_cmpw512_mask: 4807 case X86::BI__builtin_ia32_cmpd512_mask: 4808 case X86::BI__builtin_ia32_cmpq512_mask: 4809 case X86::BI__builtin_ia32_ucmpb128_mask: 4810 case X86::BI__builtin_ia32_ucmpw128_mask: 4811 case X86::BI__builtin_ia32_ucmpd128_mask: 4812 case X86::BI__builtin_ia32_ucmpq128_mask: 4813 case X86::BI__builtin_ia32_ucmpb256_mask: 4814 case X86::BI__builtin_ia32_ucmpw256_mask: 4815 case X86::BI__builtin_ia32_ucmpd256_mask: 4816 case X86::BI__builtin_ia32_ucmpq256_mask: 4817 case X86::BI__builtin_ia32_ucmpb512_mask: 4818 case X86::BI__builtin_ia32_ucmpw512_mask: 4819 case X86::BI__builtin_ia32_ucmpd512_mask: 4820 case X86::BI__builtin_ia32_ucmpq512_mask: 4821 case X86::BI__builtin_ia32_vpcomub: 4822 case X86::BI__builtin_ia32_vpcomuw: 4823 case X86::BI__builtin_ia32_vpcomud: 4824 case X86::BI__builtin_ia32_vpcomuq: 4825 case X86::BI__builtin_ia32_vpcomb: 4826 case X86::BI__builtin_ia32_vpcomw: 4827 case X86::BI__builtin_ia32_vpcomd: 4828 case X86::BI__builtin_ia32_vpcomq: 4829 case X86::BI__builtin_ia32_vec_set_v8hi: 4830 case X86::BI__builtin_ia32_vec_set_v8si: 4831 i = 2; l = 0; u = 7; 4832 break; 4833 case X86::BI__builtin_ia32_vpermilpd256: 4834 case X86::BI__builtin_ia32_roundps: 4835 case X86::BI__builtin_ia32_roundpd: 4836 case X86::BI__builtin_ia32_roundps256: 4837 case X86::BI__builtin_ia32_roundpd256: 4838 case X86::BI__builtin_ia32_getmantpd128_mask: 4839 case X86::BI__builtin_ia32_getmantpd256_mask: 4840 case X86::BI__builtin_ia32_getmantps128_mask: 4841 case X86::BI__builtin_ia32_getmantps256_mask: 4842 case X86::BI__builtin_ia32_getmantpd512_mask: 4843 case X86::BI__builtin_ia32_getmantps512_mask: 4844 case X86::BI__builtin_ia32_getmantph128_mask: 4845 case X86::BI__builtin_ia32_getmantph256_mask: 4846 case X86::BI__builtin_ia32_getmantph512_mask: 4847 case X86::BI__builtin_ia32_vec_ext_v16qi: 4848 case X86::BI__builtin_ia32_vec_ext_v16hi: 4849 i = 1; l = 0; u = 15; 4850 break; 4851 case X86::BI__builtin_ia32_pblendd128: 4852 case X86::BI__builtin_ia32_blendps: 4853 case X86::BI__builtin_ia32_blendpd256: 4854 case X86::BI__builtin_ia32_shufpd256: 4855 case X86::BI__builtin_ia32_roundss: 4856 case X86::BI__builtin_ia32_roundsd: 4857 case X86::BI__builtin_ia32_rangepd128_mask: 4858 case X86::BI__builtin_ia32_rangepd256_mask: 4859 case X86::BI__builtin_ia32_rangepd512_mask: 4860 case X86::BI__builtin_ia32_rangeps128_mask: 4861 case X86::BI__builtin_ia32_rangeps256_mask: 4862 case X86::BI__builtin_ia32_rangeps512_mask: 4863 case X86::BI__builtin_ia32_getmantsd_round_mask: 4864 case X86::BI__builtin_ia32_getmantss_round_mask: 4865 case X86::BI__builtin_ia32_getmantsh_round_mask: 4866 case X86::BI__builtin_ia32_vec_set_v16qi: 4867 case X86::BI__builtin_ia32_vec_set_v16hi: 4868 i = 2; l = 0; u = 15; 4869 break; 4870 case X86::BI__builtin_ia32_vec_ext_v32qi: 4871 i = 1; l = 0; u = 31; 4872 break; 4873 case X86::BI__builtin_ia32_cmpps: 4874 case X86::BI__builtin_ia32_cmpss: 4875 case X86::BI__builtin_ia32_cmppd: 4876 case X86::BI__builtin_ia32_cmpsd: 4877 case X86::BI__builtin_ia32_cmpps256: 4878 case X86::BI__builtin_ia32_cmppd256: 4879 case X86::BI__builtin_ia32_cmpps128_mask: 4880 case X86::BI__builtin_ia32_cmppd128_mask: 4881 case X86::BI__builtin_ia32_cmpps256_mask: 4882 case X86::BI__builtin_ia32_cmppd256_mask: 4883 case X86::BI__builtin_ia32_cmpps512_mask: 4884 case X86::BI__builtin_ia32_cmppd512_mask: 4885 case X86::BI__builtin_ia32_cmpsd_mask: 4886 case X86::BI__builtin_ia32_cmpss_mask: 4887 case X86::BI__builtin_ia32_vec_set_v32qi: 4888 i = 2; l = 0; u = 31; 4889 break; 4890 case X86::BI__builtin_ia32_permdf256: 4891 case X86::BI__builtin_ia32_permdi256: 4892 case X86::BI__builtin_ia32_permdf512: 4893 case X86::BI__builtin_ia32_permdi512: 4894 case X86::BI__builtin_ia32_vpermilps: 4895 case X86::BI__builtin_ia32_vpermilps256: 4896 case X86::BI__builtin_ia32_vpermilpd512: 4897 case X86::BI__builtin_ia32_vpermilps512: 4898 case X86::BI__builtin_ia32_pshufd: 4899 case X86::BI__builtin_ia32_pshufd256: 4900 case X86::BI__builtin_ia32_pshufd512: 4901 case X86::BI__builtin_ia32_pshufhw: 4902 case X86::BI__builtin_ia32_pshufhw256: 4903 case X86::BI__builtin_ia32_pshufhw512: 4904 case X86::BI__builtin_ia32_pshuflw: 4905 case X86::BI__builtin_ia32_pshuflw256: 4906 case X86::BI__builtin_ia32_pshuflw512: 4907 case X86::BI__builtin_ia32_vcvtps2ph: 4908 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4909 case X86::BI__builtin_ia32_vcvtps2ph256: 4910 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4911 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4912 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4913 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4914 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4915 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4916 case X86::BI__builtin_ia32_rndscaleps_mask: 4917 case X86::BI__builtin_ia32_rndscalepd_mask: 4918 case X86::BI__builtin_ia32_rndscaleph_mask: 4919 case X86::BI__builtin_ia32_reducepd128_mask: 4920 case X86::BI__builtin_ia32_reducepd256_mask: 4921 case X86::BI__builtin_ia32_reducepd512_mask: 4922 case X86::BI__builtin_ia32_reduceps128_mask: 4923 case X86::BI__builtin_ia32_reduceps256_mask: 4924 case X86::BI__builtin_ia32_reduceps512_mask: 4925 case X86::BI__builtin_ia32_reduceph128_mask: 4926 case X86::BI__builtin_ia32_reduceph256_mask: 4927 case X86::BI__builtin_ia32_reduceph512_mask: 4928 case X86::BI__builtin_ia32_prold512: 4929 case X86::BI__builtin_ia32_prolq512: 4930 case X86::BI__builtin_ia32_prold128: 4931 case X86::BI__builtin_ia32_prold256: 4932 case X86::BI__builtin_ia32_prolq128: 4933 case X86::BI__builtin_ia32_prolq256: 4934 case X86::BI__builtin_ia32_prord512: 4935 case X86::BI__builtin_ia32_prorq512: 4936 case X86::BI__builtin_ia32_prord128: 4937 case X86::BI__builtin_ia32_prord256: 4938 case X86::BI__builtin_ia32_prorq128: 4939 case X86::BI__builtin_ia32_prorq256: 4940 case X86::BI__builtin_ia32_fpclasspd128_mask: 4941 case X86::BI__builtin_ia32_fpclasspd256_mask: 4942 case X86::BI__builtin_ia32_fpclassps128_mask: 4943 case X86::BI__builtin_ia32_fpclassps256_mask: 4944 case X86::BI__builtin_ia32_fpclassps512_mask: 4945 case X86::BI__builtin_ia32_fpclasspd512_mask: 4946 case X86::BI__builtin_ia32_fpclassph128_mask: 4947 case X86::BI__builtin_ia32_fpclassph256_mask: 4948 case X86::BI__builtin_ia32_fpclassph512_mask: 4949 case X86::BI__builtin_ia32_fpclasssd_mask: 4950 case X86::BI__builtin_ia32_fpclassss_mask: 4951 case X86::BI__builtin_ia32_fpclasssh_mask: 4952 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4953 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4954 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4955 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4956 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4957 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4958 case X86::BI__builtin_ia32_kshiftliqi: 4959 case X86::BI__builtin_ia32_kshiftlihi: 4960 case X86::BI__builtin_ia32_kshiftlisi: 4961 case X86::BI__builtin_ia32_kshiftlidi: 4962 case X86::BI__builtin_ia32_kshiftriqi: 4963 case X86::BI__builtin_ia32_kshiftrihi: 4964 case X86::BI__builtin_ia32_kshiftrisi: 4965 case X86::BI__builtin_ia32_kshiftridi: 4966 i = 1; l = 0; u = 255; 4967 break; 4968 case X86::BI__builtin_ia32_vperm2f128_pd256: 4969 case X86::BI__builtin_ia32_vperm2f128_ps256: 4970 case X86::BI__builtin_ia32_vperm2f128_si256: 4971 case X86::BI__builtin_ia32_permti256: 4972 case X86::BI__builtin_ia32_pblendw128: 4973 case X86::BI__builtin_ia32_pblendw256: 4974 case X86::BI__builtin_ia32_blendps256: 4975 case X86::BI__builtin_ia32_pblendd256: 4976 case X86::BI__builtin_ia32_palignr128: 4977 case X86::BI__builtin_ia32_palignr256: 4978 case X86::BI__builtin_ia32_palignr512: 4979 case X86::BI__builtin_ia32_alignq512: 4980 case X86::BI__builtin_ia32_alignd512: 4981 case X86::BI__builtin_ia32_alignd128: 4982 case X86::BI__builtin_ia32_alignd256: 4983 case X86::BI__builtin_ia32_alignq128: 4984 case X86::BI__builtin_ia32_alignq256: 4985 case X86::BI__builtin_ia32_vcomisd: 4986 case X86::BI__builtin_ia32_vcomiss: 4987 case X86::BI__builtin_ia32_shuf_f32x4: 4988 case X86::BI__builtin_ia32_shuf_f64x2: 4989 case X86::BI__builtin_ia32_shuf_i32x4: 4990 case X86::BI__builtin_ia32_shuf_i64x2: 4991 case X86::BI__builtin_ia32_shufpd512: 4992 case X86::BI__builtin_ia32_shufps: 4993 case X86::BI__builtin_ia32_shufps256: 4994 case X86::BI__builtin_ia32_shufps512: 4995 case X86::BI__builtin_ia32_dbpsadbw128: 4996 case X86::BI__builtin_ia32_dbpsadbw256: 4997 case X86::BI__builtin_ia32_dbpsadbw512: 4998 case X86::BI__builtin_ia32_vpshldd128: 4999 case X86::BI__builtin_ia32_vpshldd256: 5000 case X86::BI__builtin_ia32_vpshldd512: 5001 case X86::BI__builtin_ia32_vpshldq128: 5002 case X86::BI__builtin_ia32_vpshldq256: 5003 case X86::BI__builtin_ia32_vpshldq512: 5004 case X86::BI__builtin_ia32_vpshldw128: 5005 case X86::BI__builtin_ia32_vpshldw256: 5006 case X86::BI__builtin_ia32_vpshldw512: 5007 case X86::BI__builtin_ia32_vpshrdd128: 5008 case X86::BI__builtin_ia32_vpshrdd256: 5009 case X86::BI__builtin_ia32_vpshrdd512: 5010 case X86::BI__builtin_ia32_vpshrdq128: 5011 case X86::BI__builtin_ia32_vpshrdq256: 5012 case X86::BI__builtin_ia32_vpshrdq512: 5013 case X86::BI__builtin_ia32_vpshrdw128: 5014 case X86::BI__builtin_ia32_vpshrdw256: 5015 case X86::BI__builtin_ia32_vpshrdw512: 5016 i = 2; l = 0; u = 255; 5017 break; 5018 case X86::BI__builtin_ia32_fixupimmpd512_mask: 5019 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 5020 case X86::BI__builtin_ia32_fixupimmps512_mask: 5021 case X86::BI__builtin_ia32_fixupimmps512_maskz: 5022 case X86::BI__builtin_ia32_fixupimmsd_mask: 5023 case X86::BI__builtin_ia32_fixupimmsd_maskz: 5024 case X86::BI__builtin_ia32_fixupimmss_mask: 5025 case X86::BI__builtin_ia32_fixupimmss_maskz: 5026 case X86::BI__builtin_ia32_fixupimmpd128_mask: 5027 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 5028 case X86::BI__builtin_ia32_fixupimmpd256_mask: 5029 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 5030 case X86::BI__builtin_ia32_fixupimmps128_mask: 5031 case X86::BI__builtin_ia32_fixupimmps128_maskz: 5032 case X86::BI__builtin_ia32_fixupimmps256_mask: 5033 case X86::BI__builtin_ia32_fixupimmps256_maskz: 5034 case X86::BI__builtin_ia32_pternlogd512_mask: 5035 case X86::BI__builtin_ia32_pternlogd512_maskz: 5036 case X86::BI__builtin_ia32_pternlogq512_mask: 5037 case X86::BI__builtin_ia32_pternlogq512_maskz: 5038 case X86::BI__builtin_ia32_pternlogd128_mask: 5039 case X86::BI__builtin_ia32_pternlogd128_maskz: 5040 case X86::BI__builtin_ia32_pternlogd256_mask: 5041 case X86::BI__builtin_ia32_pternlogd256_maskz: 5042 case X86::BI__builtin_ia32_pternlogq128_mask: 5043 case X86::BI__builtin_ia32_pternlogq128_maskz: 5044 case X86::BI__builtin_ia32_pternlogq256_mask: 5045 case X86::BI__builtin_ia32_pternlogq256_maskz: 5046 i = 3; l = 0; u = 255; 5047 break; 5048 case X86::BI__builtin_ia32_gatherpfdpd: 5049 case X86::BI__builtin_ia32_gatherpfdps: 5050 case X86::BI__builtin_ia32_gatherpfqpd: 5051 case X86::BI__builtin_ia32_gatherpfqps: 5052 case X86::BI__builtin_ia32_scatterpfdpd: 5053 case X86::BI__builtin_ia32_scatterpfdps: 5054 case X86::BI__builtin_ia32_scatterpfqpd: 5055 case X86::BI__builtin_ia32_scatterpfqps: 5056 i = 4; l = 2; u = 3; 5057 break; 5058 case X86::BI__builtin_ia32_reducesd_mask: 5059 case X86::BI__builtin_ia32_reducess_mask: 5060 case X86::BI__builtin_ia32_rndscalesd_round_mask: 5061 case X86::BI__builtin_ia32_rndscaless_round_mask: 5062 case X86::BI__builtin_ia32_rndscalesh_round_mask: 5063 case X86::BI__builtin_ia32_reducesh_mask: 5064 i = 4; l = 0; u = 255; 5065 break; 5066 } 5067 5068 // Note that we don't force a hard error on the range check here, allowing 5069 // template-generated or macro-generated dead code to potentially have out-of- 5070 // range values. These need to code generate, but don't need to necessarily 5071 // make any sense. We use a warning that defaults to an error. 5072 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 5073 } 5074 5075 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 5076 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 5077 /// Returns true when the format fits the function and the FormatStringInfo has 5078 /// been populated. 5079 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 5080 FormatStringInfo *FSI) { 5081 FSI->HasVAListArg = Format->getFirstArg() == 0; 5082 FSI->FormatIdx = Format->getFormatIdx() - 1; 5083 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 5084 5085 // The way the format attribute works in GCC, the implicit this argument 5086 // of member functions is counted. However, it doesn't appear in our own 5087 // lists, so decrement format_idx in that case. 5088 if (IsCXXMember) { 5089 if(FSI->FormatIdx == 0) 5090 return false; 5091 --FSI->FormatIdx; 5092 if (FSI->FirstDataArg != 0) 5093 --FSI->FirstDataArg; 5094 } 5095 return true; 5096 } 5097 5098 /// Checks if a the given expression evaluates to null. 5099 /// 5100 /// Returns true if the value evaluates to null. 5101 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 5102 // If the expression has non-null type, it doesn't evaluate to null. 5103 if (auto nullability 5104 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 5105 if (*nullability == NullabilityKind::NonNull) 5106 return false; 5107 } 5108 5109 // As a special case, transparent unions initialized with zero are 5110 // considered null for the purposes of the nonnull attribute. 5111 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 5112 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 5113 if (const CompoundLiteralExpr *CLE = 5114 dyn_cast<CompoundLiteralExpr>(Expr)) 5115 if (const InitListExpr *ILE = 5116 dyn_cast<InitListExpr>(CLE->getInitializer())) 5117 Expr = ILE->getInit(0); 5118 } 5119 5120 bool Result; 5121 return (!Expr->isValueDependent() && 5122 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 5123 !Result); 5124 } 5125 5126 static void CheckNonNullArgument(Sema &S, 5127 const Expr *ArgExpr, 5128 SourceLocation CallSiteLoc) { 5129 if (CheckNonNullExpr(S, ArgExpr)) 5130 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 5131 S.PDiag(diag::warn_null_arg) 5132 << ArgExpr->getSourceRange()); 5133 } 5134 5135 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 5136 FormatStringInfo FSI; 5137 if ((GetFormatStringType(Format) == FST_NSString) && 5138 getFormatStringInfo(Format, false, &FSI)) { 5139 Idx = FSI.FormatIdx; 5140 return true; 5141 } 5142 return false; 5143 } 5144 5145 /// Diagnose use of %s directive in an NSString which is being passed 5146 /// as formatting string to formatting method. 5147 static void 5148 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 5149 const NamedDecl *FDecl, 5150 Expr **Args, 5151 unsigned NumArgs) { 5152 unsigned Idx = 0; 5153 bool Format = false; 5154 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 5155 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 5156 Idx = 2; 5157 Format = true; 5158 } 5159 else 5160 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 5161 if (S.GetFormatNSStringIdx(I, Idx)) { 5162 Format = true; 5163 break; 5164 } 5165 } 5166 if (!Format || NumArgs <= Idx) 5167 return; 5168 const Expr *FormatExpr = Args[Idx]; 5169 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 5170 FormatExpr = CSCE->getSubExpr(); 5171 const StringLiteral *FormatString; 5172 if (const ObjCStringLiteral *OSL = 5173 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 5174 FormatString = OSL->getString(); 5175 else 5176 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 5177 if (!FormatString) 5178 return; 5179 if (S.FormatStringHasSArg(FormatString)) { 5180 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 5181 << "%s" << 1 << 1; 5182 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 5183 << FDecl->getDeclName(); 5184 } 5185 } 5186 5187 /// Determine whether the given type has a non-null nullability annotation. 5188 static bool isNonNullType(ASTContext &ctx, QualType type) { 5189 if (auto nullability = type->getNullability(ctx)) 5190 return *nullability == NullabilityKind::NonNull; 5191 5192 return false; 5193 } 5194 5195 static void CheckNonNullArguments(Sema &S, 5196 const NamedDecl *FDecl, 5197 const FunctionProtoType *Proto, 5198 ArrayRef<const Expr *> Args, 5199 SourceLocation CallSiteLoc) { 5200 assert((FDecl || Proto) && "Need a function declaration or prototype"); 5201 5202 // Already checked by by constant evaluator. 5203 if (S.isConstantEvaluated()) 5204 return; 5205 // Check the attributes attached to the method/function itself. 5206 llvm::SmallBitVector NonNullArgs; 5207 if (FDecl) { 5208 // Handle the nonnull attribute on the function/method declaration itself. 5209 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 5210 if (!NonNull->args_size()) { 5211 // Easy case: all pointer arguments are nonnull. 5212 for (const auto *Arg : Args) 5213 if (S.isValidPointerAttrType(Arg->getType())) 5214 CheckNonNullArgument(S, Arg, CallSiteLoc); 5215 return; 5216 } 5217 5218 for (const ParamIdx &Idx : NonNull->args()) { 5219 unsigned IdxAST = Idx.getASTIndex(); 5220 if (IdxAST >= Args.size()) 5221 continue; 5222 if (NonNullArgs.empty()) 5223 NonNullArgs.resize(Args.size()); 5224 NonNullArgs.set(IdxAST); 5225 } 5226 } 5227 } 5228 5229 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 5230 // Handle the nonnull attribute on the parameters of the 5231 // function/method. 5232 ArrayRef<ParmVarDecl*> parms; 5233 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 5234 parms = FD->parameters(); 5235 else 5236 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 5237 5238 unsigned ParamIndex = 0; 5239 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 5240 I != E; ++I, ++ParamIndex) { 5241 const ParmVarDecl *PVD = *I; 5242 if (PVD->hasAttr<NonNullAttr>() || 5243 isNonNullType(S.Context, PVD->getType())) { 5244 if (NonNullArgs.empty()) 5245 NonNullArgs.resize(Args.size()); 5246 5247 NonNullArgs.set(ParamIndex); 5248 } 5249 } 5250 } else { 5251 // If we have a non-function, non-method declaration but no 5252 // function prototype, try to dig out the function prototype. 5253 if (!Proto) { 5254 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 5255 QualType type = VD->getType().getNonReferenceType(); 5256 if (auto pointerType = type->getAs<PointerType>()) 5257 type = pointerType->getPointeeType(); 5258 else if (auto blockType = type->getAs<BlockPointerType>()) 5259 type = blockType->getPointeeType(); 5260 // FIXME: data member pointers? 5261 5262 // Dig out the function prototype, if there is one. 5263 Proto = type->getAs<FunctionProtoType>(); 5264 } 5265 } 5266 5267 // Fill in non-null argument information from the nullability 5268 // information on the parameter types (if we have them). 5269 if (Proto) { 5270 unsigned Index = 0; 5271 for (auto paramType : Proto->getParamTypes()) { 5272 if (isNonNullType(S.Context, paramType)) { 5273 if (NonNullArgs.empty()) 5274 NonNullArgs.resize(Args.size()); 5275 5276 NonNullArgs.set(Index); 5277 } 5278 5279 ++Index; 5280 } 5281 } 5282 } 5283 5284 // Check for non-null arguments. 5285 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 5286 ArgIndex != ArgIndexEnd; ++ArgIndex) { 5287 if (NonNullArgs[ArgIndex]) 5288 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 5289 } 5290 } 5291 5292 /// Warn if a pointer or reference argument passed to a function points to an 5293 /// object that is less aligned than the parameter. This can happen when 5294 /// creating a typedef with a lower alignment than the original type and then 5295 /// calling functions defined in terms of the original type. 5296 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 5297 StringRef ParamName, QualType ArgTy, 5298 QualType ParamTy) { 5299 5300 // If a function accepts a pointer or reference type 5301 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 5302 return; 5303 5304 // If the parameter is a pointer type, get the pointee type for the 5305 // argument too. If the parameter is a reference type, don't try to get 5306 // the pointee type for the argument. 5307 if (ParamTy->isPointerType()) 5308 ArgTy = ArgTy->getPointeeType(); 5309 5310 // Remove reference or pointer 5311 ParamTy = ParamTy->getPointeeType(); 5312 5313 // Find expected alignment, and the actual alignment of the passed object. 5314 // getTypeAlignInChars requires complete types 5315 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 5316 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 5317 ArgTy->isUndeducedType()) 5318 return; 5319 5320 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 5321 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 5322 5323 // If the argument is less aligned than the parameter, there is a 5324 // potential alignment issue. 5325 if (ArgAlign < ParamAlign) 5326 Diag(Loc, diag::warn_param_mismatched_alignment) 5327 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 5328 << ParamName << (FDecl != nullptr) << FDecl; 5329 } 5330 5331 /// Handles the checks for format strings, non-POD arguments to vararg 5332 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 5333 /// attributes. 5334 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 5335 const Expr *ThisArg, ArrayRef<const Expr *> Args, 5336 bool IsMemberFunction, SourceLocation Loc, 5337 SourceRange Range, VariadicCallType CallType) { 5338 // FIXME: We should check as much as we can in the template definition. 5339 if (CurContext->isDependentContext()) 5340 return; 5341 5342 // Printf and scanf checking. 5343 llvm::SmallBitVector CheckedVarArgs; 5344 if (FDecl) { 5345 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 5346 // Only create vector if there are format attributes. 5347 CheckedVarArgs.resize(Args.size()); 5348 5349 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 5350 CheckedVarArgs); 5351 } 5352 } 5353 5354 // Refuse POD arguments that weren't caught by the format string 5355 // checks above. 5356 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 5357 if (CallType != VariadicDoesNotApply && 5358 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 5359 unsigned NumParams = Proto ? Proto->getNumParams() 5360 : FDecl && isa<FunctionDecl>(FDecl) 5361 ? cast<FunctionDecl>(FDecl)->getNumParams() 5362 : FDecl && isa<ObjCMethodDecl>(FDecl) 5363 ? cast<ObjCMethodDecl>(FDecl)->param_size() 5364 : 0; 5365 5366 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 5367 // Args[ArgIdx] can be null in malformed code. 5368 if (const Expr *Arg = Args[ArgIdx]) { 5369 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 5370 checkVariadicArgument(Arg, CallType); 5371 } 5372 } 5373 } 5374 5375 if (FDecl || Proto) { 5376 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 5377 5378 // Type safety checking. 5379 if (FDecl) { 5380 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 5381 CheckArgumentWithTypeTag(I, Args, Loc); 5382 } 5383 } 5384 5385 // Check that passed arguments match the alignment of original arguments. 5386 // Try to get the missing prototype from the declaration. 5387 if (!Proto && FDecl) { 5388 const auto *FT = FDecl->getFunctionType(); 5389 if (isa_and_nonnull<FunctionProtoType>(FT)) 5390 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 5391 } 5392 if (Proto) { 5393 // For variadic functions, we may have more args than parameters. 5394 // For some K&R functions, we may have less args than parameters. 5395 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 5396 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 5397 // Args[ArgIdx] can be null in malformed code. 5398 if (const Expr *Arg = Args[ArgIdx]) { 5399 if (Arg->containsErrors()) 5400 continue; 5401 5402 QualType ParamTy = Proto->getParamType(ArgIdx); 5403 QualType ArgTy = Arg->getType(); 5404 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 5405 ArgTy, ParamTy); 5406 } 5407 } 5408 } 5409 5410 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 5411 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 5412 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 5413 if (!Arg->isValueDependent()) { 5414 Expr::EvalResult Align; 5415 if (Arg->EvaluateAsInt(Align, Context)) { 5416 const llvm::APSInt &I = Align.Val.getInt(); 5417 if (!I.isPowerOf2()) 5418 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 5419 << Arg->getSourceRange(); 5420 5421 if (I > Sema::MaximumAlignment) 5422 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 5423 << Arg->getSourceRange() << Sema::MaximumAlignment; 5424 } 5425 } 5426 } 5427 5428 if (FD) 5429 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 5430 } 5431 5432 /// CheckConstructorCall - Check a constructor call for correctness and safety 5433 /// properties not enforced by the C type system. 5434 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 5435 ArrayRef<const Expr *> Args, 5436 const FunctionProtoType *Proto, 5437 SourceLocation Loc) { 5438 VariadicCallType CallType = 5439 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 5440 5441 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 5442 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 5443 Context.getPointerType(Ctor->getThisObjectType())); 5444 5445 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 5446 Loc, SourceRange(), CallType); 5447 } 5448 5449 /// CheckFunctionCall - Check a direct function call for various correctness 5450 /// and safety properties not strictly enforced by the C type system. 5451 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 5452 const FunctionProtoType *Proto) { 5453 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 5454 isa<CXXMethodDecl>(FDecl); 5455 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 5456 IsMemberOperatorCall; 5457 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 5458 TheCall->getCallee()); 5459 Expr** Args = TheCall->getArgs(); 5460 unsigned NumArgs = TheCall->getNumArgs(); 5461 5462 Expr *ImplicitThis = nullptr; 5463 if (IsMemberOperatorCall) { 5464 // If this is a call to a member operator, hide the first argument 5465 // from checkCall. 5466 // FIXME: Our choice of AST representation here is less than ideal. 5467 ImplicitThis = Args[0]; 5468 ++Args; 5469 --NumArgs; 5470 } else if (IsMemberFunction) 5471 ImplicitThis = 5472 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 5473 5474 if (ImplicitThis) { 5475 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 5476 // used. 5477 QualType ThisType = ImplicitThis->getType(); 5478 if (!ThisType->isPointerType()) { 5479 assert(!ThisType->isReferenceType()); 5480 ThisType = Context.getPointerType(ThisType); 5481 } 5482 5483 QualType ThisTypeFromDecl = 5484 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 5485 5486 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 5487 ThisTypeFromDecl); 5488 } 5489 5490 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 5491 IsMemberFunction, TheCall->getRParenLoc(), 5492 TheCall->getCallee()->getSourceRange(), CallType); 5493 5494 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5495 // None of the checks below are needed for functions that don't have 5496 // simple names (e.g., C++ conversion functions). 5497 if (!FnInfo) 5498 return false; 5499 5500 CheckTCBEnforcement(TheCall, FDecl); 5501 5502 CheckAbsoluteValueFunction(TheCall, FDecl); 5503 CheckMaxUnsignedZero(TheCall, FDecl); 5504 5505 if (getLangOpts().ObjC) 5506 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 5507 5508 unsigned CMId = FDecl->getMemoryFunctionKind(); 5509 5510 // Handle memory setting and copying functions. 5511 switch (CMId) { 5512 case 0: 5513 return false; 5514 case Builtin::BIstrlcpy: // fallthrough 5515 case Builtin::BIstrlcat: 5516 CheckStrlcpycatArguments(TheCall, FnInfo); 5517 break; 5518 case Builtin::BIstrncat: 5519 CheckStrncatArguments(TheCall, FnInfo); 5520 break; 5521 case Builtin::BIfree: 5522 CheckFreeArguments(TheCall); 5523 break; 5524 default: 5525 CheckMemaccessArguments(TheCall, CMId, FnInfo); 5526 } 5527 5528 return false; 5529 } 5530 5531 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 5532 ArrayRef<const Expr *> Args) { 5533 VariadicCallType CallType = 5534 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 5535 5536 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 5537 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 5538 CallType); 5539 5540 return false; 5541 } 5542 5543 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 5544 const FunctionProtoType *Proto) { 5545 QualType Ty; 5546 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 5547 Ty = V->getType().getNonReferenceType(); 5548 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 5549 Ty = F->getType().getNonReferenceType(); 5550 else 5551 return false; 5552 5553 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 5554 !Ty->isFunctionProtoType()) 5555 return false; 5556 5557 VariadicCallType CallType; 5558 if (!Proto || !Proto->isVariadic()) { 5559 CallType = VariadicDoesNotApply; 5560 } else if (Ty->isBlockPointerType()) { 5561 CallType = VariadicBlock; 5562 } else { // Ty->isFunctionPointerType() 5563 CallType = VariadicFunction; 5564 } 5565 5566 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 5567 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5568 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5569 TheCall->getCallee()->getSourceRange(), CallType); 5570 5571 return false; 5572 } 5573 5574 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 5575 /// such as function pointers returned from functions. 5576 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 5577 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 5578 TheCall->getCallee()); 5579 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 5580 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5581 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5582 TheCall->getCallee()->getSourceRange(), CallType); 5583 5584 return false; 5585 } 5586 5587 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 5588 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 5589 return false; 5590 5591 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 5592 switch (Op) { 5593 case AtomicExpr::AO__c11_atomic_init: 5594 case AtomicExpr::AO__opencl_atomic_init: 5595 llvm_unreachable("There is no ordering argument for an init"); 5596 5597 case AtomicExpr::AO__c11_atomic_load: 5598 case AtomicExpr::AO__opencl_atomic_load: 5599 case AtomicExpr::AO__hip_atomic_load: 5600 case AtomicExpr::AO__atomic_load_n: 5601 case AtomicExpr::AO__atomic_load: 5602 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5603 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5604 5605 case AtomicExpr::AO__c11_atomic_store: 5606 case AtomicExpr::AO__opencl_atomic_store: 5607 case AtomicExpr::AO__hip_atomic_store: 5608 case AtomicExpr::AO__atomic_store: 5609 case AtomicExpr::AO__atomic_store_n: 5610 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5611 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5612 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5613 5614 default: 5615 return true; 5616 } 5617 } 5618 5619 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5620 AtomicExpr::AtomicOp Op) { 5621 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5622 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5623 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5624 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5625 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5626 Op); 5627 } 5628 5629 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5630 SourceLocation RParenLoc, MultiExprArg Args, 5631 AtomicExpr::AtomicOp Op, 5632 AtomicArgumentOrder ArgOrder) { 5633 // All the non-OpenCL operations take one of the following forms. 5634 // The OpenCL operations take the __c11 forms with one extra argument for 5635 // synchronization scope. 5636 enum { 5637 // C __c11_atomic_init(A *, C) 5638 Init, 5639 5640 // C __c11_atomic_load(A *, int) 5641 Load, 5642 5643 // void __atomic_load(A *, CP, int) 5644 LoadCopy, 5645 5646 // void __atomic_store(A *, CP, int) 5647 Copy, 5648 5649 // C __c11_atomic_add(A *, M, int) 5650 Arithmetic, 5651 5652 // C __atomic_exchange_n(A *, CP, int) 5653 Xchg, 5654 5655 // void __atomic_exchange(A *, C *, CP, int) 5656 GNUXchg, 5657 5658 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 5659 C11CmpXchg, 5660 5661 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 5662 GNUCmpXchg 5663 } Form = Init; 5664 5665 const unsigned NumForm = GNUCmpXchg + 1; 5666 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 5667 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 5668 // where: 5669 // C is an appropriate type, 5670 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 5671 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 5672 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 5673 // the int parameters are for orderings. 5674 5675 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 5676 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 5677 "need to update code for modified forms"); 5678 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 5679 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 5680 AtomicExpr::AO__atomic_load, 5681 "need to update code for modified C11 atomics"); 5682 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 5683 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 5684 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_load && 5685 Op <= AtomicExpr::AO__hip_atomic_fetch_max; 5686 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 5687 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 5688 IsOpenCL; 5689 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 5690 Op == AtomicExpr::AO__atomic_store_n || 5691 Op == AtomicExpr::AO__atomic_exchange_n || 5692 Op == AtomicExpr::AO__atomic_compare_exchange_n; 5693 bool IsAddSub = false; 5694 5695 switch (Op) { 5696 case AtomicExpr::AO__c11_atomic_init: 5697 case AtomicExpr::AO__opencl_atomic_init: 5698 Form = Init; 5699 break; 5700 5701 case AtomicExpr::AO__c11_atomic_load: 5702 case AtomicExpr::AO__opencl_atomic_load: 5703 case AtomicExpr::AO__hip_atomic_load: 5704 case AtomicExpr::AO__atomic_load_n: 5705 Form = Load; 5706 break; 5707 5708 case AtomicExpr::AO__atomic_load: 5709 Form = LoadCopy; 5710 break; 5711 5712 case AtomicExpr::AO__c11_atomic_store: 5713 case AtomicExpr::AO__opencl_atomic_store: 5714 case AtomicExpr::AO__hip_atomic_store: 5715 case AtomicExpr::AO__atomic_store: 5716 case AtomicExpr::AO__atomic_store_n: 5717 Form = Copy; 5718 break; 5719 case AtomicExpr::AO__hip_atomic_fetch_add: 5720 case AtomicExpr::AO__hip_atomic_fetch_min: 5721 case AtomicExpr::AO__hip_atomic_fetch_max: 5722 case AtomicExpr::AO__c11_atomic_fetch_add: 5723 case AtomicExpr::AO__c11_atomic_fetch_sub: 5724 case AtomicExpr::AO__opencl_atomic_fetch_add: 5725 case AtomicExpr::AO__opencl_atomic_fetch_sub: 5726 case AtomicExpr::AO__atomic_fetch_add: 5727 case AtomicExpr::AO__atomic_fetch_sub: 5728 case AtomicExpr::AO__atomic_add_fetch: 5729 case AtomicExpr::AO__atomic_sub_fetch: 5730 IsAddSub = true; 5731 Form = Arithmetic; 5732 break; 5733 case AtomicExpr::AO__c11_atomic_fetch_and: 5734 case AtomicExpr::AO__c11_atomic_fetch_or: 5735 case AtomicExpr::AO__c11_atomic_fetch_xor: 5736 case AtomicExpr::AO__hip_atomic_fetch_and: 5737 case AtomicExpr::AO__hip_atomic_fetch_or: 5738 case AtomicExpr::AO__hip_atomic_fetch_xor: 5739 case AtomicExpr::AO__c11_atomic_fetch_nand: 5740 case AtomicExpr::AO__opencl_atomic_fetch_and: 5741 case AtomicExpr::AO__opencl_atomic_fetch_or: 5742 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5743 case AtomicExpr::AO__atomic_fetch_and: 5744 case AtomicExpr::AO__atomic_fetch_or: 5745 case AtomicExpr::AO__atomic_fetch_xor: 5746 case AtomicExpr::AO__atomic_fetch_nand: 5747 case AtomicExpr::AO__atomic_and_fetch: 5748 case AtomicExpr::AO__atomic_or_fetch: 5749 case AtomicExpr::AO__atomic_xor_fetch: 5750 case AtomicExpr::AO__atomic_nand_fetch: 5751 Form = Arithmetic; 5752 break; 5753 case AtomicExpr::AO__c11_atomic_fetch_min: 5754 case AtomicExpr::AO__c11_atomic_fetch_max: 5755 case AtomicExpr::AO__opencl_atomic_fetch_min: 5756 case AtomicExpr::AO__opencl_atomic_fetch_max: 5757 case AtomicExpr::AO__atomic_min_fetch: 5758 case AtomicExpr::AO__atomic_max_fetch: 5759 case AtomicExpr::AO__atomic_fetch_min: 5760 case AtomicExpr::AO__atomic_fetch_max: 5761 Form = Arithmetic; 5762 break; 5763 5764 case AtomicExpr::AO__c11_atomic_exchange: 5765 case AtomicExpr::AO__hip_atomic_exchange: 5766 case AtomicExpr::AO__opencl_atomic_exchange: 5767 case AtomicExpr::AO__atomic_exchange_n: 5768 Form = Xchg; 5769 break; 5770 5771 case AtomicExpr::AO__atomic_exchange: 5772 Form = GNUXchg; 5773 break; 5774 5775 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5776 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5777 case AtomicExpr::AO__hip_atomic_compare_exchange_strong: 5778 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5779 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5780 case AtomicExpr::AO__hip_atomic_compare_exchange_weak: 5781 Form = C11CmpXchg; 5782 break; 5783 5784 case AtomicExpr::AO__atomic_compare_exchange: 5785 case AtomicExpr::AO__atomic_compare_exchange_n: 5786 Form = GNUCmpXchg; 5787 break; 5788 } 5789 5790 unsigned AdjustedNumArgs = NumArgs[Form]; 5791 if ((IsOpenCL || IsHIP) && Op != AtomicExpr::AO__opencl_atomic_init) 5792 ++AdjustedNumArgs; 5793 // Check we have the right number of arguments. 5794 if (Args.size() < AdjustedNumArgs) { 5795 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5796 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5797 << ExprRange; 5798 return ExprError(); 5799 } else if (Args.size() > AdjustedNumArgs) { 5800 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5801 diag::err_typecheck_call_too_many_args) 5802 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5803 << ExprRange; 5804 return ExprError(); 5805 } 5806 5807 // Inspect the first argument of the atomic operation. 5808 Expr *Ptr = Args[0]; 5809 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5810 if (ConvertedPtr.isInvalid()) 5811 return ExprError(); 5812 5813 Ptr = ConvertedPtr.get(); 5814 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5815 if (!pointerType) { 5816 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5817 << Ptr->getType() << Ptr->getSourceRange(); 5818 return ExprError(); 5819 } 5820 5821 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5822 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5823 QualType ValType = AtomTy; // 'C' 5824 if (IsC11) { 5825 if (!AtomTy->isAtomicType()) { 5826 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5827 << Ptr->getType() << Ptr->getSourceRange(); 5828 return ExprError(); 5829 } 5830 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5831 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5832 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5833 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5834 << Ptr->getSourceRange(); 5835 return ExprError(); 5836 } 5837 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5838 } else if (Form != Load && Form != LoadCopy) { 5839 if (ValType.isConstQualified()) { 5840 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5841 << Ptr->getType() << Ptr->getSourceRange(); 5842 return ExprError(); 5843 } 5844 } 5845 5846 // For an arithmetic operation, the implied arithmetic must be well-formed. 5847 if (Form == Arithmetic) { 5848 // GCC does not enforce these rules for GNU atomics, but we do to help catch 5849 // trivial type errors. 5850 auto IsAllowedValueType = [&](QualType ValType) { 5851 if (ValType->isIntegerType()) 5852 return true; 5853 if (ValType->isPointerType()) 5854 return true; 5855 if (!ValType->isFloatingType()) 5856 return false; 5857 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5858 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5859 &Context.getTargetInfo().getLongDoubleFormat() == 5860 &llvm::APFloat::x87DoubleExtended()) 5861 return false; 5862 return true; 5863 }; 5864 if (IsAddSub && !IsAllowedValueType(ValType)) { 5865 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5866 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5867 return ExprError(); 5868 } 5869 if (!IsAddSub && !ValType->isIntegerType()) { 5870 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5871 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5872 return ExprError(); 5873 } 5874 if (IsC11 && ValType->isPointerType() && 5875 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5876 diag::err_incomplete_type)) { 5877 return ExprError(); 5878 } 5879 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5880 // For __atomic_*_n operations, the value type must be a scalar integral or 5881 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5882 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5883 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5884 return ExprError(); 5885 } 5886 5887 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5888 !AtomTy->isScalarType()) { 5889 // For GNU atomics, require a trivially-copyable type. This is not part of 5890 // the GNU atomics specification but we enforce it for consistency with 5891 // other atomics which generally all require a trivially-copyable type. This 5892 // is because atomics just copy bits. 5893 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5894 << Ptr->getType() << Ptr->getSourceRange(); 5895 return ExprError(); 5896 } 5897 5898 switch (ValType.getObjCLifetime()) { 5899 case Qualifiers::OCL_None: 5900 case Qualifiers::OCL_ExplicitNone: 5901 // okay 5902 break; 5903 5904 case Qualifiers::OCL_Weak: 5905 case Qualifiers::OCL_Strong: 5906 case Qualifiers::OCL_Autoreleasing: 5907 // FIXME: Can this happen? By this point, ValType should be known 5908 // to be trivially copyable. 5909 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5910 << ValType << Ptr->getSourceRange(); 5911 return ExprError(); 5912 } 5913 5914 // All atomic operations have an overload which takes a pointer to a volatile 5915 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5916 // into the result or the other operands. Similarly atomic_load takes a 5917 // pointer to a const 'A'. 5918 ValType.removeLocalVolatile(); 5919 ValType.removeLocalConst(); 5920 QualType ResultType = ValType; 5921 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5922 Form == Init) 5923 ResultType = Context.VoidTy; 5924 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5925 ResultType = Context.BoolTy; 5926 5927 // The type of a parameter passed 'by value'. In the GNU atomics, such 5928 // arguments are actually passed as pointers. 5929 QualType ByValType = ValType; // 'CP' 5930 bool IsPassedByAddress = false; 5931 if (!IsC11 && !IsHIP && !IsN) { 5932 ByValType = Ptr->getType(); 5933 IsPassedByAddress = true; 5934 } 5935 5936 SmallVector<Expr *, 5> APIOrderedArgs; 5937 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5938 APIOrderedArgs.push_back(Args[0]); 5939 switch (Form) { 5940 case Init: 5941 case Load: 5942 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5943 break; 5944 case LoadCopy: 5945 case Copy: 5946 case Arithmetic: 5947 case Xchg: 5948 APIOrderedArgs.push_back(Args[2]); // Val1 5949 APIOrderedArgs.push_back(Args[1]); // Order 5950 break; 5951 case GNUXchg: 5952 APIOrderedArgs.push_back(Args[2]); // Val1 5953 APIOrderedArgs.push_back(Args[3]); // Val2 5954 APIOrderedArgs.push_back(Args[1]); // Order 5955 break; 5956 case C11CmpXchg: 5957 APIOrderedArgs.push_back(Args[2]); // Val1 5958 APIOrderedArgs.push_back(Args[4]); // Val2 5959 APIOrderedArgs.push_back(Args[1]); // Order 5960 APIOrderedArgs.push_back(Args[3]); // OrderFail 5961 break; 5962 case GNUCmpXchg: 5963 APIOrderedArgs.push_back(Args[2]); // Val1 5964 APIOrderedArgs.push_back(Args[4]); // Val2 5965 APIOrderedArgs.push_back(Args[5]); // Weak 5966 APIOrderedArgs.push_back(Args[1]); // Order 5967 APIOrderedArgs.push_back(Args[3]); // OrderFail 5968 break; 5969 } 5970 } else 5971 APIOrderedArgs.append(Args.begin(), Args.end()); 5972 5973 // The first argument's non-CV pointer type is used to deduce the type of 5974 // subsequent arguments, except for: 5975 // - weak flag (always converted to bool) 5976 // - memory order (always converted to int) 5977 // - scope (always converted to int) 5978 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5979 QualType Ty; 5980 if (i < NumVals[Form] + 1) { 5981 switch (i) { 5982 case 0: 5983 // The first argument is always a pointer. It has a fixed type. 5984 // It is always dereferenced, a nullptr is undefined. 5985 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5986 // Nothing else to do: we already know all we want about this pointer. 5987 continue; 5988 case 1: 5989 // The second argument is the non-atomic operand. For arithmetic, this 5990 // is always passed by value, and for a compare_exchange it is always 5991 // passed by address. For the rest, GNU uses by-address and C11 uses 5992 // by-value. 5993 assert(Form != Load); 5994 if (Form == Arithmetic && ValType->isPointerType()) 5995 Ty = Context.getPointerDiffType(); 5996 else if (Form == Init || Form == Arithmetic) 5997 Ty = ValType; 5998 else if (Form == Copy || Form == Xchg) { 5999 if (IsPassedByAddress) { 6000 // The value pointer is always dereferenced, a nullptr is undefined. 6001 CheckNonNullArgument(*this, APIOrderedArgs[i], 6002 ExprRange.getBegin()); 6003 } 6004 Ty = ByValType; 6005 } else { 6006 Expr *ValArg = APIOrderedArgs[i]; 6007 // The value pointer is always dereferenced, a nullptr is undefined. 6008 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 6009 LangAS AS = LangAS::Default; 6010 // Keep address space of non-atomic pointer type. 6011 if (const PointerType *PtrTy = 6012 ValArg->getType()->getAs<PointerType>()) { 6013 AS = PtrTy->getPointeeType().getAddressSpace(); 6014 } 6015 Ty = Context.getPointerType( 6016 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 6017 } 6018 break; 6019 case 2: 6020 // The third argument to compare_exchange / GNU exchange is the desired 6021 // value, either by-value (for the C11 and *_n variant) or as a pointer. 6022 if (IsPassedByAddress) 6023 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 6024 Ty = ByValType; 6025 break; 6026 case 3: 6027 // The fourth argument to GNU compare_exchange is a 'weak' flag. 6028 Ty = Context.BoolTy; 6029 break; 6030 } 6031 } else { 6032 // The order(s) and scope are always converted to int. 6033 Ty = Context.IntTy; 6034 } 6035 6036 InitializedEntity Entity = 6037 InitializedEntity::InitializeParameter(Context, Ty, false); 6038 ExprResult Arg = APIOrderedArgs[i]; 6039 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6040 if (Arg.isInvalid()) 6041 return true; 6042 APIOrderedArgs[i] = Arg.get(); 6043 } 6044 6045 // Permute the arguments into a 'consistent' order. 6046 SmallVector<Expr*, 5> SubExprs; 6047 SubExprs.push_back(Ptr); 6048 switch (Form) { 6049 case Init: 6050 // Note, AtomicExpr::getVal1() has a special case for this atomic. 6051 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6052 break; 6053 case Load: 6054 SubExprs.push_back(APIOrderedArgs[1]); // Order 6055 break; 6056 case LoadCopy: 6057 case Copy: 6058 case Arithmetic: 6059 case Xchg: 6060 SubExprs.push_back(APIOrderedArgs[2]); // Order 6061 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6062 break; 6063 case GNUXchg: 6064 // Note, AtomicExpr::getVal2() has a special case for this atomic. 6065 SubExprs.push_back(APIOrderedArgs[3]); // Order 6066 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6067 SubExprs.push_back(APIOrderedArgs[2]); // Val2 6068 break; 6069 case C11CmpXchg: 6070 SubExprs.push_back(APIOrderedArgs[3]); // Order 6071 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6072 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 6073 SubExprs.push_back(APIOrderedArgs[2]); // Val2 6074 break; 6075 case GNUCmpXchg: 6076 SubExprs.push_back(APIOrderedArgs[4]); // Order 6077 SubExprs.push_back(APIOrderedArgs[1]); // Val1 6078 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 6079 SubExprs.push_back(APIOrderedArgs[2]); // Val2 6080 SubExprs.push_back(APIOrderedArgs[3]); // Weak 6081 break; 6082 } 6083 6084 if (SubExprs.size() >= 2 && Form != Init) { 6085 if (Optional<llvm::APSInt> Result = 6086 SubExprs[1]->getIntegerConstantExpr(Context)) 6087 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 6088 Diag(SubExprs[1]->getBeginLoc(), 6089 diag::warn_atomic_op_has_invalid_memory_order) 6090 << SubExprs[1]->getSourceRange(); 6091 } 6092 6093 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 6094 auto *Scope = Args[Args.size() - 1]; 6095 if (Optional<llvm::APSInt> Result = 6096 Scope->getIntegerConstantExpr(Context)) { 6097 if (!ScopeModel->isValid(Result->getZExtValue())) 6098 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 6099 << Scope->getSourceRange(); 6100 } 6101 SubExprs.push_back(Scope); 6102 } 6103 6104 AtomicExpr *AE = new (Context) 6105 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 6106 6107 if ((Op == AtomicExpr::AO__c11_atomic_load || 6108 Op == AtomicExpr::AO__c11_atomic_store || 6109 Op == AtomicExpr::AO__opencl_atomic_load || 6110 Op == AtomicExpr::AO__hip_atomic_load || 6111 Op == AtomicExpr::AO__opencl_atomic_store || 6112 Op == AtomicExpr::AO__hip_atomic_store) && 6113 Context.AtomicUsesUnsupportedLibcall(AE)) 6114 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 6115 << ((Op == AtomicExpr::AO__c11_atomic_load || 6116 Op == AtomicExpr::AO__opencl_atomic_load || 6117 Op == AtomicExpr::AO__hip_atomic_load) 6118 ? 0 6119 : 1); 6120 6121 if (ValType->isBitIntType()) { 6122 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit); 6123 return ExprError(); 6124 } 6125 6126 return AE; 6127 } 6128 6129 /// checkBuiltinArgument - Given a call to a builtin function, perform 6130 /// normal type-checking on the given argument, updating the call in 6131 /// place. This is useful when a builtin function requires custom 6132 /// type-checking for some of its arguments but not necessarily all of 6133 /// them. 6134 /// 6135 /// Returns true on error. 6136 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 6137 FunctionDecl *Fn = E->getDirectCallee(); 6138 assert(Fn && "builtin call without direct callee!"); 6139 6140 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 6141 InitializedEntity Entity = 6142 InitializedEntity::InitializeParameter(S.Context, Param); 6143 6144 ExprResult Arg = E->getArg(0); 6145 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 6146 if (Arg.isInvalid()) 6147 return true; 6148 6149 E->setArg(ArgIndex, Arg.get()); 6150 return false; 6151 } 6152 6153 /// We have a call to a function like __sync_fetch_and_add, which is an 6154 /// overloaded function based on the pointer type of its first argument. 6155 /// The main BuildCallExpr routines have already promoted the types of 6156 /// arguments because all of these calls are prototyped as void(...). 6157 /// 6158 /// This function goes through and does final semantic checking for these 6159 /// builtins, as well as generating any warnings. 6160 ExprResult 6161 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 6162 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 6163 Expr *Callee = TheCall->getCallee(); 6164 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 6165 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6166 6167 // Ensure that we have at least one argument to do type inference from. 6168 if (TheCall->getNumArgs() < 1) { 6169 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6170 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 6171 return ExprError(); 6172 } 6173 6174 // Inspect the first argument of the atomic builtin. This should always be 6175 // a pointer type, whose element is an integral scalar or pointer type. 6176 // Because it is a pointer type, we don't have to worry about any implicit 6177 // casts here. 6178 // FIXME: We don't allow floating point scalars as input. 6179 Expr *FirstArg = TheCall->getArg(0); 6180 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 6181 if (FirstArgResult.isInvalid()) 6182 return ExprError(); 6183 FirstArg = FirstArgResult.get(); 6184 TheCall->setArg(0, FirstArg); 6185 6186 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 6187 if (!pointerType) { 6188 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 6189 << FirstArg->getType() << FirstArg->getSourceRange(); 6190 return ExprError(); 6191 } 6192 6193 QualType ValType = pointerType->getPointeeType(); 6194 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6195 !ValType->isBlockPointerType()) { 6196 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 6197 << FirstArg->getType() << FirstArg->getSourceRange(); 6198 return ExprError(); 6199 } 6200 6201 if (ValType.isConstQualified()) { 6202 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 6203 << FirstArg->getType() << FirstArg->getSourceRange(); 6204 return ExprError(); 6205 } 6206 6207 switch (ValType.getObjCLifetime()) { 6208 case Qualifiers::OCL_None: 6209 case Qualifiers::OCL_ExplicitNone: 6210 // okay 6211 break; 6212 6213 case Qualifiers::OCL_Weak: 6214 case Qualifiers::OCL_Strong: 6215 case Qualifiers::OCL_Autoreleasing: 6216 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 6217 << ValType << FirstArg->getSourceRange(); 6218 return ExprError(); 6219 } 6220 6221 // Strip any qualifiers off ValType. 6222 ValType = ValType.getUnqualifiedType(); 6223 6224 // The majority of builtins return a value, but a few have special return 6225 // types, so allow them to override appropriately below. 6226 QualType ResultType = ValType; 6227 6228 // We need to figure out which concrete builtin this maps onto. For example, 6229 // __sync_fetch_and_add with a 2 byte object turns into 6230 // __sync_fetch_and_add_2. 6231 #define BUILTIN_ROW(x) \ 6232 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 6233 Builtin::BI##x##_8, Builtin::BI##x##_16 } 6234 6235 static const unsigned BuiltinIndices[][5] = { 6236 BUILTIN_ROW(__sync_fetch_and_add), 6237 BUILTIN_ROW(__sync_fetch_and_sub), 6238 BUILTIN_ROW(__sync_fetch_and_or), 6239 BUILTIN_ROW(__sync_fetch_and_and), 6240 BUILTIN_ROW(__sync_fetch_and_xor), 6241 BUILTIN_ROW(__sync_fetch_and_nand), 6242 6243 BUILTIN_ROW(__sync_add_and_fetch), 6244 BUILTIN_ROW(__sync_sub_and_fetch), 6245 BUILTIN_ROW(__sync_and_and_fetch), 6246 BUILTIN_ROW(__sync_or_and_fetch), 6247 BUILTIN_ROW(__sync_xor_and_fetch), 6248 BUILTIN_ROW(__sync_nand_and_fetch), 6249 6250 BUILTIN_ROW(__sync_val_compare_and_swap), 6251 BUILTIN_ROW(__sync_bool_compare_and_swap), 6252 BUILTIN_ROW(__sync_lock_test_and_set), 6253 BUILTIN_ROW(__sync_lock_release), 6254 BUILTIN_ROW(__sync_swap) 6255 }; 6256 #undef BUILTIN_ROW 6257 6258 // Determine the index of the size. 6259 unsigned SizeIndex; 6260 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 6261 case 1: SizeIndex = 0; break; 6262 case 2: SizeIndex = 1; break; 6263 case 4: SizeIndex = 2; break; 6264 case 8: SizeIndex = 3; break; 6265 case 16: SizeIndex = 4; break; 6266 default: 6267 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 6268 << FirstArg->getType() << FirstArg->getSourceRange(); 6269 return ExprError(); 6270 } 6271 6272 // Each of these builtins has one pointer argument, followed by some number of 6273 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 6274 // that we ignore. Find out which row of BuiltinIndices to read from as well 6275 // as the number of fixed args. 6276 unsigned BuiltinID = FDecl->getBuiltinID(); 6277 unsigned BuiltinIndex, NumFixed = 1; 6278 bool WarnAboutSemanticsChange = false; 6279 switch (BuiltinID) { 6280 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 6281 case Builtin::BI__sync_fetch_and_add: 6282 case Builtin::BI__sync_fetch_and_add_1: 6283 case Builtin::BI__sync_fetch_and_add_2: 6284 case Builtin::BI__sync_fetch_and_add_4: 6285 case Builtin::BI__sync_fetch_and_add_8: 6286 case Builtin::BI__sync_fetch_and_add_16: 6287 BuiltinIndex = 0; 6288 break; 6289 6290 case Builtin::BI__sync_fetch_and_sub: 6291 case Builtin::BI__sync_fetch_and_sub_1: 6292 case Builtin::BI__sync_fetch_and_sub_2: 6293 case Builtin::BI__sync_fetch_and_sub_4: 6294 case Builtin::BI__sync_fetch_and_sub_8: 6295 case Builtin::BI__sync_fetch_and_sub_16: 6296 BuiltinIndex = 1; 6297 break; 6298 6299 case Builtin::BI__sync_fetch_and_or: 6300 case Builtin::BI__sync_fetch_and_or_1: 6301 case Builtin::BI__sync_fetch_and_or_2: 6302 case Builtin::BI__sync_fetch_and_or_4: 6303 case Builtin::BI__sync_fetch_and_or_8: 6304 case Builtin::BI__sync_fetch_and_or_16: 6305 BuiltinIndex = 2; 6306 break; 6307 6308 case Builtin::BI__sync_fetch_and_and: 6309 case Builtin::BI__sync_fetch_and_and_1: 6310 case Builtin::BI__sync_fetch_and_and_2: 6311 case Builtin::BI__sync_fetch_and_and_4: 6312 case Builtin::BI__sync_fetch_and_and_8: 6313 case Builtin::BI__sync_fetch_and_and_16: 6314 BuiltinIndex = 3; 6315 break; 6316 6317 case Builtin::BI__sync_fetch_and_xor: 6318 case Builtin::BI__sync_fetch_and_xor_1: 6319 case Builtin::BI__sync_fetch_and_xor_2: 6320 case Builtin::BI__sync_fetch_and_xor_4: 6321 case Builtin::BI__sync_fetch_and_xor_8: 6322 case Builtin::BI__sync_fetch_and_xor_16: 6323 BuiltinIndex = 4; 6324 break; 6325 6326 case Builtin::BI__sync_fetch_and_nand: 6327 case Builtin::BI__sync_fetch_and_nand_1: 6328 case Builtin::BI__sync_fetch_and_nand_2: 6329 case Builtin::BI__sync_fetch_and_nand_4: 6330 case Builtin::BI__sync_fetch_and_nand_8: 6331 case Builtin::BI__sync_fetch_and_nand_16: 6332 BuiltinIndex = 5; 6333 WarnAboutSemanticsChange = true; 6334 break; 6335 6336 case Builtin::BI__sync_add_and_fetch: 6337 case Builtin::BI__sync_add_and_fetch_1: 6338 case Builtin::BI__sync_add_and_fetch_2: 6339 case Builtin::BI__sync_add_and_fetch_4: 6340 case Builtin::BI__sync_add_and_fetch_8: 6341 case Builtin::BI__sync_add_and_fetch_16: 6342 BuiltinIndex = 6; 6343 break; 6344 6345 case Builtin::BI__sync_sub_and_fetch: 6346 case Builtin::BI__sync_sub_and_fetch_1: 6347 case Builtin::BI__sync_sub_and_fetch_2: 6348 case Builtin::BI__sync_sub_and_fetch_4: 6349 case Builtin::BI__sync_sub_and_fetch_8: 6350 case Builtin::BI__sync_sub_and_fetch_16: 6351 BuiltinIndex = 7; 6352 break; 6353 6354 case Builtin::BI__sync_and_and_fetch: 6355 case Builtin::BI__sync_and_and_fetch_1: 6356 case Builtin::BI__sync_and_and_fetch_2: 6357 case Builtin::BI__sync_and_and_fetch_4: 6358 case Builtin::BI__sync_and_and_fetch_8: 6359 case Builtin::BI__sync_and_and_fetch_16: 6360 BuiltinIndex = 8; 6361 break; 6362 6363 case Builtin::BI__sync_or_and_fetch: 6364 case Builtin::BI__sync_or_and_fetch_1: 6365 case Builtin::BI__sync_or_and_fetch_2: 6366 case Builtin::BI__sync_or_and_fetch_4: 6367 case Builtin::BI__sync_or_and_fetch_8: 6368 case Builtin::BI__sync_or_and_fetch_16: 6369 BuiltinIndex = 9; 6370 break; 6371 6372 case Builtin::BI__sync_xor_and_fetch: 6373 case Builtin::BI__sync_xor_and_fetch_1: 6374 case Builtin::BI__sync_xor_and_fetch_2: 6375 case Builtin::BI__sync_xor_and_fetch_4: 6376 case Builtin::BI__sync_xor_and_fetch_8: 6377 case Builtin::BI__sync_xor_and_fetch_16: 6378 BuiltinIndex = 10; 6379 break; 6380 6381 case Builtin::BI__sync_nand_and_fetch: 6382 case Builtin::BI__sync_nand_and_fetch_1: 6383 case Builtin::BI__sync_nand_and_fetch_2: 6384 case Builtin::BI__sync_nand_and_fetch_4: 6385 case Builtin::BI__sync_nand_and_fetch_8: 6386 case Builtin::BI__sync_nand_and_fetch_16: 6387 BuiltinIndex = 11; 6388 WarnAboutSemanticsChange = true; 6389 break; 6390 6391 case Builtin::BI__sync_val_compare_and_swap: 6392 case Builtin::BI__sync_val_compare_and_swap_1: 6393 case Builtin::BI__sync_val_compare_and_swap_2: 6394 case Builtin::BI__sync_val_compare_and_swap_4: 6395 case Builtin::BI__sync_val_compare_and_swap_8: 6396 case Builtin::BI__sync_val_compare_and_swap_16: 6397 BuiltinIndex = 12; 6398 NumFixed = 2; 6399 break; 6400 6401 case Builtin::BI__sync_bool_compare_and_swap: 6402 case Builtin::BI__sync_bool_compare_and_swap_1: 6403 case Builtin::BI__sync_bool_compare_and_swap_2: 6404 case Builtin::BI__sync_bool_compare_and_swap_4: 6405 case Builtin::BI__sync_bool_compare_and_swap_8: 6406 case Builtin::BI__sync_bool_compare_and_swap_16: 6407 BuiltinIndex = 13; 6408 NumFixed = 2; 6409 ResultType = Context.BoolTy; 6410 break; 6411 6412 case Builtin::BI__sync_lock_test_and_set: 6413 case Builtin::BI__sync_lock_test_and_set_1: 6414 case Builtin::BI__sync_lock_test_and_set_2: 6415 case Builtin::BI__sync_lock_test_and_set_4: 6416 case Builtin::BI__sync_lock_test_and_set_8: 6417 case Builtin::BI__sync_lock_test_and_set_16: 6418 BuiltinIndex = 14; 6419 break; 6420 6421 case Builtin::BI__sync_lock_release: 6422 case Builtin::BI__sync_lock_release_1: 6423 case Builtin::BI__sync_lock_release_2: 6424 case Builtin::BI__sync_lock_release_4: 6425 case Builtin::BI__sync_lock_release_8: 6426 case Builtin::BI__sync_lock_release_16: 6427 BuiltinIndex = 15; 6428 NumFixed = 0; 6429 ResultType = Context.VoidTy; 6430 break; 6431 6432 case Builtin::BI__sync_swap: 6433 case Builtin::BI__sync_swap_1: 6434 case Builtin::BI__sync_swap_2: 6435 case Builtin::BI__sync_swap_4: 6436 case Builtin::BI__sync_swap_8: 6437 case Builtin::BI__sync_swap_16: 6438 BuiltinIndex = 16; 6439 break; 6440 } 6441 6442 // Now that we know how many fixed arguments we expect, first check that we 6443 // have at least that many. 6444 if (TheCall->getNumArgs() < 1+NumFixed) { 6445 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6446 << 0 << 1 + NumFixed << TheCall->getNumArgs() 6447 << Callee->getSourceRange(); 6448 return ExprError(); 6449 } 6450 6451 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 6452 << Callee->getSourceRange(); 6453 6454 if (WarnAboutSemanticsChange) { 6455 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 6456 << Callee->getSourceRange(); 6457 } 6458 6459 // Get the decl for the concrete builtin from this, we can tell what the 6460 // concrete integer type we should convert to is. 6461 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 6462 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 6463 FunctionDecl *NewBuiltinDecl; 6464 if (NewBuiltinID == BuiltinID) 6465 NewBuiltinDecl = FDecl; 6466 else { 6467 // Perform builtin lookup to avoid redeclaring it. 6468 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 6469 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 6470 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 6471 assert(Res.getFoundDecl()); 6472 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 6473 if (!NewBuiltinDecl) 6474 return ExprError(); 6475 } 6476 6477 // The first argument --- the pointer --- has a fixed type; we 6478 // deduce the types of the rest of the arguments accordingly. Walk 6479 // the remaining arguments, converting them to the deduced value type. 6480 for (unsigned i = 0; i != NumFixed; ++i) { 6481 ExprResult Arg = TheCall->getArg(i+1); 6482 6483 // GCC does an implicit conversion to the pointer or integer ValType. This 6484 // can fail in some cases (1i -> int**), check for this error case now. 6485 // Initialize the argument. 6486 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6487 ValType, /*consume*/ false); 6488 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6489 if (Arg.isInvalid()) 6490 return ExprError(); 6491 6492 // Okay, we have something that *can* be converted to the right type. Check 6493 // to see if there is a potentially weird extension going on here. This can 6494 // happen when you do an atomic operation on something like an char* and 6495 // pass in 42. The 42 gets converted to char. This is even more strange 6496 // for things like 45.123 -> char, etc. 6497 // FIXME: Do this check. 6498 TheCall->setArg(i+1, Arg.get()); 6499 } 6500 6501 // Create a new DeclRefExpr to refer to the new decl. 6502 DeclRefExpr *NewDRE = DeclRefExpr::Create( 6503 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 6504 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 6505 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 6506 6507 // Set the callee in the CallExpr. 6508 // FIXME: This loses syntactic information. 6509 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 6510 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 6511 CK_BuiltinFnToFnPtr); 6512 TheCall->setCallee(PromotedCall.get()); 6513 6514 // Change the result type of the call to match the original value type. This 6515 // is arbitrary, but the codegen for these builtins ins design to handle it 6516 // gracefully. 6517 TheCall->setType(ResultType); 6518 6519 // Prohibit problematic uses of bit-precise integer types with atomic 6520 // builtins. The arguments would have already been converted to the first 6521 // argument's type, so only need to check the first argument. 6522 const auto *BitIntValType = ValType->getAs<BitIntType>(); 6523 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) { 6524 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 6525 return ExprError(); 6526 } 6527 6528 return TheCallResult; 6529 } 6530 6531 /// SemaBuiltinNontemporalOverloaded - We have a call to 6532 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 6533 /// overloaded function based on the pointer type of its last argument. 6534 /// 6535 /// This function goes through and does final semantic checking for these 6536 /// builtins. 6537 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 6538 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 6539 DeclRefExpr *DRE = 6540 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6541 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6542 unsigned BuiltinID = FDecl->getBuiltinID(); 6543 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 6544 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 6545 "Unexpected nontemporal load/store builtin!"); 6546 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 6547 unsigned numArgs = isStore ? 2 : 1; 6548 6549 // Ensure that we have the proper number of arguments. 6550 if (checkArgCount(*this, TheCall, numArgs)) 6551 return ExprError(); 6552 6553 // Inspect the last argument of the nontemporal builtin. This should always 6554 // be a pointer type, from which we imply the type of the memory access. 6555 // Because it is a pointer type, we don't have to worry about any implicit 6556 // casts here. 6557 Expr *PointerArg = TheCall->getArg(numArgs - 1); 6558 ExprResult PointerArgResult = 6559 DefaultFunctionArrayLvalueConversion(PointerArg); 6560 6561 if (PointerArgResult.isInvalid()) 6562 return ExprError(); 6563 PointerArg = PointerArgResult.get(); 6564 TheCall->setArg(numArgs - 1, PointerArg); 6565 6566 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 6567 if (!pointerType) { 6568 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 6569 << PointerArg->getType() << PointerArg->getSourceRange(); 6570 return ExprError(); 6571 } 6572 6573 QualType ValType = pointerType->getPointeeType(); 6574 6575 // Strip any qualifiers off ValType. 6576 ValType = ValType.getUnqualifiedType(); 6577 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6578 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 6579 !ValType->isVectorType()) { 6580 Diag(DRE->getBeginLoc(), 6581 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 6582 << PointerArg->getType() << PointerArg->getSourceRange(); 6583 return ExprError(); 6584 } 6585 6586 if (!isStore) { 6587 TheCall->setType(ValType); 6588 return TheCallResult; 6589 } 6590 6591 ExprResult ValArg = TheCall->getArg(0); 6592 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6593 Context, ValType, /*consume*/ false); 6594 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 6595 if (ValArg.isInvalid()) 6596 return ExprError(); 6597 6598 TheCall->setArg(0, ValArg.get()); 6599 TheCall->setType(Context.VoidTy); 6600 return TheCallResult; 6601 } 6602 6603 /// CheckObjCString - Checks that the argument to the builtin 6604 /// CFString constructor is correct 6605 /// Note: It might also make sense to do the UTF-16 conversion here (would 6606 /// simplify the backend). 6607 bool Sema::CheckObjCString(Expr *Arg) { 6608 Arg = Arg->IgnoreParenCasts(); 6609 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 6610 6611 if (!Literal || !Literal->isAscii()) { 6612 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 6613 << Arg->getSourceRange(); 6614 return true; 6615 } 6616 6617 if (Literal->containsNonAsciiOrNull()) { 6618 StringRef String = Literal->getString(); 6619 unsigned NumBytes = String.size(); 6620 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6621 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6622 llvm::UTF16 *ToPtr = &ToBuf[0]; 6623 6624 llvm::ConversionResult Result = 6625 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6626 ToPtr + NumBytes, llvm::strictConversion); 6627 // Check for conversion failure. 6628 if (Result != llvm::conversionOK) 6629 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6630 << Arg->getSourceRange(); 6631 } 6632 return false; 6633 } 6634 6635 /// CheckObjCString - Checks that the format string argument to the os_log() 6636 /// and os_trace() functions is correct, and converts it to const char *. 6637 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6638 Arg = Arg->IgnoreParenCasts(); 6639 auto *Literal = dyn_cast<StringLiteral>(Arg); 6640 if (!Literal) { 6641 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6642 Literal = ObjcLiteral->getString(); 6643 } 6644 } 6645 6646 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6647 return ExprError( 6648 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 6649 << Arg->getSourceRange()); 6650 } 6651 6652 ExprResult Result(Literal); 6653 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 6654 InitializedEntity Entity = 6655 InitializedEntity::InitializeParameter(Context, ResultTy, false); 6656 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 6657 return Result; 6658 } 6659 6660 /// Check that the user is calling the appropriate va_start builtin for the 6661 /// target and calling convention. 6662 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 6663 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 6664 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 6665 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 6666 TT.getArch() == llvm::Triple::aarch64_32); 6667 bool IsWindows = TT.isOSWindows(); 6668 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 6669 if (IsX64 || IsAArch64) { 6670 CallingConv CC = CC_C; 6671 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 6672 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 6673 if (IsMSVAStart) { 6674 // Don't allow this in System V ABI functions. 6675 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 6676 return S.Diag(Fn->getBeginLoc(), 6677 diag::err_ms_va_start_used_in_sysv_function); 6678 } else { 6679 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 6680 // On x64 Windows, don't allow this in System V ABI functions. 6681 // (Yes, that means there's no corresponding way to support variadic 6682 // System V ABI functions on Windows.) 6683 if ((IsWindows && CC == CC_X86_64SysV) || 6684 (!IsWindows && CC == CC_Win64)) 6685 return S.Diag(Fn->getBeginLoc(), 6686 diag::err_va_start_used_in_wrong_abi_function) 6687 << !IsWindows; 6688 } 6689 return false; 6690 } 6691 6692 if (IsMSVAStart) 6693 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 6694 return false; 6695 } 6696 6697 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 6698 ParmVarDecl **LastParam = nullptr) { 6699 // Determine whether the current function, block, or obj-c method is variadic 6700 // and get its parameter list. 6701 bool IsVariadic = false; 6702 ArrayRef<ParmVarDecl *> Params; 6703 DeclContext *Caller = S.CurContext; 6704 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 6705 IsVariadic = Block->isVariadic(); 6706 Params = Block->parameters(); 6707 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 6708 IsVariadic = FD->isVariadic(); 6709 Params = FD->parameters(); 6710 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 6711 IsVariadic = MD->isVariadic(); 6712 // FIXME: This isn't correct for methods (results in bogus warning). 6713 Params = MD->parameters(); 6714 } else if (isa<CapturedDecl>(Caller)) { 6715 // We don't support va_start in a CapturedDecl. 6716 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 6717 return true; 6718 } else { 6719 // This must be some other declcontext that parses exprs. 6720 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 6721 return true; 6722 } 6723 6724 if (!IsVariadic) { 6725 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 6726 return true; 6727 } 6728 6729 if (LastParam) 6730 *LastParam = Params.empty() ? nullptr : Params.back(); 6731 6732 return false; 6733 } 6734 6735 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 6736 /// for validity. Emit an error and return true on failure; return false 6737 /// on success. 6738 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 6739 Expr *Fn = TheCall->getCallee(); 6740 6741 if (checkVAStartABI(*this, BuiltinID, Fn)) 6742 return true; 6743 6744 if (checkArgCount(*this, TheCall, 2)) 6745 return true; 6746 6747 // Type-check the first argument normally. 6748 if (checkBuiltinArgument(*this, TheCall, 0)) 6749 return true; 6750 6751 // Check that the current function is variadic, and get its last parameter. 6752 ParmVarDecl *LastParam; 6753 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6754 return true; 6755 6756 // Verify that the second argument to the builtin is the last argument of the 6757 // current function or method. 6758 bool SecondArgIsLastNamedArgument = false; 6759 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6760 6761 // These are valid if SecondArgIsLastNamedArgument is false after the next 6762 // block. 6763 QualType Type; 6764 SourceLocation ParamLoc; 6765 bool IsCRegister = false; 6766 6767 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6768 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6769 SecondArgIsLastNamedArgument = PV == LastParam; 6770 6771 Type = PV->getType(); 6772 ParamLoc = PV->getLocation(); 6773 IsCRegister = 6774 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6775 } 6776 } 6777 6778 if (!SecondArgIsLastNamedArgument) 6779 Diag(TheCall->getArg(1)->getBeginLoc(), 6780 diag::warn_second_arg_of_va_start_not_last_named_param); 6781 else if (IsCRegister || Type->isReferenceType() || 6782 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6783 // Promotable integers are UB, but enumerations need a bit of 6784 // extra checking to see what their promotable type actually is. 6785 if (!Type->isPromotableIntegerType()) 6786 return false; 6787 if (!Type->isEnumeralType()) 6788 return true; 6789 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6790 return !(ED && 6791 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6792 }()) { 6793 unsigned Reason = 0; 6794 if (Type->isReferenceType()) Reason = 1; 6795 else if (IsCRegister) Reason = 2; 6796 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6797 Diag(ParamLoc, diag::note_parameter_type) << Type; 6798 } 6799 6800 TheCall->setType(Context.VoidTy); 6801 return false; 6802 } 6803 6804 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6805 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool { 6806 const LangOptions &LO = getLangOpts(); 6807 6808 if (LO.CPlusPlus) 6809 return Arg->getType() 6810 .getCanonicalType() 6811 .getTypePtr() 6812 ->getPointeeType() 6813 .withoutLocalFastQualifiers() == Context.CharTy; 6814 6815 // In C, allow aliasing through `char *`, this is required for AArch64 at 6816 // least. 6817 return true; 6818 }; 6819 6820 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6821 // const char *named_addr); 6822 6823 Expr *Func = Call->getCallee(); 6824 6825 if (Call->getNumArgs() < 3) 6826 return Diag(Call->getEndLoc(), 6827 diag::err_typecheck_call_too_few_args_at_least) 6828 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6829 6830 // Type-check the first argument normally. 6831 if (checkBuiltinArgument(*this, Call, 0)) 6832 return true; 6833 6834 // Check that the current function is variadic. 6835 if (checkVAStartIsInVariadicFunction(*this, Func)) 6836 return true; 6837 6838 // __va_start on Windows does not validate the parameter qualifiers 6839 6840 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6841 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6842 6843 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6844 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6845 6846 const QualType &ConstCharPtrTy = 6847 Context.getPointerType(Context.CharTy.withConst()); 6848 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1)) 6849 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6850 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6851 << 0 /* qualifier difference */ 6852 << 3 /* parameter mismatch */ 6853 << 2 << Arg1->getType() << ConstCharPtrTy; 6854 6855 const QualType SizeTy = Context.getSizeType(); 6856 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6857 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6858 << Arg2->getType() << SizeTy << 1 /* different class */ 6859 << 0 /* qualifier difference */ 6860 << 3 /* parameter mismatch */ 6861 << 3 << Arg2->getType() << SizeTy; 6862 6863 return false; 6864 } 6865 6866 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6867 /// friends. This is declared to take (...), so we have to check everything. 6868 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6869 if (checkArgCount(*this, TheCall, 2)) 6870 return true; 6871 6872 ExprResult OrigArg0 = TheCall->getArg(0); 6873 ExprResult OrigArg1 = TheCall->getArg(1); 6874 6875 // Do standard promotions between the two arguments, returning their common 6876 // type. 6877 QualType Res = UsualArithmeticConversions( 6878 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6879 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6880 return true; 6881 6882 // Make sure any conversions are pushed back into the call; this is 6883 // type safe since unordered compare builtins are declared as "_Bool 6884 // foo(...)". 6885 TheCall->setArg(0, OrigArg0.get()); 6886 TheCall->setArg(1, OrigArg1.get()); 6887 6888 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6889 return false; 6890 6891 // If the common type isn't a real floating type, then the arguments were 6892 // invalid for this operation. 6893 if (Res.isNull() || !Res->isRealFloatingType()) 6894 return Diag(OrigArg0.get()->getBeginLoc(), 6895 diag::err_typecheck_call_invalid_ordered_compare) 6896 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6897 << SourceRange(OrigArg0.get()->getBeginLoc(), 6898 OrigArg1.get()->getEndLoc()); 6899 6900 return false; 6901 } 6902 6903 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6904 /// __builtin_isnan and friends. This is declared to take (...), so we have 6905 /// to check everything. We expect the last argument to be a floating point 6906 /// value. 6907 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6908 if (checkArgCount(*this, TheCall, NumArgs)) 6909 return true; 6910 6911 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6912 // on all preceding parameters just being int. Try all of those. 6913 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6914 Expr *Arg = TheCall->getArg(i); 6915 6916 if (Arg->isTypeDependent()) 6917 return false; 6918 6919 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6920 6921 if (Res.isInvalid()) 6922 return true; 6923 TheCall->setArg(i, Res.get()); 6924 } 6925 6926 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6927 6928 if (OrigArg->isTypeDependent()) 6929 return false; 6930 6931 // Usual Unary Conversions will convert half to float, which we want for 6932 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6933 // type how it is, but do normal L->Rvalue conversions. 6934 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6935 OrigArg = UsualUnaryConversions(OrigArg).get(); 6936 else 6937 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6938 TheCall->setArg(NumArgs - 1, OrigArg); 6939 6940 // This operation requires a non-_Complex floating-point number. 6941 if (!OrigArg->getType()->isRealFloatingType()) 6942 return Diag(OrigArg->getBeginLoc(), 6943 diag::err_typecheck_call_invalid_unary_fp) 6944 << OrigArg->getType() << OrigArg->getSourceRange(); 6945 6946 return false; 6947 } 6948 6949 /// Perform semantic analysis for a call to __builtin_complex. 6950 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6951 if (checkArgCount(*this, TheCall, 2)) 6952 return true; 6953 6954 bool Dependent = false; 6955 for (unsigned I = 0; I != 2; ++I) { 6956 Expr *Arg = TheCall->getArg(I); 6957 QualType T = Arg->getType(); 6958 if (T->isDependentType()) { 6959 Dependent = true; 6960 continue; 6961 } 6962 6963 // Despite supporting _Complex int, GCC requires a real floating point type 6964 // for the operands of __builtin_complex. 6965 if (!T->isRealFloatingType()) { 6966 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6967 << Arg->getType() << Arg->getSourceRange(); 6968 } 6969 6970 ExprResult Converted = DefaultLvalueConversion(Arg); 6971 if (Converted.isInvalid()) 6972 return true; 6973 TheCall->setArg(I, Converted.get()); 6974 } 6975 6976 if (Dependent) { 6977 TheCall->setType(Context.DependentTy); 6978 return false; 6979 } 6980 6981 Expr *Real = TheCall->getArg(0); 6982 Expr *Imag = TheCall->getArg(1); 6983 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6984 return Diag(Real->getBeginLoc(), 6985 diag::err_typecheck_call_different_arg_types) 6986 << Real->getType() << Imag->getType() 6987 << Real->getSourceRange() << Imag->getSourceRange(); 6988 } 6989 6990 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6991 // don't allow this builtin to form those types either. 6992 // FIXME: Should we allow these types? 6993 if (Real->getType()->isFloat16Type()) 6994 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6995 << "_Float16"; 6996 if (Real->getType()->isHalfType()) 6997 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6998 << "half"; 6999 7000 TheCall->setType(Context.getComplexType(Real->getType())); 7001 return false; 7002 } 7003 7004 // Customized Sema Checking for VSX builtins that have the following signature: 7005 // vector [...] builtinName(vector [...], vector [...], const int); 7006 // Which takes the same type of vectors (any legal vector type) for the first 7007 // two arguments and takes compile time constant for the third argument. 7008 // Example builtins are : 7009 // vector double vec_xxpermdi(vector double, vector double, int); 7010 // vector short vec_xxsldwi(vector short, vector short, int); 7011 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 7012 unsigned ExpectedNumArgs = 3; 7013 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 7014 return true; 7015 7016 // Check the third argument is a compile time constant 7017 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 7018 return Diag(TheCall->getBeginLoc(), 7019 diag::err_vsx_builtin_nonconstant_argument) 7020 << 3 /* argument index */ << TheCall->getDirectCallee() 7021 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 7022 TheCall->getArg(2)->getEndLoc()); 7023 7024 QualType Arg1Ty = TheCall->getArg(0)->getType(); 7025 QualType Arg2Ty = TheCall->getArg(1)->getType(); 7026 7027 // Check the type of argument 1 and argument 2 are vectors. 7028 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 7029 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 7030 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 7031 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 7032 << TheCall->getDirectCallee() 7033 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 7034 TheCall->getArg(1)->getEndLoc()); 7035 } 7036 7037 // Check the first two arguments are the same type. 7038 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 7039 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 7040 << TheCall->getDirectCallee() 7041 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 7042 TheCall->getArg(1)->getEndLoc()); 7043 } 7044 7045 // When default clang type checking is turned off and the customized type 7046 // checking is used, the returning type of the function must be explicitly 7047 // set. Otherwise it is _Bool by default. 7048 TheCall->setType(Arg1Ty); 7049 7050 return false; 7051 } 7052 7053 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 7054 // This is declared to take (...), so we have to check everything. 7055 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 7056 if (TheCall->getNumArgs() < 2) 7057 return ExprError(Diag(TheCall->getEndLoc(), 7058 diag::err_typecheck_call_too_few_args_at_least) 7059 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 7060 << TheCall->getSourceRange()); 7061 7062 // Determine which of the following types of shufflevector we're checking: 7063 // 1) unary, vector mask: (lhs, mask) 7064 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 7065 QualType resType = TheCall->getArg(0)->getType(); 7066 unsigned numElements = 0; 7067 7068 if (!TheCall->getArg(0)->isTypeDependent() && 7069 !TheCall->getArg(1)->isTypeDependent()) { 7070 QualType LHSType = TheCall->getArg(0)->getType(); 7071 QualType RHSType = TheCall->getArg(1)->getType(); 7072 7073 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 7074 return ExprError( 7075 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 7076 << TheCall->getDirectCallee() 7077 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 7078 TheCall->getArg(1)->getEndLoc())); 7079 7080 numElements = LHSType->castAs<VectorType>()->getNumElements(); 7081 unsigned numResElements = TheCall->getNumArgs() - 2; 7082 7083 // Check to see if we have a call with 2 vector arguments, the unary shuffle 7084 // with mask. If so, verify that RHS is an integer vector type with the 7085 // same number of elts as lhs. 7086 if (TheCall->getNumArgs() == 2) { 7087 if (!RHSType->hasIntegerRepresentation() || 7088 RHSType->castAs<VectorType>()->getNumElements() != numElements) 7089 return ExprError(Diag(TheCall->getBeginLoc(), 7090 diag::err_vec_builtin_incompatible_vector) 7091 << TheCall->getDirectCallee() 7092 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 7093 TheCall->getArg(1)->getEndLoc())); 7094 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 7095 return ExprError(Diag(TheCall->getBeginLoc(), 7096 diag::err_vec_builtin_incompatible_vector) 7097 << TheCall->getDirectCallee() 7098 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 7099 TheCall->getArg(1)->getEndLoc())); 7100 } else if (numElements != numResElements) { 7101 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 7102 resType = Context.getVectorType(eltType, numResElements, 7103 VectorType::GenericVector); 7104 } 7105 } 7106 7107 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 7108 if (TheCall->getArg(i)->isTypeDependent() || 7109 TheCall->getArg(i)->isValueDependent()) 7110 continue; 7111 7112 Optional<llvm::APSInt> Result; 7113 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 7114 return ExprError(Diag(TheCall->getBeginLoc(), 7115 diag::err_shufflevector_nonconstant_argument) 7116 << TheCall->getArg(i)->getSourceRange()); 7117 7118 // Allow -1 which will be translated to undef in the IR. 7119 if (Result->isSigned() && Result->isAllOnes()) 7120 continue; 7121 7122 if (Result->getActiveBits() > 64 || 7123 Result->getZExtValue() >= numElements * 2) 7124 return ExprError(Diag(TheCall->getBeginLoc(), 7125 diag::err_shufflevector_argument_too_large) 7126 << TheCall->getArg(i)->getSourceRange()); 7127 } 7128 7129 SmallVector<Expr*, 32> exprs; 7130 7131 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 7132 exprs.push_back(TheCall->getArg(i)); 7133 TheCall->setArg(i, nullptr); 7134 } 7135 7136 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 7137 TheCall->getCallee()->getBeginLoc(), 7138 TheCall->getRParenLoc()); 7139 } 7140 7141 /// SemaConvertVectorExpr - Handle __builtin_convertvector 7142 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 7143 SourceLocation BuiltinLoc, 7144 SourceLocation RParenLoc) { 7145 ExprValueKind VK = VK_PRValue; 7146 ExprObjectKind OK = OK_Ordinary; 7147 QualType DstTy = TInfo->getType(); 7148 QualType SrcTy = E->getType(); 7149 7150 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 7151 return ExprError(Diag(BuiltinLoc, 7152 diag::err_convertvector_non_vector) 7153 << E->getSourceRange()); 7154 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 7155 return ExprError(Diag(BuiltinLoc, 7156 diag::err_convertvector_non_vector_type)); 7157 7158 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 7159 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 7160 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 7161 if (SrcElts != DstElts) 7162 return ExprError(Diag(BuiltinLoc, 7163 diag::err_convertvector_incompatible_vector) 7164 << E->getSourceRange()); 7165 } 7166 7167 return new (Context) 7168 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 7169 } 7170 7171 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 7172 // This is declared to take (const void*, ...) and can take two 7173 // optional constant int args. 7174 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 7175 unsigned NumArgs = TheCall->getNumArgs(); 7176 7177 if (NumArgs > 3) 7178 return Diag(TheCall->getEndLoc(), 7179 diag::err_typecheck_call_too_many_args_at_most) 7180 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 7181 7182 // Argument 0 is checked for us and the remaining arguments must be 7183 // constant integers. 7184 for (unsigned i = 1; i != NumArgs; ++i) 7185 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 7186 return true; 7187 7188 return false; 7189 } 7190 7191 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 7192 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 7193 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 7194 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 7195 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7196 if (checkArgCount(*this, TheCall, 1)) 7197 return true; 7198 Expr *Arg = TheCall->getArg(0); 7199 if (Arg->isInstantiationDependent()) 7200 return false; 7201 7202 QualType ArgTy = Arg->getType(); 7203 if (!ArgTy->hasFloatingRepresentation()) 7204 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 7205 << ArgTy; 7206 if (Arg->isLValue()) { 7207 ExprResult FirstArg = DefaultLvalueConversion(Arg); 7208 TheCall->setArg(0, FirstArg.get()); 7209 } 7210 TheCall->setType(TheCall->getArg(0)->getType()); 7211 return false; 7212 } 7213 7214 /// SemaBuiltinAssume - Handle __assume (MS Extension). 7215 // __assume does not evaluate its arguments, and should warn if its argument 7216 // has side effects. 7217 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 7218 Expr *Arg = TheCall->getArg(0); 7219 if (Arg->isInstantiationDependent()) return false; 7220 7221 if (Arg->HasSideEffects(Context)) 7222 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 7223 << Arg->getSourceRange() 7224 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 7225 7226 return false; 7227 } 7228 7229 /// Handle __builtin_alloca_with_align. This is declared 7230 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 7231 /// than 8. 7232 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 7233 // The alignment must be a constant integer. 7234 Expr *Arg = TheCall->getArg(1); 7235 7236 // We can't check the value of a dependent argument. 7237 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 7238 if (const auto *UE = 7239 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 7240 if (UE->getKind() == UETT_AlignOf || 7241 UE->getKind() == UETT_PreferredAlignOf) 7242 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 7243 << Arg->getSourceRange(); 7244 7245 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 7246 7247 if (!Result.isPowerOf2()) 7248 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 7249 << Arg->getSourceRange(); 7250 7251 if (Result < Context.getCharWidth()) 7252 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 7253 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 7254 7255 if (Result > std::numeric_limits<int32_t>::max()) 7256 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 7257 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 7258 } 7259 7260 return false; 7261 } 7262 7263 /// Handle __builtin_assume_aligned. This is declared 7264 /// as (const void*, size_t, ...) and can take one optional constant int arg. 7265 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 7266 unsigned NumArgs = TheCall->getNumArgs(); 7267 7268 if (NumArgs > 3) 7269 return Diag(TheCall->getEndLoc(), 7270 diag::err_typecheck_call_too_many_args_at_most) 7271 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 7272 7273 // The alignment must be a constant integer. 7274 Expr *Arg = TheCall->getArg(1); 7275 7276 // We can't check the value of a dependent argument. 7277 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 7278 llvm::APSInt Result; 7279 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7280 return true; 7281 7282 if (!Result.isPowerOf2()) 7283 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 7284 << Arg->getSourceRange(); 7285 7286 if (Result > Sema::MaximumAlignment) 7287 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 7288 << Arg->getSourceRange() << Sema::MaximumAlignment; 7289 } 7290 7291 if (NumArgs > 2) { 7292 ExprResult Arg(TheCall->getArg(2)); 7293 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 7294 Context.getSizeType(), false); 7295 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 7296 if (Arg.isInvalid()) return true; 7297 TheCall->setArg(2, Arg.get()); 7298 } 7299 7300 return false; 7301 } 7302 7303 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 7304 unsigned BuiltinID = 7305 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 7306 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 7307 7308 unsigned NumArgs = TheCall->getNumArgs(); 7309 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 7310 if (NumArgs < NumRequiredArgs) { 7311 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 7312 << 0 /* function call */ << NumRequiredArgs << NumArgs 7313 << TheCall->getSourceRange(); 7314 } 7315 if (NumArgs >= NumRequiredArgs + 0x100) { 7316 return Diag(TheCall->getEndLoc(), 7317 diag::err_typecheck_call_too_many_args_at_most) 7318 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 7319 << TheCall->getSourceRange(); 7320 } 7321 unsigned i = 0; 7322 7323 // For formatting call, check buffer arg. 7324 if (!IsSizeCall) { 7325 ExprResult Arg(TheCall->getArg(i)); 7326 InitializedEntity Entity = InitializedEntity::InitializeParameter( 7327 Context, Context.VoidPtrTy, false); 7328 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 7329 if (Arg.isInvalid()) 7330 return true; 7331 TheCall->setArg(i, Arg.get()); 7332 i++; 7333 } 7334 7335 // Check string literal arg. 7336 unsigned FormatIdx = i; 7337 { 7338 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 7339 if (Arg.isInvalid()) 7340 return true; 7341 TheCall->setArg(i, Arg.get()); 7342 i++; 7343 } 7344 7345 // Make sure variadic args are scalar. 7346 unsigned FirstDataArg = i; 7347 while (i < NumArgs) { 7348 ExprResult Arg = DefaultVariadicArgumentPromotion( 7349 TheCall->getArg(i), VariadicFunction, nullptr); 7350 if (Arg.isInvalid()) 7351 return true; 7352 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 7353 if (ArgSize.getQuantity() >= 0x100) { 7354 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 7355 << i << (int)ArgSize.getQuantity() << 0xff 7356 << TheCall->getSourceRange(); 7357 } 7358 TheCall->setArg(i, Arg.get()); 7359 i++; 7360 } 7361 7362 // Check formatting specifiers. NOTE: We're only doing this for the non-size 7363 // call to avoid duplicate diagnostics. 7364 if (!IsSizeCall) { 7365 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 7366 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 7367 bool Success = CheckFormatArguments( 7368 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 7369 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 7370 CheckedVarArgs); 7371 if (!Success) 7372 return true; 7373 } 7374 7375 if (IsSizeCall) { 7376 TheCall->setType(Context.getSizeType()); 7377 } else { 7378 TheCall->setType(Context.VoidPtrTy); 7379 } 7380 return false; 7381 } 7382 7383 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 7384 /// TheCall is a constant expression. 7385 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 7386 llvm::APSInt &Result) { 7387 Expr *Arg = TheCall->getArg(ArgNum); 7388 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 7389 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 7390 7391 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 7392 7393 Optional<llvm::APSInt> R; 7394 if (!(R = Arg->getIntegerConstantExpr(Context))) 7395 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 7396 << FDecl->getDeclName() << Arg->getSourceRange(); 7397 Result = *R; 7398 return false; 7399 } 7400 7401 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 7402 /// TheCall is a constant expression in the range [Low, High]. 7403 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 7404 int Low, int High, bool RangeIsError) { 7405 if (isConstantEvaluated()) 7406 return false; 7407 llvm::APSInt Result; 7408 7409 // We can't check the value of a dependent argument. 7410 Expr *Arg = TheCall->getArg(ArgNum); 7411 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7412 return false; 7413 7414 // Check constant-ness first. 7415 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7416 return true; 7417 7418 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 7419 if (RangeIsError) 7420 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 7421 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 7422 else 7423 // Defer the warning until we know if the code will be emitted so that 7424 // dead code can ignore this. 7425 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 7426 PDiag(diag::warn_argument_invalid_range) 7427 << toString(Result, 10) << Low << High 7428 << Arg->getSourceRange()); 7429 } 7430 7431 return false; 7432 } 7433 7434 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 7435 /// TheCall is a constant expression is a multiple of Num.. 7436 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 7437 unsigned Num) { 7438 llvm::APSInt Result; 7439 7440 // We can't check the value of a dependent argument. 7441 Expr *Arg = TheCall->getArg(ArgNum); 7442 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7443 return false; 7444 7445 // Check constant-ness first. 7446 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7447 return true; 7448 7449 if (Result.getSExtValue() % Num != 0) 7450 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 7451 << Num << Arg->getSourceRange(); 7452 7453 return false; 7454 } 7455 7456 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 7457 /// constant expression representing a power of 2. 7458 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 7459 llvm::APSInt Result; 7460 7461 // We can't check the value of a dependent argument. 7462 Expr *Arg = TheCall->getArg(ArgNum); 7463 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7464 return false; 7465 7466 // Check constant-ness first. 7467 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7468 return true; 7469 7470 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 7471 // and only if x is a power of 2. 7472 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 7473 return false; 7474 7475 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 7476 << Arg->getSourceRange(); 7477 } 7478 7479 static bool IsShiftedByte(llvm::APSInt Value) { 7480 if (Value.isNegative()) 7481 return false; 7482 7483 // Check if it's a shifted byte, by shifting it down 7484 while (true) { 7485 // If the value fits in the bottom byte, the check passes. 7486 if (Value < 0x100) 7487 return true; 7488 7489 // Otherwise, if the value has _any_ bits in the bottom byte, the check 7490 // fails. 7491 if ((Value & 0xFF) != 0) 7492 return false; 7493 7494 // If the bottom 8 bits are all 0, but something above that is nonzero, 7495 // then shifting the value right by 8 bits won't affect whether it's a 7496 // shifted byte or not. So do that, and go round again. 7497 Value >>= 8; 7498 } 7499 } 7500 7501 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 7502 /// a constant expression representing an arbitrary byte value shifted left by 7503 /// a multiple of 8 bits. 7504 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 7505 unsigned ArgBits) { 7506 llvm::APSInt Result; 7507 7508 // We can't check the value of a dependent argument. 7509 Expr *Arg = TheCall->getArg(ArgNum); 7510 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7511 return false; 7512 7513 // Check constant-ness first. 7514 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7515 return true; 7516 7517 // Truncate to the given size. 7518 Result = Result.getLoBits(ArgBits); 7519 Result.setIsUnsigned(true); 7520 7521 if (IsShiftedByte(Result)) 7522 return false; 7523 7524 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 7525 << Arg->getSourceRange(); 7526 } 7527 7528 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 7529 /// TheCall is a constant expression representing either a shifted byte value, 7530 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 7531 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 7532 /// Arm MVE intrinsics. 7533 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 7534 int ArgNum, 7535 unsigned ArgBits) { 7536 llvm::APSInt Result; 7537 7538 // We can't check the value of a dependent argument. 7539 Expr *Arg = TheCall->getArg(ArgNum); 7540 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7541 return false; 7542 7543 // Check constant-ness first. 7544 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7545 return true; 7546 7547 // Truncate to the given size. 7548 Result = Result.getLoBits(ArgBits); 7549 Result.setIsUnsigned(true); 7550 7551 // Check to see if it's in either of the required forms. 7552 if (IsShiftedByte(Result) || 7553 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 7554 return false; 7555 7556 return Diag(TheCall->getBeginLoc(), 7557 diag::err_argument_not_shifted_byte_or_xxff) 7558 << Arg->getSourceRange(); 7559 } 7560 7561 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 7562 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 7563 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 7564 if (checkArgCount(*this, TheCall, 2)) 7565 return true; 7566 Expr *Arg0 = TheCall->getArg(0); 7567 Expr *Arg1 = TheCall->getArg(1); 7568 7569 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7570 if (FirstArg.isInvalid()) 7571 return true; 7572 QualType FirstArgType = FirstArg.get()->getType(); 7573 if (!FirstArgType->isAnyPointerType()) 7574 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7575 << "first" << FirstArgType << Arg0->getSourceRange(); 7576 TheCall->setArg(0, FirstArg.get()); 7577 7578 ExprResult SecArg = DefaultLvalueConversion(Arg1); 7579 if (SecArg.isInvalid()) 7580 return true; 7581 QualType SecArgType = SecArg.get()->getType(); 7582 if (!SecArgType->isIntegerType()) 7583 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7584 << "second" << SecArgType << Arg1->getSourceRange(); 7585 7586 // Derive the return type from the pointer argument. 7587 TheCall->setType(FirstArgType); 7588 return false; 7589 } 7590 7591 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 7592 if (checkArgCount(*this, TheCall, 2)) 7593 return true; 7594 7595 Expr *Arg0 = TheCall->getArg(0); 7596 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7597 if (FirstArg.isInvalid()) 7598 return true; 7599 QualType FirstArgType = FirstArg.get()->getType(); 7600 if (!FirstArgType->isAnyPointerType()) 7601 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7602 << "first" << FirstArgType << Arg0->getSourceRange(); 7603 TheCall->setArg(0, FirstArg.get()); 7604 7605 // Derive the return type from the pointer argument. 7606 TheCall->setType(FirstArgType); 7607 7608 // Second arg must be an constant in range [0,15] 7609 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7610 } 7611 7612 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 7613 if (checkArgCount(*this, TheCall, 2)) 7614 return true; 7615 Expr *Arg0 = TheCall->getArg(0); 7616 Expr *Arg1 = TheCall->getArg(1); 7617 7618 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7619 if (FirstArg.isInvalid()) 7620 return true; 7621 QualType FirstArgType = FirstArg.get()->getType(); 7622 if (!FirstArgType->isAnyPointerType()) 7623 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7624 << "first" << FirstArgType << Arg0->getSourceRange(); 7625 7626 QualType SecArgType = Arg1->getType(); 7627 if (!SecArgType->isIntegerType()) 7628 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7629 << "second" << SecArgType << Arg1->getSourceRange(); 7630 TheCall->setType(Context.IntTy); 7631 return false; 7632 } 7633 7634 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7635 BuiltinID == AArch64::BI__builtin_arm_stg) { 7636 if (checkArgCount(*this, TheCall, 1)) 7637 return true; 7638 Expr *Arg0 = TheCall->getArg(0); 7639 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7640 if (FirstArg.isInvalid()) 7641 return true; 7642 7643 QualType FirstArgType = FirstArg.get()->getType(); 7644 if (!FirstArgType->isAnyPointerType()) 7645 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7646 << "first" << FirstArgType << Arg0->getSourceRange(); 7647 TheCall->setArg(0, FirstArg.get()); 7648 7649 // Derive the return type from the pointer argument. 7650 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 7651 TheCall->setType(FirstArgType); 7652 return false; 7653 } 7654 7655 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 7656 Expr *ArgA = TheCall->getArg(0); 7657 Expr *ArgB = TheCall->getArg(1); 7658 7659 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 7660 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 7661 7662 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 7663 return true; 7664 7665 QualType ArgTypeA = ArgExprA.get()->getType(); 7666 QualType ArgTypeB = ArgExprB.get()->getType(); 7667 7668 auto isNull = [&] (Expr *E) -> bool { 7669 return E->isNullPointerConstant( 7670 Context, Expr::NPC_ValueDependentIsNotNull); }; 7671 7672 // argument should be either a pointer or null 7673 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 7674 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7675 << "first" << ArgTypeA << ArgA->getSourceRange(); 7676 7677 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 7678 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7679 << "second" << ArgTypeB << ArgB->getSourceRange(); 7680 7681 // Ensure Pointee types are compatible 7682 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 7683 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 7684 QualType pointeeA = ArgTypeA->getPointeeType(); 7685 QualType pointeeB = ArgTypeB->getPointeeType(); 7686 if (!Context.typesAreCompatible( 7687 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 7688 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 7689 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 7690 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 7691 << ArgB->getSourceRange(); 7692 } 7693 } 7694 7695 // at least one argument should be pointer type 7696 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 7697 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 7698 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 7699 7700 if (isNull(ArgA)) // adopt type of the other pointer 7701 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 7702 7703 if (isNull(ArgB)) 7704 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 7705 7706 TheCall->setArg(0, ArgExprA.get()); 7707 TheCall->setArg(1, ArgExprB.get()); 7708 TheCall->setType(Context.LongLongTy); 7709 return false; 7710 } 7711 assert(false && "Unhandled ARM MTE intrinsic"); 7712 return true; 7713 } 7714 7715 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 7716 /// TheCall is an ARM/AArch64 special register string literal. 7717 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 7718 int ArgNum, unsigned ExpectedFieldNum, 7719 bool AllowName) { 7720 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 7721 BuiltinID == ARM::BI__builtin_arm_wsr64 || 7722 BuiltinID == ARM::BI__builtin_arm_rsr || 7723 BuiltinID == ARM::BI__builtin_arm_rsrp || 7724 BuiltinID == ARM::BI__builtin_arm_wsr || 7725 BuiltinID == ARM::BI__builtin_arm_wsrp; 7726 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 7727 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 7728 BuiltinID == AArch64::BI__builtin_arm_rsr || 7729 BuiltinID == AArch64::BI__builtin_arm_rsrp || 7730 BuiltinID == AArch64::BI__builtin_arm_wsr || 7731 BuiltinID == AArch64::BI__builtin_arm_wsrp; 7732 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 7733 7734 // We can't check the value of a dependent argument. 7735 Expr *Arg = TheCall->getArg(ArgNum); 7736 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7737 return false; 7738 7739 // Check if the argument is a string literal. 7740 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 7741 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 7742 << Arg->getSourceRange(); 7743 7744 // Check the type of special register given. 7745 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 7746 SmallVector<StringRef, 6> Fields; 7747 Reg.split(Fields, ":"); 7748 7749 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 7750 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7751 << Arg->getSourceRange(); 7752 7753 // If the string is the name of a register then we cannot check that it is 7754 // valid here but if the string is of one the forms described in ACLE then we 7755 // can check that the supplied fields are integers and within the valid 7756 // ranges. 7757 if (Fields.size() > 1) { 7758 bool FiveFields = Fields.size() == 5; 7759 7760 bool ValidString = true; 7761 if (IsARMBuiltin) { 7762 ValidString &= Fields[0].startswith_insensitive("cp") || 7763 Fields[0].startswith_insensitive("p"); 7764 if (ValidString) 7765 Fields[0] = Fields[0].drop_front( 7766 Fields[0].startswith_insensitive("cp") ? 2 : 1); 7767 7768 ValidString &= Fields[2].startswith_insensitive("c"); 7769 if (ValidString) 7770 Fields[2] = Fields[2].drop_front(1); 7771 7772 if (FiveFields) { 7773 ValidString &= Fields[3].startswith_insensitive("c"); 7774 if (ValidString) 7775 Fields[3] = Fields[3].drop_front(1); 7776 } 7777 } 7778 7779 SmallVector<int, 5> Ranges; 7780 if (FiveFields) 7781 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 7782 else 7783 Ranges.append({15, 7, 15}); 7784 7785 for (unsigned i=0; i<Fields.size(); ++i) { 7786 int IntField; 7787 ValidString &= !Fields[i].getAsInteger(10, IntField); 7788 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7789 } 7790 7791 if (!ValidString) 7792 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7793 << Arg->getSourceRange(); 7794 } else if (IsAArch64Builtin && Fields.size() == 1) { 7795 // If the register name is one of those that appear in the condition below 7796 // and the special register builtin being used is one of the write builtins, 7797 // then we require that the argument provided for writing to the register 7798 // is an integer constant expression. This is because it will be lowered to 7799 // an MSR (immediate) instruction, so we need to know the immediate at 7800 // compile time. 7801 if (TheCall->getNumArgs() != 2) 7802 return false; 7803 7804 std::string RegLower = Reg.lower(); 7805 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7806 RegLower != "pan" && RegLower != "uao") 7807 return false; 7808 7809 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7810 } 7811 7812 return false; 7813 } 7814 7815 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7816 /// Emit an error and return true on failure; return false on success. 7817 /// TypeStr is a string containing the type descriptor of the value returned by 7818 /// the builtin and the descriptors of the expected type of the arguments. 7819 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID, 7820 const char *TypeStr) { 7821 7822 assert((TypeStr[0] != '\0') && 7823 "Invalid types in PPC MMA builtin declaration"); 7824 7825 switch (BuiltinID) { 7826 default: 7827 // This function is called in CheckPPCBuiltinFunctionCall where the 7828 // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here 7829 // we are isolating the pair vector memop builtins that can be used with mma 7830 // off so the default case is every builtin that requires mma and paired 7831 // vector memops. 7832 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7833 diag::err_ppc_builtin_only_on_arch, "10") || 7834 SemaFeatureCheck(*this, TheCall, "mma", 7835 diag::err_ppc_builtin_only_on_arch, "10")) 7836 return true; 7837 break; 7838 case PPC::BI__builtin_vsx_lxvp: 7839 case PPC::BI__builtin_vsx_stxvp: 7840 case PPC::BI__builtin_vsx_assemble_pair: 7841 case PPC::BI__builtin_vsx_disassemble_pair: 7842 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7843 diag::err_ppc_builtin_only_on_arch, "10")) 7844 return true; 7845 break; 7846 } 7847 7848 unsigned Mask = 0; 7849 unsigned ArgNum = 0; 7850 7851 // The first type in TypeStr is the type of the value returned by the 7852 // builtin. So we first read that type and change the type of TheCall. 7853 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7854 TheCall->setType(type); 7855 7856 while (*TypeStr != '\0') { 7857 Mask = 0; 7858 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7859 if (ArgNum >= TheCall->getNumArgs()) { 7860 ArgNum++; 7861 break; 7862 } 7863 7864 Expr *Arg = TheCall->getArg(ArgNum); 7865 QualType PassedType = Arg->getType(); 7866 QualType StrippedRVType = PassedType.getCanonicalType(); 7867 7868 // Strip Restrict/Volatile qualifiers. 7869 if (StrippedRVType.isRestrictQualified() || 7870 StrippedRVType.isVolatileQualified()) 7871 StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType(); 7872 7873 // The only case where the argument type and expected type are allowed to 7874 // mismatch is if the argument type is a non-void pointer (or array) and 7875 // expected type is a void pointer. 7876 if (StrippedRVType != ExpectedType) 7877 if (!(ExpectedType->isVoidPointerType() && 7878 (StrippedRVType->isPointerType() || StrippedRVType->isArrayType()))) 7879 return Diag(Arg->getBeginLoc(), 7880 diag::err_typecheck_convert_incompatible) 7881 << PassedType << ExpectedType << 1 << 0 << 0; 7882 7883 // If the value of the Mask is not 0, we have a constraint in the size of 7884 // the integer argument so here we ensure the argument is a constant that 7885 // is in the valid range. 7886 if (Mask != 0 && 7887 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7888 return true; 7889 7890 ArgNum++; 7891 } 7892 7893 // In case we exited early from the previous loop, there are other types to 7894 // read from TypeStr. So we need to read them all to ensure we have the right 7895 // number of arguments in TheCall and if it is not the case, to display a 7896 // better error message. 7897 while (*TypeStr != '\0') { 7898 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7899 ArgNum++; 7900 } 7901 if (checkArgCount(*this, TheCall, ArgNum)) 7902 return true; 7903 7904 return false; 7905 } 7906 7907 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7908 /// This checks that the target supports __builtin_longjmp and 7909 /// that val is a constant 1. 7910 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7911 if (!Context.getTargetInfo().hasSjLjLowering()) 7912 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7913 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7914 7915 Expr *Arg = TheCall->getArg(1); 7916 llvm::APSInt Result; 7917 7918 // TODO: This is less than ideal. Overload this to take a value. 7919 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7920 return true; 7921 7922 if (Result != 1) 7923 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7924 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7925 7926 return false; 7927 } 7928 7929 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7930 /// This checks that the target supports __builtin_setjmp. 7931 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7932 if (!Context.getTargetInfo().hasSjLjLowering()) 7933 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7934 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7935 return false; 7936 } 7937 7938 namespace { 7939 7940 class UncoveredArgHandler { 7941 enum { Unknown = -1, AllCovered = -2 }; 7942 7943 signed FirstUncoveredArg = Unknown; 7944 SmallVector<const Expr *, 4> DiagnosticExprs; 7945 7946 public: 7947 UncoveredArgHandler() = default; 7948 7949 bool hasUncoveredArg() const { 7950 return (FirstUncoveredArg >= 0); 7951 } 7952 7953 unsigned getUncoveredArg() const { 7954 assert(hasUncoveredArg() && "no uncovered argument"); 7955 return FirstUncoveredArg; 7956 } 7957 7958 void setAllCovered() { 7959 // A string has been found with all arguments covered, so clear out 7960 // the diagnostics. 7961 DiagnosticExprs.clear(); 7962 FirstUncoveredArg = AllCovered; 7963 } 7964 7965 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7966 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7967 7968 // Don't update if a previous string covers all arguments. 7969 if (FirstUncoveredArg == AllCovered) 7970 return; 7971 7972 // UncoveredArgHandler tracks the highest uncovered argument index 7973 // and with it all the strings that match this index. 7974 if (NewFirstUncoveredArg == FirstUncoveredArg) 7975 DiagnosticExprs.push_back(StrExpr); 7976 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7977 DiagnosticExprs.clear(); 7978 DiagnosticExprs.push_back(StrExpr); 7979 FirstUncoveredArg = NewFirstUncoveredArg; 7980 } 7981 } 7982 7983 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7984 }; 7985 7986 enum StringLiteralCheckType { 7987 SLCT_NotALiteral, 7988 SLCT_UncheckedLiteral, 7989 SLCT_CheckedLiteral 7990 }; 7991 7992 } // namespace 7993 7994 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7995 BinaryOperatorKind BinOpKind, 7996 bool AddendIsRight) { 7997 unsigned BitWidth = Offset.getBitWidth(); 7998 unsigned AddendBitWidth = Addend.getBitWidth(); 7999 // There might be negative interim results. 8000 if (Addend.isUnsigned()) { 8001 Addend = Addend.zext(++AddendBitWidth); 8002 Addend.setIsSigned(true); 8003 } 8004 // Adjust the bit width of the APSInts. 8005 if (AddendBitWidth > BitWidth) { 8006 Offset = Offset.sext(AddendBitWidth); 8007 BitWidth = AddendBitWidth; 8008 } else if (BitWidth > AddendBitWidth) { 8009 Addend = Addend.sext(BitWidth); 8010 } 8011 8012 bool Ov = false; 8013 llvm::APSInt ResOffset = Offset; 8014 if (BinOpKind == BO_Add) 8015 ResOffset = Offset.sadd_ov(Addend, Ov); 8016 else { 8017 assert(AddendIsRight && BinOpKind == BO_Sub && 8018 "operator must be add or sub with addend on the right"); 8019 ResOffset = Offset.ssub_ov(Addend, Ov); 8020 } 8021 8022 // We add an offset to a pointer here so we should support an offset as big as 8023 // possible. 8024 if (Ov) { 8025 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 8026 "index (intermediate) result too big"); 8027 Offset = Offset.sext(2 * BitWidth); 8028 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 8029 return; 8030 } 8031 8032 Offset = ResOffset; 8033 } 8034 8035 namespace { 8036 8037 // This is a wrapper class around StringLiteral to support offsetted string 8038 // literals as format strings. It takes the offset into account when returning 8039 // the string and its length or the source locations to display notes correctly. 8040 class FormatStringLiteral { 8041 const StringLiteral *FExpr; 8042 int64_t Offset; 8043 8044 public: 8045 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 8046 : FExpr(fexpr), Offset(Offset) {} 8047 8048 StringRef getString() const { 8049 return FExpr->getString().drop_front(Offset); 8050 } 8051 8052 unsigned getByteLength() const { 8053 return FExpr->getByteLength() - getCharByteWidth() * Offset; 8054 } 8055 8056 unsigned getLength() const { return FExpr->getLength() - Offset; } 8057 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 8058 8059 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 8060 8061 QualType getType() const { return FExpr->getType(); } 8062 8063 bool isAscii() const { return FExpr->isAscii(); } 8064 bool isWide() const { return FExpr->isWide(); } 8065 bool isUTF8() const { return FExpr->isUTF8(); } 8066 bool isUTF16() const { return FExpr->isUTF16(); } 8067 bool isUTF32() const { return FExpr->isUTF32(); } 8068 bool isPascal() const { return FExpr->isPascal(); } 8069 8070 SourceLocation getLocationOfByte( 8071 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 8072 const TargetInfo &Target, unsigned *StartToken = nullptr, 8073 unsigned *StartTokenByteOffset = nullptr) const { 8074 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 8075 StartToken, StartTokenByteOffset); 8076 } 8077 8078 SourceLocation getBeginLoc() const LLVM_READONLY { 8079 return FExpr->getBeginLoc().getLocWithOffset(Offset); 8080 } 8081 8082 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 8083 }; 8084 8085 } // namespace 8086 8087 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8088 const Expr *OrigFormatExpr, 8089 ArrayRef<const Expr *> Args, 8090 bool HasVAListArg, unsigned format_idx, 8091 unsigned firstDataArg, 8092 Sema::FormatStringType Type, 8093 bool inFunctionCall, 8094 Sema::VariadicCallType CallType, 8095 llvm::SmallBitVector &CheckedVarArgs, 8096 UncoveredArgHandler &UncoveredArg, 8097 bool IgnoreStringsWithoutSpecifiers); 8098 8099 // Determine if an expression is a string literal or constant string. 8100 // If this function returns false on the arguments to a function expecting a 8101 // format string, we will usually need to emit a warning. 8102 // True string literals are then checked by CheckFormatString. 8103 static StringLiteralCheckType 8104 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 8105 bool HasVAListArg, unsigned format_idx, 8106 unsigned firstDataArg, Sema::FormatStringType Type, 8107 Sema::VariadicCallType CallType, bool InFunctionCall, 8108 llvm::SmallBitVector &CheckedVarArgs, 8109 UncoveredArgHandler &UncoveredArg, 8110 llvm::APSInt Offset, 8111 bool IgnoreStringsWithoutSpecifiers = false) { 8112 if (S.isConstantEvaluated()) 8113 return SLCT_NotALiteral; 8114 tryAgain: 8115 assert(Offset.isSigned() && "invalid offset"); 8116 8117 if (E->isTypeDependent() || E->isValueDependent()) 8118 return SLCT_NotALiteral; 8119 8120 E = E->IgnoreParenCasts(); 8121 8122 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 8123 // Technically -Wformat-nonliteral does not warn about this case. 8124 // The behavior of printf and friends in this case is implementation 8125 // dependent. Ideally if the format string cannot be null then 8126 // it should have a 'nonnull' attribute in the function prototype. 8127 return SLCT_UncheckedLiteral; 8128 8129 switch (E->getStmtClass()) { 8130 case Stmt::BinaryConditionalOperatorClass: 8131 case Stmt::ConditionalOperatorClass: { 8132 // The expression is a literal if both sub-expressions were, and it was 8133 // completely checked only if both sub-expressions were checked. 8134 const AbstractConditionalOperator *C = 8135 cast<AbstractConditionalOperator>(E); 8136 8137 // Determine whether it is necessary to check both sub-expressions, for 8138 // example, because the condition expression is a constant that can be 8139 // evaluated at compile time. 8140 bool CheckLeft = true, CheckRight = true; 8141 8142 bool Cond; 8143 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 8144 S.isConstantEvaluated())) { 8145 if (Cond) 8146 CheckRight = false; 8147 else 8148 CheckLeft = false; 8149 } 8150 8151 // We need to maintain the offsets for the right and the left hand side 8152 // separately to check if every possible indexed expression is a valid 8153 // string literal. They might have different offsets for different string 8154 // literals in the end. 8155 StringLiteralCheckType Left; 8156 if (!CheckLeft) 8157 Left = SLCT_UncheckedLiteral; 8158 else { 8159 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 8160 HasVAListArg, format_idx, firstDataArg, 8161 Type, CallType, InFunctionCall, 8162 CheckedVarArgs, UncoveredArg, Offset, 8163 IgnoreStringsWithoutSpecifiers); 8164 if (Left == SLCT_NotALiteral || !CheckRight) { 8165 return Left; 8166 } 8167 } 8168 8169 StringLiteralCheckType Right = checkFormatStringExpr( 8170 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 8171 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8172 IgnoreStringsWithoutSpecifiers); 8173 8174 return (CheckLeft && Left < Right) ? Left : Right; 8175 } 8176 8177 case Stmt::ImplicitCastExprClass: 8178 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 8179 goto tryAgain; 8180 8181 case Stmt::OpaqueValueExprClass: 8182 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 8183 E = src; 8184 goto tryAgain; 8185 } 8186 return SLCT_NotALiteral; 8187 8188 case Stmt::PredefinedExprClass: 8189 // While __func__, etc., are technically not string literals, they 8190 // cannot contain format specifiers and thus are not a security 8191 // liability. 8192 return SLCT_UncheckedLiteral; 8193 8194 case Stmt::DeclRefExprClass: { 8195 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 8196 8197 // As an exception, do not flag errors for variables binding to 8198 // const string literals. 8199 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 8200 bool isConstant = false; 8201 QualType T = DR->getType(); 8202 8203 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 8204 isConstant = AT->getElementType().isConstant(S.Context); 8205 } else if (const PointerType *PT = T->getAs<PointerType>()) { 8206 isConstant = T.isConstant(S.Context) && 8207 PT->getPointeeType().isConstant(S.Context); 8208 } else if (T->isObjCObjectPointerType()) { 8209 // In ObjC, there is usually no "const ObjectPointer" type, 8210 // so don't check if the pointee type is constant. 8211 isConstant = T.isConstant(S.Context); 8212 } 8213 8214 if (isConstant) { 8215 if (const Expr *Init = VD->getAnyInitializer()) { 8216 // Look through initializers like const char c[] = { "foo" } 8217 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 8218 if (InitList->isStringLiteralInit()) 8219 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 8220 } 8221 return checkFormatStringExpr(S, Init, Args, 8222 HasVAListArg, format_idx, 8223 firstDataArg, Type, CallType, 8224 /*InFunctionCall*/ false, CheckedVarArgs, 8225 UncoveredArg, Offset); 8226 } 8227 } 8228 8229 // For vprintf* functions (i.e., HasVAListArg==true), we add a 8230 // special check to see if the format string is a function parameter 8231 // of the function calling the printf function. If the function 8232 // has an attribute indicating it is a printf-like function, then we 8233 // should suppress warnings concerning non-literals being used in a call 8234 // to a vprintf function. For example: 8235 // 8236 // void 8237 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 8238 // va_list ap; 8239 // va_start(ap, fmt); 8240 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 8241 // ... 8242 // } 8243 if (HasVAListArg) { 8244 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 8245 if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) { 8246 int PVIndex = PV->getFunctionScopeIndex() + 1; 8247 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) { 8248 // adjust for implicit parameter 8249 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) 8250 if (MD->isInstance()) 8251 ++PVIndex; 8252 // We also check if the formats are compatible. 8253 // We can't pass a 'scanf' string to a 'printf' function. 8254 if (PVIndex == PVFormat->getFormatIdx() && 8255 Type == S.GetFormatStringType(PVFormat)) 8256 return SLCT_UncheckedLiteral; 8257 } 8258 } 8259 } 8260 } 8261 } 8262 8263 return SLCT_NotALiteral; 8264 } 8265 8266 case Stmt::CallExprClass: 8267 case Stmt::CXXMemberCallExprClass: { 8268 const CallExpr *CE = cast<CallExpr>(E); 8269 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 8270 bool IsFirst = true; 8271 StringLiteralCheckType CommonResult; 8272 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 8273 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 8274 StringLiteralCheckType Result = checkFormatStringExpr( 8275 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 8276 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8277 IgnoreStringsWithoutSpecifiers); 8278 if (IsFirst) { 8279 CommonResult = Result; 8280 IsFirst = false; 8281 } 8282 } 8283 if (!IsFirst) 8284 return CommonResult; 8285 8286 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 8287 unsigned BuiltinID = FD->getBuiltinID(); 8288 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 8289 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 8290 const Expr *Arg = CE->getArg(0); 8291 return checkFormatStringExpr(S, Arg, Args, 8292 HasVAListArg, format_idx, 8293 firstDataArg, Type, CallType, 8294 InFunctionCall, CheckedVarArgs, 8295 UncoveredArg, Offset, 8296 IgnoreStringsWithoutSpecifiers); 8297 } 8298 } 8299 } 8300 8301 return SLCT_NotALiteral; 8302 } 8303 case Stmt::ObjCMessageExprClass: { 8304 const auto *ME = cast<ObjCMessageExpr>(E); 8305 if (const auto *MD = ME->getMethodDecl()) { 8306 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 8307 // As a special case heuristic, if we're using the method -[NSBundle 8308 // localizedStringForKey:value:table:], ignore any key strings that lack 8309 // format specifiers. The idea is that if the key doesn't have any 8310 // format specifiers then its probably just a key to map to the 8311 // localized strings. If it does have format specifiers though, then its 8312 // likely that the text of the key is the format string in the 8313 // programmer's language, and should be checked. 8314 const ObjCInterfaceDecl *IFace; 8315 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 8316 IFace->getIdentifier()->isStr("NSBundle") && 8317 MD->getSelector().isKeywordSelector( 8318 {"localizedStringForKey", "value", "table"})) { 8319 IgnoreStringsWithoutSpecifiers = true; 8320 } 8321 8322 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 8323 return checkFormatStringExpr( 8324 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 8325 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 8326 IgnoreStringsWithoutSpecifiers); 8327 } 8328 } 8329 8330 return SLCT_NotALiteral; 8331 } 8332 case Stmt::ObjCStringLiteralClass: 8333 case Stmt::StringLiteralClass: { 8334 const StringLiteral *StrE = nullptr; 8335 8336 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 8337 StrE = ObjCFExpr->getString(); 8338 else 8339 StrE = cast<StringLiteral>(E); 8340 8341 if (StrE) { 8342 if (Offset.isNegative() || Offset > StrE->getLength()) { 8343 // TODO: It would be better to have an explicit warning for out of 8344 // bounds literals. 8345 return SLCT_NotALiteral; 8346 } 8347 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 8348 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 8349 firstDataArg, Type, InFunctionCall, CallType, 8350 CheckedVarArgs, UncoveredArg, 8351 IgnoreStringsWithoutSpecifiers); 8352 return SLCT_CheckedLiteral; 8353 } 8354 8355 return SLCT_NotALiteral; 8356 } 8357 case Stmt::BinaryOperatorClass: { 8358 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 8359 8360 // A string literal + an int offset is still a string literal. 8361 if (BinOp->isAdditiveOp()) { 8362 Expr::EvalResult LResult, RResult; 8363 8364 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 8365 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8366 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 8367 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8368 8369 if (LIsInt != RIsInt) { 8370 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 8371 8372 if (LIsInt) { 8373 if (BinOpKind == BO_Add) { 8374 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 8375 E = BinOp->getRHS(); 8376 goto tryAgain; 8377 } 8378 } else { 8379 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 8380 E = BinOp->getLHS(); 8381 goto tryAgain; 8382 } 8383 } 8384 } 8385 8386 return SLCT_NotALiteral; 8387 } 8388 case Stmt::UnaryOperatorClass: { 8389 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 8390 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 8391 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 8392 Expr::EvalResult IndexResult; 8393 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 8394 Expr::SE_NoSideEffects, 8395 S.isConstantEvaluated())) { 8396 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 8397 /*RHS is int*/ true); 8398 E = ASE->getBase(); 8399 goto tryAgain; 8400 } 8401 } 8402 8403 return SLCT_NotALiteral; 8404 } 8405 8406 default: 8407 return SLCT_NotALiteral; 8408 } 8409 } 8410 8411 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 8412 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 8413 .Case("scanf", FST_Scanf) 8414 .Cases("printf", "printf0", FST_Printf) 8415 .Cases("NSString", "CFString", FST_NSString) 8416 .Case("strftime", FST_Strftime) 8417 .Case("strfmon", FST_Strfmon) 8418 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 8419 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 8420 .Case("os_trace", FST_OSLog) 8421 .Case("os_log", FST_OSLog) 8422 .Default(FST_Unknown); 8423 } 8424 8425 /// CheckFormatArguments - Check calls to printf and scanf (and similar 8426 /// functions) for correct use of format strings. 8427 /// Returns true if a format string has been fully checked. 8428 bool Sema::CheckFormatArguments(const FormatAttr *Format, 8429 ArrayRef<const Expr *> Args, 8430 bool IsCXXMember, 8431 VariadicCallType CallType, 8432 SourceLocation Loc, SourceRange Range, 8433 llvm::SmallBitVector &CheckedVarArgs) { 8434 FormatStringInfo FSI; 8435 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 8436 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 8437 FSI.FirstDataArg, GetFormatStringType(Format), 8438 CallType, Loc, Range, CheckedVarArgs); 8439 return false; 8440 } 8441 8442 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 8443 bool HasVAListArg, unsigned format_idx, 8444 unsigned firstDataArg, FormatStringType Type, 8445 VariadicCallType CallType, 8446 SourceLocation Loc, SourceRange Range, 8447 llvm::SmallBitVector &CheckedVarArgs) { 8448 // CHECK: printf/scanf-like function is called with no format string. 8449 if (format_idx >= Args.size()) { 8450 Diag(Loc, diag::warn_missing_format_string) << Range; 8451 return false; 8452 } 8453 8454 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 8455 8456 // CHECK: format string is not a string literal. 8457 // 8458 // Dynamically generated format strings are difficult to 8459 // automatically vet at compile time. Requiring that format strings 8460 // are string literals: (1) permits the checking of format strings by 8461 // the compiler and thereby (2) can practically remove the source of 8462 // many format string exploits. 8463 8464 // Format string can be either ObjC string (e.g. @"%d") or 8465 // C string (e.g. "%d") 8466 // ObjC string uses the same format specifiers as C string, so we can use 8467 // the same format string checking logic for both ObjC and C strings. 8468 UncoveredArgHandler UncoveredArg; 8469 StringLiteralCheckType CT = 8470 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 8471 format_idx, firstDataArg, Type, CallType, 8472 /*IsFunctionCall*/ true, CheckedVarArgs, 8473 UncoveredArg, 8474 /*no string offset*/ llvm::APSInt(64, false) = 0); 8475 8476 // Generate a diagnostic where an uncovered argument is detected. 8477 if (UncoveredArg.hasUncoveredArg()) { 8478 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 8479 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 8480 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 8481 } 8482 8483 if (CT != SLCT_NotALiteral) 8484 // Literal format string found, check done! 8485 return CT == SLCT_CheckedLiteral; 8486 8487 // Strftime is particular as it always uses a single 'time' argument, 8488 // so it is safe to pass a non-literal string. 8489 if (Type == FST_Strftime) 8490 return false; 8491 8492 // Do not emit diag when the string param is a macro expansion and the 8493 // format is either NSString or CFString. This is a hack to prevent 8494 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 8495 // which are usually used in place of NS and CF string literals. 8496 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 8497 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 8498 return false; 8499 8500 // If there are no arguments specified, warn with -Wformat-security, otherwise 8501 // warn only with -Wformat-nonliteral. 8502 if (Args.size() == firstDataArg) { 8503 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 8504 << OrigFormatExpr->getSourceRange(); 8505 switch (Type) { 8506 default: 8507 break; 8508 case FST_Kprintf: 8509 case FST_FreeBSDKPrintf: 8510 case FST_Printf: 8511 Diag(FormatLoc, diag::note_format_security_fixit) 8512 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 8513 break; 8514 case FST_NSString: 8515 Diag(FormatLoc, diag::note_format_security_fixit) 8516 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 8517 break; 8518 } 8519 } else { 8520 Diag(FormatLoc, diag::warn_format_nonliteral) 8521 << OrigFormatExpr->getSourceRange(); 8522 } 8523 return false; 8524 } 8525 8526 namespace { 8527 8528 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 8529 protected: 8530 Sema &S; 8531 const FormatStringLiteral *FExpr; 8532 const Expr *OrigFormatExpr; 8533 const Sema::FormatStringType FSType; 8534 const unsigned FirstDataArg; 8535 const unsigned NumDataArgs; 8536 const char *Beg; // Start of format string. 8537 const bool HasVAListArg; 8538 ArrayRef<const Expr *> Args; 8539 unsigned FormatIdx; 8540 llvm::SmallBitVector CoveredArgs; 8541 bool usesPositionalArgs = false; 8542 bool atFirstArg = true; 8543 bool inFunctionCall; 8544 Sema::VariadicCallType CallType; 8545 llvm::SmallBitVector &CheckedVarArgs; 8546 UncoveredArgHandler &UncoveredArg; 8547 8548 public: 8549 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 8550 const Expr *origFormatExpr, 8551 const Sema::FormatStringType type, unsigned firstDataArg, 8552 unsigned numDataArgs, const char *beg, bool hasVAListArg, 8553 ArrayRef<const Expr *> Args, unsigned formatIdx, 8554 bool inFunctionCall, Sema::VariadicCallType callType, 8555 llvm::SmallBitVector &CheckedVarArgs, 8556 UncoveredArgHandler &UncoveredArg) 8557 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 8558 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 8559 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 8560 inFunctionCall(inFunctionCall), CallType(callType), 8561 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 8562 CoveredArgs.resize(numDataArgs); 8563 CoveredArgs.reset(); 8564 } 8565 8566 void DoneProcessing(); 8567 8568 void HandleIncompleteSpecifier(const char *startSpecifier, 8569 unsigned specifierLen) override; 8570 8571 void HandleInvalidLengthModifier( 8572 const analyze_format_string::FormatSpecifier &FS, 8573 const analyze_format_string::ConversionSpecifier &CS, 8574 const char *startSpecifier, unsigned specifierLen, 8575 unsigned DiagID); 8576 8577 void HandleNonStandardLengthModifier( 8578 const analyze_format_string::FormatSpecifier &FS, 8579 const char *startSpecifier, unsigned specifierLen); 8580 8581 void HandleNonStandardConversionSpecifier( 8582 const analyze_format_string::ConversionSpecifier &CS, 8583 const char *startSpecifier, unsigned specifierLen); 8584 8585 void HandlePosition(const char *startPos, unsigned posLen) override; 8586 8587 void HandleInvalidPosition(const char *startSpecifier, 8588 unsigned specifierLen, 8589 analyze_format_string::PositionContext p) override; 8590 8591 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 8592 8593 void HandleNullChar(const char *nullCharacter) override; 8594 8595 template <typename Range> 8596 static void 8597 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 8598 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 8599 bool IsStringLocation, Range StringRange, 8600 ArrayRef<FixItHint> Fixit = None); 8601 8602 protected: 8603 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 8604 const char *startSpec, 8605 unsigned specifierLen, 8606 const char *csStart, unsigned csLen); 8607 8608 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 8609 const char *startSpec, 8610 unsigned specifierLen); 8611 8612 SourceRange getFormatStringRange(); 8613 CharSourceRange getSpecifierRange(const char *startSpecifier, 8614 unsigned specifierLen); 8615 SourceLocation getLocationOfByte(const char *x); 8616 8617 const Expr *getDataArg(unsigned i) const; 8618 8619 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 8620 const analyze_format_string::ConversionSpecifier &CS, 8621 const char *startSpecifier, unsigned specifierLen, 8622 unsigned argIndex); 8623 8624 template <typename Range> 8625 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 8626 bool IsStringLocation, Range StringRange, 8627 ArrayRef<FixItHint> Fixit = None); 8628 }; 8629 8630 } // namespace 8631 8632 SourceRange CheckFormatHandler::getFormatStringRange() { 8633 return OrigFormatExpr->getSourceRange(); 8634 } 8635 8636 CharSourceRange CheckFormatHandler:: 8637 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 8638 SourceLocation Start = getLocationOfByte(startSpecifier); 8639 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 8640 8641 // Advance the end SourceLocation by one due to half-open ranges. 8642 End = End.getLocWithOffset(1); 8643 8644 return CharSourceRange::getCharRange(Start, End); 8645 } 8646 8647 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 8648 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 8649 S.getLangOpts(), S.Context.getTargetInfo()); 8650 } 8651 8652 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 8653 unsigned specifierLen){ 8654 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 8655 getLocationOfByte(startSpecifier), 8656 /*IsStringLocation*/true, 8657 getSpecifierRange(startSpecifier, specifierLen)); 8658 } 8659 8660 void CheckFormatHandler::HandleInvalidLengthModifier( 8661 const analyze_format_string::FormatSpecifier &FS, 8662 const analyze_format_string::ConversionSpecifier &CS, 8663 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 8664 using namespace analyze_format_string; 8665 8666 const LengthModifier &LM = FS.getLengthModifier(); 8667 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8668 8669 // See if we know how to fix this length modifier. 8670 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8671 if (FixedLM) { 8672 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8673 getLocationOfByte(LM.getStart()), 8674 /*IsStringLocation*/true, 8675 getSpecifierRange(startSpecifier, specifierLen)); 8676 8677 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8678 << FixedLM->toString() 8679 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8680 8681 } else { 8682 FixItHint Hint; 8683 if (DiagID == diag::warn_format_nonsensical_length) 8684 Hint = FixItHint::CreateRemoval(LMRange); 8685 8686 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8687 getLocationOfByte(LM.getStart()), 8688 /*IsStringLocation*/true, 8689 getSpecifierRange(startSpecifier, specifierLen), 8690 Hint); 8691 } 8692 } 8693 8694 void CheckFormatHandler::HandleNonStandardLengthModifier( 8695 const analyze_format_string::FormatSpecifier &FS, 8696 const char *startSpecifier, unsigned specifierLen) { 8697 using namespace analyze_format_string; 8698 8699 const LengthModifier &LM = FS.getLengthModifier(); 8700 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8701 8702 // See if we know how to fix this length modifier. 8703 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8704 if (FixedLM) { 8705 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8706 << LM.toString() << 0, 8707 getLocationOfByte(LM.getStart()), 8708 /*IsStringLocation*/true, 8709 getSpecifierRange(startSpecifier, specifierLen)); 8710 8711 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8712 << FixedLM->toString() 8713 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8714 8715 } else { 8716 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8717 << LM.toString() << 0, 8718 getLocationOfByte(LM.getStart()), 8719 /*IsStringLocation*/true, 8720 getSpecifierRange(startSpecifier, specifierLen)); 8721 } 8722 } 8723 8724 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 8725 const analyze_format_string::ConversionSpecifier &CS, 8726 const char *startSpecifier, unsigned specifierLen) { 8727 using namespace analyze_format_string; 8728 8729 // See if we know how to fix this conversion specifier. 8730 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 8731 if (FixedCS) { 8732 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8733 << CS.toString() << /*conversion specifier*/1, 8734 getLocationOfByte(CS.getStart()), 8735 /*IsStringLocation*/true, 8736 getSpecifierRange(startSpecifier, specifierLen)); 8737 8738 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 8739 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 8740 << FixedCS->toString() 8741 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 8742 } else { 8743 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8744 << CS.toString() << /*conversion specifier*/1, 8745 getLocationOfByte(CS.getStart()), 8746 /*IsStringLocation*/true, 8747 getSpecifierRange(startSpecifier, specifierLen)); 8748 } 8749 } 8750 8751 void CheckFormatHandler::HandlePosition(const char *startPos, 8752 unsigned posLen) { 8753 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 8754 getLocationOfByte(startPos), 8755 /*IsStringLocation*/true, 8756 getSpecifierRange(startPos, posLen)); 8757 } 8758 8759 void 8760 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 8761 analyze_format_string::PositionContext p) { 8762 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 8763 << (unsigned) p, 8764 getLocationOfByte(startPos), /*IsStringLocation*/true, 8765 getSpecifierRange(startPos, posLen)); 8766 } 8767 8768 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 8769 unsigned posLen) { 8770 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 8771 getLocationOfByte(startPos), 8772 /*IsStringLocation*/true, 8773 getSpecifierRange(startPos, posLen)); 8774 } 8775 8776 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 8777 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 8778 // The presence of a null character is likely an error. 8779 EmitFormatDiagnostic( 8780 S.PDiag(diag::warn_printf_format_string_contains_null_char), 8781 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 8782 getFormatStringRange()); 8783 } 8784 } 8785 8786 // Note that this may return NULL if there was an error parsing or building 8787 // one of the argument expressions. 8788 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 8789 return Args[FirstDataArg + i]; 8790 } 8791 8792 void CheckFormatHandler::DoneProcessing() { 8793 // Does the number of data arguments exceed the number of 8794 // format conversions in the format string? 8795 if (!HasVAListArg) { 8796 // Find any arguments that weren't covered. 8797 CoveredArgs.flip(); 8798 signed notCoveredArg = CoveredArgs.find_first(); 8799 if (notCoveredArg >= 0) { 8800 assert((unsigned)notCoveredArg < NumDataArgs); 8801 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 8802 } else { 8803 UncoveredArg.setAllCovered(); 8804 } 8805 } 8806 } 8807 8808 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 8809 const Expr *ArgExpr) { 8810 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 8811 "Invalid state"); 8812 8813 if (!ArgExpr) 8814 return; 8815 8816 SourceLocation Loc = ArgExpr->getBeginLoc(); 8817 8818 if (S.getSourceManager().isInSystemMacro(Loc)) 8819 return; 8820 8821 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8822 for (auto E : DiagnosticExprs) 8823 PDiag << E->getSourceRange(); 8824 8825 CheckFormatHandler::EmitFormatDiagnostic( 8826 S, IsFunctionCall, DiagnosticExprs[0], 8827 PDiag, Loc, /*IsStringLocation*/false, 8828 DiagnosticExprs[0]->getSourceRange()); 8829 } 8830 8831 bool 8832 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8833 SourceLocation Loc, 8834 const char *startSpec, 8835 unsigned specifierLen, 8836 const char *csStart, 8837 unsigned csLen) { 8838 bool keepGoing = true; 8839 if (argIndex < NumDataArgs) { 8840 // Consider the argument coverered, even though the specifier doesn't 8841 // make sense. 8842 CoveredArgs.set(argIndex); 8843 } 8844 else { 8845 // If argIndex exceeds the number of data arguments we 8846 // don't issue a warning because that is just a cascade of warnings (and 8847 // they may have intended '%%' anyway). We don't want to continue processing 8848 // the format string after this point, however, as we will like just get 8849 // gibberish when trying to match arguments. 8850 keepGoing = false; 8851 } 8852 8853 StringRef Specifier(csStart, csLen); 8854 8855 // If the specifier in non-printable, it could be the first byte of a UTF-8 8856 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8857 // hex value. 8858 std::string CodePointStr; 8859 if (!llvm::sys::locale::isPrint(*csStart)) { 8860 llvm::UTF32 CodePoint; 8861 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8862 const llvm::UTF8 *E = 8863 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8864 llvm::ConversionResult Result = 8865 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8866 8867 if (Result != llvm::conversionOK) { 8868 unsigned char FirstChar = *csStart; 8869 CodePoint = (llvm::UTF32)FirstChar; 8870 } 8871 8872 llvm::raw_string_ostream OS(CodePointStr); 8873 if (CodePoint < 256) 8874 OS << "\\x" << llvm::format("%02x", CodePoint); 8875 else if (CodePoint <= 0xFFFF) 8876 OS << "\\u" << llvm::format("%04x", CodePoint); 8877 else 8878 OS << "\\U" << llvm::format("%08x", CodePoint); 8879 OS.flush(); 8880 Specifier = CodePointStr; 8881 } 8882 8883 EmitFormatDiagnostic( 8884 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8885 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8886 8887 return keepGoing; 8888 } 8889 8890 void 8891 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8892 const char *startSpec, 8893 unsigned specifierLen) { 8894 EmitFormatDiagnostic( 8895 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8896 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8897 } 8898 8899 bool 8900 CheckFormatHandler::CheckNumArgs( 8901 const analyze_format_string::FormatSpecifier &FS, 8902 const analyze_format_string::ConversionSpecifier &CS, 8903 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8904 8905 if (argIndex >= NumDataArgs) { 8906 PartialDiagnostic PDiag = FS.usesPositionalArg() 8907 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8908 << (argIndex+1) << NumDataArgs) 8909 : S.PDiag(diag::warn_printf_insufficient_data_args); 8910 EmitFormatDiagnostic( 8911 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8912 getSpecifierRange(startSpecifier, specifierLen)); 8913 8914 // Since more arguments than conversion tokens are given, by extension 8915 // all arguments are covered, so mark this as so. 8916 UncoveredArg.setAllCovered(); 8917 return false; 8918 } 8919 return true; 8920 } 8921 8922 template<typename Range> 8923 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8924 SourceLocation Loc, 8925 bool IsStringLocation, 8926 Range StringRange, 8927 ArrayRef<FixItHint> FixIt) { 8928 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8929 Loc, IsStringLocation, StringRange, FixIt); 8930 } 8931 8932 /// If the format string is not within the function call, emit a note 8933 /// so that the function call and string are in diagnostic messages. 8934 /// 8935 /// \param InFunctionCall if true, the format string is within the function 8936 /// call and only one diagnostic message will be produced. Otherwise, an 8937 /// extra note will be emitted pointing to location of the format string. 8938 /// 8939 /// \param ArgumentExpr the expression that is passed as the format string 8940 /// argument in the function call. Used for getting locations when two 8941 /// diagnostics are emitted. 8942 /// 8943 /// \param PDiag the callee should already have provided any strings for the 8944 /// diagnostic message. This function only adds locations and fixits 8945 /// to diagnostics. 8946 /// 8947 /// \param Loc primary location for diagnostic. If two diagnostics are 8948 /// required, one will be at Loc and a new SourceLocation will be created for 8949 /// the other one. 8950 /// 8951 /// \param IsStringLocation if true, Loc points to the format string should be 8952 /// used for the note. Otherwise, Loc points to the argument list and will 8953 /// be used with PDiag. 8954 /// 8955 /// \param StringRange some or all of the string to highlight. This is 8956 /// templated so it can accept either a CharSourceRange or a SourceRange. 8957 /// 8958 /// \param FixIt optional fix it hint for the format string. 8959 template <typename Range> 8960 void CheckFormatHandler::EmitFormatDiagnostic( 8961 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8962 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8963 Range StringRange, ArrayRef<FixItHint> FixIt) { 8964 if (InFunctionCall) { 8965 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8966 D << StringRange; 8967 D << FixIt; 8968 } else { 8969 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8970 << ArgumentExpr->getSourceRange(); 8971 8972 const Sema::SemaDiagnosticBuilder &Note = 8973 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8974 diag::note_format_string_defined); 8975 8976 Note << StringRange; 8977 Note << FixIt; 8978 } 8979 } 8980 8981 //===--- CHECK: Printf format string checking ------------------------------===// 8982 8983 namespace { 8984 8985 class CheckPrintfHandler : public CheckFormatHandler { 8986 public: 8987 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8988 const Expr *origFormatExpr, 8989 const Sema::FormatStringType type, unsigned firstDataArg, 8990 unsigned numDataArgs, bool isObjC, const char *beg, 8991 bool hasVAListArg, ArrayRef<const Expr *> Args, 8992 unsigned formatIdx, bool inFunctionCall, 8993 Sema::VariadicCallType CallType, 8994 llvm::SmallBitVector &CheckedVarArgs, 8995 UncoveredArgHandler &UncoveredArg) 8996 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8997 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8998 inFunctionCall, CallType, CheckedVarArgs, 8999 UncoveredArg) {} 9000 9001 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 9002 9003 /// Returns true if '%@' specifiers are allowed in the format string. 9004 bool allowsObjCArg() const { 9005 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 9006 FSType == Sema::FST_OSTrace; 9007 } 9008 9009 bool HandleInvalidPrintfConversionSpecifier( 9010 const analyze_printf::PrintfSpecifier &FS, 9011 const char *startSpecifier, 9012 unsigned specifierLen) override; 9013 9014 void handleInvalidMaskType(StringRef MaskType) override; 9015 9016 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 9017 const char *startSpecifier, unsigned specifierLen, 9018 const TargetInfo &Target) override; 9019 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9020 const char *StartSpecifier, 9021 unsigned SpecifierLen, 9022 const Expr *E); 9023 9024 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 9025 const char *startSpecifier, unsigned specifierLen); 9026 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 9027 const analyze_printf::OptionalAmount &Amt, 9028 unsigned type, 9029 const char *startSpecifier, unsigned specifierLen); 9030 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 9031 const analyze_printf::OptionalFlag &flag, 9032 const char *startSpecifier, unsigned specifierLen); 9033 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 9034 const analyze_printf::OptionalFlag &ignoredFlag, 9035 const analyze_printf::OptionalFlag &flag, 9036 const char *startSpecifier, unsigned specifierLen); 9037 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 9038 const Expr *E); 9039 9040 void HandleEmptyObjCModifierFlag(const char *startFlag, 9041 unsigned flagLen) override; 9042 9043 void HandleInvalidObjCModifierFlag(const char *startFlag, 9044 unsigned flagLen) override; 9045 9046 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 9047 const char *flagsEnd, 9048 const char *conversionPosition) 9049 override; 9050 }; 9051 9052 } // namespace 9053 9054 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 9055 const analyze_printf::PrintfSpecifier &FS, 9056 const char *startSpecifier, 9057 unsigned specifierLen) { 9058 const analyze_printf::PrintfConversionSpecifier &CS = 9059 FS.getConversionSpecifier(); 9060 9061 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9062 getLocationOfByte(CS.getStart()), 9063 startSpecifier, specifierLen, 9064 CS.getStart(), CS.getLength()); 9065 } 9066 9067 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 9068 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 9069 } 9070 9071 bool CheckPrintfHandler::HandleAmount( 9072 const analyze_format_string::OptionalAmount &Amt, 9073 unsigned k, const char *startSpecifier, 9074 unsigned specifierLen) { 9075 if (Amt.hasDataArgument()) { 9076 if (!HasVAListArg) { 9077 unsigned argIndex = Amt.getArgIndex(); 9078 if (argIndex >= NumDataArgs) { 9079 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 9080 << k, 9081 getLocationOfByte(Amt.getStart()), 9082 /*IsStringLocation*/true, 9083 getSpecifierRange(startSpecifier, specifierLen)); 9084 // Don't do any more checking. We will just emit 9085 // spurious errors. 9086 return false; 9087 } 9088 9089 // Type check the data argument. It should be an 'int'. 9090 // Although not in conformance with C99, we also allow the argument to be 9091 // an 'unsigned int' as that is a reasonably safe case. GCC also 9092 // doesn't emit a warning for that case. 9093 CoveredArgs.set(argIndex); 9094 const Expr *Arg = getDataArg(argIndex); 9095 if (!Arg) 9096 return false; 9097 9098 QualType T = Arg->getType(); 9099 9100 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 9101 assert(AT.isValid()); 9102 9103 if (!AT.matchesType(S.Context, T)) { 9104 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 9105 << k << AT.getRepresentativeTypeName(S.Context) 9106 << T << Arg->getSourceRange(), 9107 getLocationOfByte(Amt.getStart()), 9108 /*IsStringLocation*/true, 9109 getSpecifierRange(startSpecifier, specifierLen)); 9110 // Don't do any more checking. We will just emit 9111 // spurious errors. 9112 return false; 9113 } 9114 } 9115 } 9116 return true; 9117 } 9118 9119 void CheckPrintfHandler::HandleInvalidAmount( 9120 const analyze_printf::PrintfSpecifier &FS, 9121 const analyze_printf::OptionalAmount &Amt, 9122 unsigned type, 9123 const char *startSpecifier, 9124 unsigned specifierLen) { 9125 const analyze_printf::PrintfConversionSpecifier &CS = 9126 FS.getConversionSpecifier(); 9127 9128 FixItHint fixit = 9129 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 9130 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 9131 Amt.getConstantLength())) 9132 : FixItHint(); 9133 9134 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 9135 << type << CS.toString(), 9136 getLocationOfByte(Amt.getStart()), 9137 /*IsStringLocation*/true, 9138 getSpecifierRange(startSpecifier, specifierLen), 9139 fixit); 9140 } 9141 9142 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 9143 const analyze_printf::OptionalFlag &flag, 9144 const char *startSpecifier, 9145 unsigned specifierLen) { 9146 // Warn about pointless flag with a fixit removal. 9147 const analyze_printf::PrintfConversionSpecifier &CS = 9148 FS.getConversionSpecifier(); 9149 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 9150 << flag.toString() << CS.toString(), 9151 getLocationOfByte(flag.getPosition()), 9152 /*IsStringLocation*/true, 9153 getSpecifierRange(startSpecifier, specifierLen), 9154 FixItHint::CreateRemoval( 9155 getSpecifierRange(flag.getPosition(), 1))); 9156 } 9157 9158 void CheckPrintfHandler::HandleIgnoredFlag( 9159 const analyze_printf::PrintfSpecifier &FS, 9160 const analyze_printf::OptionalFlag &ignoredFlag, 9161 const analyze_printf::OptionalFlag &flag, 9162 const char *startSpecifier, 9163 unsigned specifierLen) { 9164 // Warn about ignored flag with a fixit removal. 9165 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 9166 << ignoredFlag.toString() << flag.toString(), 9167 getLocationOfByte(ignoredFlag.getPosition()), 9168 /*IsStringLocation*/true, 9169 getSpecifierRange(startSpecifier, specifierLen), 9170 FixItHint::CreateRemoval( 9171 getSpecifierRange(ignoredFlag.getPosition(), 1))); 9172 } 9173 9174 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 9175 unsigned flagLen) { 9176 // Warn about an empty flag. 9177 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 9178 getLocationOfByte(startFlag), 9179 /*IsStringLocation*/true, 9180 getSpecifierRange(startFlag, flagLen)); 9181 } 9182 9183 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 9184 unsigned flagLen) { 9185 // Warn about an invalid flag. 9186 auto Range = getSpecifierRange(startFlag, flagLen); 9187 StringRef flag(startFlag, flagLen); 9188 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 9189 getLocationOfByte(startFlag), 9190 /*IsStringLocation*/true, 9191 Range, FixItHint::CreateRemoval(Range)); 9192 } 9193 9194 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 9195 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 9196 // Warn about using '[...]' without a '@' conversion. 9197 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 9198 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 9199 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 9200 getLocationOfByte(conversionPosition), 9201 /*IsStringLocation*/true, 9202 Range, FixItHint::CreateRemoval(Range)); 9203 } 9204 9205 // Determines if the specified is a C++ class or struct containing 9206 // a member with the specified name and kind (e.g. a CXXMethodDecl named 9207 // "c_str()"). 9208 template<typename MemberKind> 9209 static llvm::SmallPtrSet<MemberKind*, 1> 9210 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 9211 const RecordType *RT = Ty->getAs<RecordType>(); 9212 llvm::SmallPtrSet<MemberKind*, 1> Results; 9213 9214 if (!RT) 9215 return Results; 9216 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 9217 if (!RD || !RD->getDefinition()) 9218 return Results; 9219 9220 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 9221 Sema::LookupMemberName); 9222 R.suppressDiagnostics(); 9223 9224 // We just need to include all members of the right kind turned up by the 9225 // filter, at this point. 9226 if (S.LookupQualifiedName(R, RT->getDecl())) 9227 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 9228 NamedDecl *decl = (*I)->getUnderlyingDecl(); 9229 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 9230 Results.insert(FK); 9231 } 9232 return Results; 9233 } 9234 9235 /// Check if we could call '.c_str()' on an object. 9236 /// 9237 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 9238 /// allow the call, or if it would be ambiguous). 9239 bool Sema::hasCStrMethod(const Expr *E) { 9240 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 9241 9242 MethodSet Results = 9243 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 9244 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 9245 MI != ME; ++MI) 9246 if ((*MI)->getMinRequiredArguments() == 0) 9247 return true; 9248 return false; 9249 } 9250 9251 // Check if a (w)string was passed when a (w)char* was needed, and offer a 9252 // better diagnostic if so. AT is assumed to be valid. 9253 // Returns true when a c_str() conversion method is found. 9254 bool CheckPrintfHandler::checkForCStrMembers( 9255 const analyze_printf::ArgType &AT, const Expr *E) { 9256 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 9257 9258 MethodSet Results = 9259 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 9260 9261 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 9262 MI != ME; ++MI) { 9263 const CXXMethodDecl *Method = *MI; 9264 if (Method->getMinRequiredArguments() == 0 && 9265 AT.matchesType(S.Context, Method->getReturnType())) { 9266 // FIXME: Suggest parens if the expression needs them. 9267 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 9268 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 9269 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 9270 return true; 9271 } 9272 } 9273 9274 return false; 9275 } 9276 9277 bool CheckPrintfHandler::HandlePrintfSpecifier( 9278 const analyze_printf::PrintfSpecifier &FS, const char *startSpecifier, 9279 unsigned specifierLen, const TargetInfo &Target) { 9280 using namespace analyze_format_string; 9281 using namespace analyze_printf; 9282 9283 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 9284 9285 if (FS.consumesDataArgument()) { 9286 if (atFirstArg) { 9287 atFirstArg = false; 9288 usesPositionalArgs = FS.usesPositionalArg(); 9289 } 9290 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9291 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9292 startSpecifier, specifierLen); 9293 return false; 9294 } 9295 } 9296 9297 // First check if the field width, precision, and conversion specifier 9298 // have matching data arguments. 9299 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 9300 startSpecifier, specifierLen)) { 9301 return false; 9302 } 9303 9304 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 9305 startSpecifier, specifierLen)) { 9306 return false; 9307 } 9308 9309 if (!CS.consumesDataArgument()) { 9310 // FIXME: Technically specifying a precision or field width here 9311 // makes no sense. Worth issuing a warning at some point. 9312 return true; 9313 } 9314 9315 // Consume the argument. 9316 unsigned argIndex = FS.getArgIndex(); 9317 if (argIndex < NumDataArgs) { 9318 // The check to see if the argIndex is valid will come later. 9319 // We set the bit here because we may exit early from this 9320 // function if we encounter some other error. 9321 CoveredArgs.set(argIndex); 9322 } 9323 9324 // FreeBSD kernel extensions. 9325 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 9326 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 9327 // We need at least two arguments. 9328 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 9329 return false; 9330 9331 // Claim the second argument. 9332 CoveredArgs.set(argIndex + 1); 9333 9334 // Type check the first argument (int for %b, pointer for %D) 9335 const Expr *Ex = getDataArg(argIndex); 9336 const analyze_printf::ArgType &AT = 9337 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 9338 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 9339 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 9340 EmitFormatDiagnostic( 9341 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9342 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 9343 << false << Ex->getSourceRange(), 9344 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9345 getSpecifierRange(startSpecifier, specifierLen)); 9346 9347 // Type check the second argument (char * for both %b and %D) 9348 Ex = getDataArg(argIndex + 1); 9349 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 9350 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 9351 EmitFormatDiagnostic( 9352 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9353 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 9354 << false << Ex->getSourceRange(), 9355 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9356 getSpecifierRange(startSpecifier, specifierLen)); 9357 9358 return true; 9359 } 9360 9361 // Check for using an Objective-C specific conversion specifier 9362 // in a non-ObjC literal. 9363 if (!allowsObjCArg() && CS.isObjCArg()) { 9364 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9365 specifierLen); 9366 } 9367 9368 // %P can only be used with os_log. 9369 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 9370 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9371 specifierLen); 9372 } 9373 9374 // %n is not allowed with os_log. 9375 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 9376 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 9377 getLocationOfByte(CS.getStart()), 9378 /*IsStringLocation*/ false, 9379 getSpecifierRange(startSpecifier, specifierLen)); 9380 9381 return true; 9382 } 9383 9384 // Only scalars are allowed for os_trace. 9385 if (FSType == Sema::FST_OSTrace && 9386 (CS.getKind() == ConversionSpecifier::PArg || 9387 CS.getKind() == ConversionSpecifier::sArg || 9388 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 9389 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9390 specifierLen); 9391 } 9392 9393 // Check for use of public/private annotation outside of os_log(). 9394 if (FSType != Sema::FST_OSLog) { 9395 if (FS.isPublic().isSet()) { 9396 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9397 << "public", 9398 getLocationOfByte(FS.isPublic().getPosition()), 9399 /*IsStringLocation*/ false, 9400 getSpecifierRange(startSpecifier, specifierLen)); 9401 } 9402 if (FS.isPrivate().isSet()) { 9403 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9404 << "private", 9405 getLocationOfByte(FS.isPrivate().getPosition()), 9406 /*IsStringLocation*/ false, 9407 getSpecifierRange(startSpecifier, specifierLen)); 9408 } 9409 } 9410 9411 const llvm::Triple &Triple = Target.getTriple(); 9412 if (CS.getKind() == ConversionSpecifier::nArg && 9413 (Triple.isAndroid() || Triple.isOSFuchsia())) { 9414 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_narg_not_supported), 9415 getLocationOfByte(CS.getStart()), 9416 /*IsStringLocation*/ false, 9417 getSpecifierRange(startSpecifier, specifierLen)); 9418 } 9419 9420 // Check for invalid use of field width 9421 if (!FS.hasValidFieldWidth()) { 9422 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 9423 startSpecifier, specifierLen); 9424 } 9425 9426 // Check for invalid use of precision 9427 if (!FS.hasValidPrecision()) { 9428 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 9429 startSpecifier, specifierLen); 9430 } 9431 9432 // Precision is mandatory for %P specifier. 9433 if (CS.getKind() == ConversionSpecifier::PArg && 9434 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 9435 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 9436 getLocationOfByte(startSpecifier), 9437 /*IsStringLocation*/ false, 9438 getSpecifierRange(startSpecifier, specifierLen)); 9439 } 9440 9441 // Check each flag does not conflict with any other component. 9442 if (!FS.hasValidThousandsGroupingPrefix()) 9443 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 9444 if (!FS.hasValidLeadingZeros()) 9445 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 9446 if (!FS.hasValidPlusPrefix()) 9447 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 9448 if (!FS.hasValidSpacePrefix()) 9449 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 9450 if (!FS.hasValidAlternativeForm()) 9451 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 9452 if (!FS.hasValidLeftJustified()) 9453 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 9454 9455 // Check that flags are not ignored by another flag 9456 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 9457 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 9458 startSpecifier, specifierLen); 9459 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 9460 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 9461 startSpecifier, specifierLen); 9462 9463 // Check the length modifier is valid with the given conversion specifier. 9464 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9465 S.getLangOpts())) 9466 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9467 diag::warn_format_nonsensical_length); 9468 else if (!FS.hasStandardLengthModifier()) 9469 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9470 else if (!FS.hasStandardLengthConversionCombination()) 9471 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9472 diag::warn_format_non_standard_conversion_spec); 9473 9474 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9475 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9476 9477 // The remaining checks depend on the data arguments. 9478 if (HasVAListArg) 9479 return true; 9480 9481 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9482 return false; 9483 9484 const Expr *Arg = getDataArg(argIndex); 9485 if (!Arg) 9486 return true; 9487 9488 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 9489 } 9490 9491 static bool requiresParensToAddCast(const Expr *E) { 9492 // FIXME: We should have a general way to reason about operator 9493 // precedence and whether parens are actually needed here. 9494 // Take care of a few common cases where they aren't. 9495 const Expr *Inside = E->IgnoreImpCasts(); 9496 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 9497 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 9498 9499 switch (Inside->getStmtClass()) { 9500 case Stmt::ArraySubscriptExprClass: 9501 case Stmt::CallExprClass: 9502 case Stmt::CharacterLiteralClass: 9503 case Stmt::CXXBoolLiteralExprClass: 9504 case Stmt::DeclRefExprClass: 9505 case Stmt::FloatingLiteralClass: 9506 case Stmt::IntegerLiteralClass: 9507 case Stmt::MemberExprClass: 9508 case Stmt::ObjCArrayLiteralClass: 9509 case Stmt::ObjCBoolLiteralExprClass: 9510 case Stmt::ObjCBoxedExprClass: 9511 case Stmt::ObjCDictionaryLiteralClass: 9512 case Stmt::ObjCEncodeExprClass: 9513 case Stmt::ObjCIvarRefExprClass: 9514 case Stmt::ObjCMessageExprClass: 9515 case Stmt::ObjCPropertyRefExprClass: 9516 case Stmt::ObjCStringLiteralClass: 9517 case Stmt::ObjCSubscriptRefExprClass: 9518 case Stmt::ParenExprClass: 9519 case Stmt::StringLiteralClass: 9520 case Stmt::UnaryOperatorClass: 9521 return false; 9522 default: 9523 return true; 9524 } 9525 } 9526 9527 static std::pair<QualType, StringRef> 9528 shouldNotPrintDirectly(const ASTContext &Context, 9529 QualType IntendedTy, 9530 const Expr *E) { 9531 // Use a 'while' to peel off layers of typedefs. 9532 QualType TyTy = IntendedTy; 9533 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 9534 StringRef Name = UserTy->getDecl()->getName(); 9535 QualType CastTy = llvm::StringSwitch<QualType>(Name) 9536 .Case("CFIndex", Context.getNSIntegerType()) 9537 .Case("NSInteger", Context.getNSIntegerType()) 9538 .Case("NSUInteger", Context.getNSUIntegerType()) 9539 .Case("SInt32", Context.IntTy) 9540 .Case("UInt32", Context.UnsignedIntTy) 9541 .Default(QualType()); 9542 9543 if (!CastTy.isNull()) 9544 return std::make_pair(CastTy, Name); 9545 9546 TyTy = UserTy->desugar(); 9547 } 9548 9549 // Strip parens if necessary. 9550 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 9551 return shouldNotPrintDirectly(Context, 9552 PE->getSubExpr()->getType(), 9553 PE->getSubExpr()); 9554 9555 // If this is a conditional expression, then its result type is constructed 9556 // via usual arithmetic conversions and thus there might be no necessary 9557 // typedef sugar there. Recurse to operands to check for NSInteger & 9558 // Co. usage condition. 9559 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9560 QualType TrueTy, FalseTy; 9561 StringRef TrueName, FalseName; 9562 9563 std::tie(TrueTy, TrueName) = 9564 shouldNotPrintDirectly(Context, 9565 CO->getTrueExpr()->getType(), 9566 CO->getTrueExpr()); 9567 std::tie(FalseTy, FalseName) = 9568 shouldNotPrintDirectly(Context, 9569 CO->getFalseExpr()->getType(), 9570 CO->getFalseExpr()); 9571 9572 if (TrueTy == FalseTy) 9573 return std::make_pair(TrueTy, TrueName); 9574 else if (TrueTy.isNull()) 9575 return std::make_pair(FalseTy, FalseName); 9576 else if (FalseTy.isNull()) 9577 return std::make_pair(TrueTy, TrueName); 9578 } 9579 9580 return std::make_pair(QualType(), StringRef()); 9581 } 9582 9583 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 9584 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 9585 /// type do not count. 9586 static bool 9587 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 9588 QualType From = ICE->getSubExpr()->getType(); 9589 QualType To = ICE->getType(); 9590 // It's an integer promotion if the destination type is the promoted 9591 // source type. 9592 if (ICE->getCastKind() == CK_IntegralCast && 9593 From->isPromotableIntegerType() && 9594 S.Context.getPromotedIntegerType(From) == To) 9595 return true; 9596 // Look through vector types, since we do default argument promotion for 9597 // those in OpenCL. 9598 if (const auto *VecTy = From->getAs<ExtVectorType>()) 9599 From = VecTy->getElementType(); 9600 if (const auto *VecTy = To->getAs<ExtVectorType>()) 9601 To = VecTy->getElementType(); 9602 // It's a floating promotion if the source type is a lower rank. 9603 return ICE->getCastKind() == CK_FloatingCast && 9604 S.Context.getFloatingTypeOrder(From, To) < 0; 9605 } 9606 9607 bool 9608 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9609 const char *StartSpecifier, 9610 unsigned SpecifierLen, 9611 const Expr *E) { 9612 using namespace analyze_format_string; 9613 using namespace analyze_printf; 9614 9615 // Now type check the data expression that matches the 9616 // format specifier. 9617 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 9618 if (!AT.isValid()) 9619 return true; 9620 9621 QualType ExprTy = E->getType(); 9622 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 9623 ExprTy = TET->getUnderlyingExpr()->getType(); 9624 } 9625 9626 // Diagnose attempts to print a boolean value as a character. Unlike other 9627 // -Wformat diagnostics, this is fine from a type perspective, but it still 9628 // doesn't make sense. 9629 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 9630 E->isKnownToHaveBooleanValue()) { 9631 const CharSourceRange &CSR = 9632 getSpecifierRange(StartSpecifier, SpecifierLen); 9633 SmallString<4> FSString; 9634 llvm::raw_svector_ostream os(FSString); 9635 FS.toString(os); 9636 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 9637 << FSString, 9638 E->getExprLoc(), false, CSR); 9639 return true; 9640 } 9641 9642 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 9643 if (Match == analyze_printf::ArgType::Match) 9644 return true; 9645 9646 // Look through argument promotions for our error message's reported type. 9647 // This includes the integral and floating promotions, but excludes array 9648 // and function pointer decay (seeing that an argument intended to be a 9649 // string has type 'char [6]' is probably more confusing than 'char *') and 9650 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 9651 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9652 if (isArithmeticArgumentPromotion(S, ICE)) { 9653 E = ICE->getSubExpr(); 9654 ExprTy = E->getType(); 9655 9656 // Check if we didn't match because of an implicit cast from a 'char' 9657 // or 'short' to an 'int'. This is done because printf is a varargs 9658 // function. 9659 if (ICE->getType() == S.Context.IntTy || 9660 ICE->getType() == S.Context.UnsignedIntTy) { 9661 // All further checking is done on the subexpression 9662 const analyze_printf::ArgType::MatchKind ImplicitMatch = 9663 AT.matchesType(S.Context, ExprTy); 9664 if (ImplicitMatch == analyze_printf::ArgType::Match) 9665 return true; 9666 if (ImplicitMatch == ArgType::NoMatchPedantic || 9667 ImplicitMatch == ArgType::NoMatchTypeConfusion) 9668 Match = ImplicitMatch; 9669 } 9670 } 9671 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 9672 // Special case for 'a', which has type 'int' in C. 9673 // Note, however, that we do /not/ want to treat multibyte constants like 9674 // 'MooV' as characters! This form is deprecated but still exists. In 9675 // addition, don't treat expressions as of type 'char' if one byte length 9676 // modifier is provided. 9677 if (ExprTy == S.Context.IntTy && 9678 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 9679 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 9680 ExprTy = S.Context.CharTy; 9681 } 9682 9683 // Look through enums to their underlying type. 9684 bool IsEnum = false; 9685 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 9686 ExprTy = EnumTy->getDecl()->getIntegerType(); 9687 IsEnum = true; 9688 } 9689 9690 // %C in an Objective-C context prints a unichar, not a wchar_t. 9691 // If the argument is an integer of some kind, believe the %C and suggest 9692 // a cast instead of changing the conversion specifier. 9693 QualType IntendedTy = ExprTy; 9694 if (isObjCContext() && 9695 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 9696 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 9697 !ExprTy->isCharType()) { 9698 // 'unichar' is defined as a typedef of unsigned short, but we should 9699 // prefer using the typedef if it is visible. 9700 IntendedTy = S.Context.UnsignedShortTy; 9701 9702 // While we are here, check if the value is an IntegerLiteral that happens 9703 // to be within the valid range. 9704 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 9705 const llvm::APInt &V = IL->getValue(); 9706 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 9707 return true; 9708 } 9709 9710 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 9711 Sema::LookupOrdinaryName); 9712 if (S.LookupName(Result, S.getCurScope())) { 9713 NamedDecl *ND = Result.getFoundDecl(); 9714 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 9715 if (TD->getUnderlyingType() == IntendedTy) 9716 IntendedTy = S.Context.getTypedefType(TD); 9717 } 9718 } 9719 } 9720 9721 // Special-case some of Darwin's platform-independence types by suggesting 9722 // casts to primitive types that are known to be large enough. 9723 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 9724 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 9725 QualType CastTy; 9726 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 9727 if (!CastTy.isNull()) { 9728 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 9729 // (long in ASTContext). Only complain to pedants. 9730 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 9731 (AT.isSizeT() || AT.isPtrdiffT()) && 9732 AT.matchesType(S.Context, CastTy)) 9733 Match = ArgType::NoMatchPedantic; 9734 IntendedTy = CastTy; 9735 ShouldNotPrintDirectly = true; 9736 } 9737 } 9738 9739 // We may be able to offer a FixItHint if it is a supported type. 9740 PrintfSpecifier fixedFS = FS; 9741 bool Success = 9742 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 9743 9744 if (Success) { 9745 // Get the fix string from the fixed format specifier 9746 SmallString<16> buf; 9747 llvm::raw_svector_ostream os(buf); 9748 fixedFS.toString(os); 9749 9750 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 9751 9752 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 9753 unsigned Diag; 9754 switch (Match) { 9755 case ArgType::Match: llvm_unreachable("expected non-matching"); 9756 case ArgType::NoMatchPedantic: 9757 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9758 break; 9759 case ArgType::NoMatchTypeConfusion: 9760 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9761 break; 9762 case ArgType::NoMatch: 9763 Diag = diag::warn_format_conversion_argument_type_mismatch; 9764 break; 9765 } 9766 9767 // In this case, the specifier is wrong and should be changed to match 9768 // the argument. 9769 EmitFormatDiagnostic(S.PDiag(Diag) 9770 << AT.getRepresentativeTypeName(S.Context) 9771 << IntendedTy << IsEnum << E->getSourceRange(), 9772 E->getBeginLoc(), 9773 /*IsStringLocation*/ false, SpecRange, 9774 FixItHint::CreateReplacement(SpecRange, os.str())); 9775 } else { 9776 // The canonical type for formatting this value is different from the 9777 // actual type of the expression. (This occurs, for example, with Darwin's 9778 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 9779 // should be printed as 'long' for 64-bit compatibility.) 9780 // Rather than emitting a normal format/argument mismatch, we want to 9781 // add a cast to the recommended type (and correct the format string 9782 // if necessary). 9783 SmallString<16> CastBuf; 9784 llvm::raw_svector_ostream CastFix(CastBuf); 9785 CastFix << "("; 9786 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 9787 CastFix << ")"; 9788 9789 SmallVector<FixItHint,4> Hints; 9790 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 9791 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 9792 9793 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 9794 // If there's already a cast present, just replace it. 9795 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 9796 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 9797 9798 } else if (!requiresParensToAddCast(E)) { 9799 // If the expression has high enough precedence, 9800 // just write the C-style cast. 9801 Hints.push_back( 9802 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9803 } else { 9804 // Otherwise, add parens around the expression as well as the cast. 9805 CastFix << "("; 9806 Hints.push_back( 9807 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9808 9809 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 9810 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 9811 } 9812 9813 if (ShouldNotPrintDirectly) { 9814 // The expression has a type that should not be printed directly. 9815 // We extract the name from the typedef because we don't want to show 9816 // the underlying type in the diagnostic. 9817 StringRef Name; 9818 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 9819 Name = TypedefTy->getDecl()->getName(); 9820 else 9821 Name = CastTyName; 9822 unsigned Diag = Match == ArgType::NoMatchPedantic 9823 ? diag::warn_format_argument_needs_cast_pedantic 9824 : diag::warn_format_argument_needs_cast; 9825 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 9826 << E->getSourceRange(), 9827 E->getBeginLoc(), /*IsStringLocation=*/false, 9828 SpecRange, Hints); 9829 } else { 9830 // In this case, the expression could be printed using a different 9831 // specifier, but we've decided that the specifier is probably correct 9832 // and we should cast instead. Just use the normal warning message. 9833 EmitFormatDiagnostic( 9834 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9835 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9836 << E->getSourceRange(), 9837 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9838 } 9839 } 9840 } else { 9841 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9842 SpecifierLen); 9843 // Since the warning for passing non-POD types to variadic functions 9844 // was deferred until now, we emit a warning for non-POD 9845 // arguments here. 9846 switch (S.isValidVarArgType(ExprTy)) { 9847 case Sema::VAK_Valid: 9848 case Sema::VAK_ValidInCXX11: { 9849 unsigned Diag; 9850 switch (Match) { 9851 case ArgType::Match: llvm_unreachable("expected non-matching"); 9852 case ArgType::NoMatchPedantic: 9853 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9854 break; 9855 case ArgType::NoMatchTypeConfusion: 9856 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9857 break; 9858 case ArgType::NoMatch: 9859 Diag = diag::warn_format_conversion_argument_type_mismatch; 9860 break; 9861 } 9862 9863 EmitFormatDiagnostic( 9864 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9865 << IsEnum << CSR << E->getSourceRange(), 9866 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9867 break; 9868 } 9869 case Sema::VAK_Undefined: 9870 case Sema::VAK_MSVCUndefined: 9871 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9872 << S.getLangOpts().CPlusPlus11 << ExprTy 9873 << CallType 9874 << AT.getRepresentativeTypeName(S.Context) << CSR 9875 << E->getSourceRange(), 9876 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9877 checkForCStrMembers(AT, E); 9878 break; 9879 9880 case Sema::VAK_Invalid: 9881 if (ExprTy->isObjCObjectType()) 9882 EmitFormatDiagnostic( 9883 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9884 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9885 << AT.getRepresentativeTypeName(S.Context) << CSR 9886 << E->getSourceRange(), 9887 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9888 else 9889 // FIXME: If this is an initializer list, suggest removing the braces 9890 // or inserting a cast to the target type. 9891 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9892 << isa<InitListExpr>(E) << ExprTy << CallType 9893 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9894 break; 9895 } 9896 9897 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9898 "format string specifier index out of range"); 9899 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9900 } 9901 9902 return true; 9903 } 9904 9905 //===--- CHECK: Scanf format string checking ------------------------------===// 9906 9907 namespace { 9908 9909 class CheckScanfHandler : public CheckFormatHandler { 9910 public: 9911 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9912 const Expr *origFormatExpr, Sema::FormatStringType type, 9913 unsigned firstDataArg, unsigned numDataArgs, 9914 const char *beg, bool hasVAListArg, 9915 ArrayRef<const Expr *> Args, unsigned formatIdx, 9916 bool inFunctionCall, Sema::VariadicCallType CallType, 9917 llvm::SmallBitVector &CheckedVarArgs, 9918 UncoveredArgHandler &UncoveredArg) 9919 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9920 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9921 inFunctionCall, CallType, CheckedVarArgs, 9922 UncoveredArg) {} 9923 9924 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9925 const char *startSpecifier, 9926 unsigned specifierLen) override; 9927 9928 bool HandleInvalidScanfConversionSpecifier( 9929 const analyze_scanf::ScanfSpecifier &FS, 9930 const char *startSpecifier, 9931 unsigned specifierLen) override; 9932 9933 void HandleIncompleteScanList(const char *start, const char *end) override; 9934 }; 9935 9936 } // namespace 9937 9938 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9939 const char *end) { 9940 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9941 getLocationOfByte(end), /*IsStringLocation*/true, 9942 getSpecifierRange(start, end - start)); 9943 } 9944 9945 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9946 const analyze_scanf::ScanfSpecifier &FS, 9947 const char *startSpecifier, 9948 unsigned specifierLen) { 9949 const analyze_scanf::ScanfConversionSpecifier &CS = 9950 FS.getConversionSpecifier(); 9951 9952 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9953 getLocationOfByte(CS.getStart()), 9954 startSpecifier, specifierLen, 9955 CS.getStart(), CS.getLength()); 9956 } 9957 9958 bool CheckScanfHandler::HandleScanfSpecifier( 9959 const analyze_scanf::ScanfSpecifier &FS, 9960 const char *startSpecifier, 9961 unsigned specifierLen) { 9962 using namespace analyze_scanf; 9963 using namespace analyze_format_string; 9964 9965 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9966 9967 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9968 // be used to decide if we are using positional arguments consistently. 9969 if (FS.consumesDataArgument()) { 9970 if (atFirstArg) { 9971 atFirstArg = false; 9972 usesPositionalArgs = FS.usesPositionalArg(); 9973 } 9974 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9975 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9976 startSpecifier, specifierLen); 9977 return false; 9978 } 9979 } 9980 9981 // Check if the field with is non-zero. 9982 const OptionalAmount &Amt = FS.getFieldWidth(); 9983 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9984 if (Amt.getConstantAmount() == 0) { 9985 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9986 Amt.getConstantLength()); 9987 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9988 getLocationOfByte(Amt.getStart()), 9989 /*IsStringLocation*/true, R, 9990 FixItHint::CreateRemoval(R)); 9991 } 9992 } 9993 9994 if (!FS.consumesDataArgument()) { 9995 // FIXME: Technically specifying a precision or field width here 9996 // makes no sense. Worth issuing a warning at some point. 9997 return true; 9998 } 9999 10000 // Consume the argument. 10001 unsigned argIndex = FS.getArgIndex(); 10002 if (argIndex < NumDataArgs) { 10003 // The check to see if the argIndex is valid will come later. 10004 // We set the bit here because we may exit early from this 10005 // function if we encounter some other error. 10006 CoveredArgs.set(argIndex); 10007 } 10008 10009 // Check the length modifier is valid with the given conversion specifier. 10010 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 10011 S.getLangOpts())) 10012 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 10013 diag::warn_format_nonsensical_length); 10014 else if (!FS.hasStandardLengthModifier()) 10015 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 10016 else if (!FS.hasStandardLengthConversionCombination()) 10017 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 10018 diag::warn_format_non_standard_conversion_spec); 10019 10020 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 10021 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 10022 10023 // The remaining checks depend on the data arguments. 10024 if (HasVAListArg) 10025 return true; 10026 10027 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 10028 return false; 10029 10030 // Check that the argument type matches the format specifier. 10031 const Expr *Ex = getDataArg(argIndex); 10032 if (!Ex) 10033 return true; 10034 10035 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 10036 10037 if (!AT.isValid()) { 10038 return true; 10039 } 10040 10041 analyze_format_string::ArgType::MatchKind Match = 10042 AT.matchesType(S.Context, Ex->getType()); 10043 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 10044 if (Match == analyze_format_string::ArgType::Match) 10045 return true; 10046 10047 ScanfSpecifier fixedFS = FS; 10048 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 10049 S.getLangOpts(), S.Context); 10050 10051 unsigned Diag = 10052 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 10053 : diag::warn_format_conversion_argument_type_mismatch; 10054 10055 if (Success) { 10056 // Get the fix string from the fixed format specifier. 10057 SmallString<128> buf; 10058 llvm::raw_svector_ostream os(buf); 10059 fixedFS.toString(os); 10060 10061 EmitFormatDiagnostic( 10062 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 10063 << Ex->getType() << false << Ex->getSourceRange(), 10064 Ex->getBeginLoc(), 10065 /*IsStringLocation*/ false, 10066 getSpecifierRange(startSpecifier, specifierLen), 10067 FixItHint::CreateReplacement( 10068 getSpecifierRange(startSpecifier, specifierLen), os.str())); 10069 } else { 10070 EmitFormatDiagnostic(S.PDiag(Diag) 10071 << AT.getRepresentativeTypeName(S.Context) 10072 << Ex->getType() << false << Ex->getSourceRange(), 10073 Ex->getBeginLoc(), 10074 /*IsStringLocation*/ false, 10075 getSpecifierRange(startSpecifier, specifierLen)); 10076 } 10077 10078 return true; 10079 } 10080 10081 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 10082 const Expr *OrigFormatExpr, 10083 ArrayRef<const Expr *> Args, 10084 bool HasVAListArg, unsigned format_idx, 10085 unsigned firstDataArg, 10086 Sema::FormatStringType Type, 10087 bool inFunctionCall, 10088 Sema::VariadicCallType CallType, 10089 llvm::SmallBitVector &CheckedVarArgs, 10090 UncoveredArgHandler &UncoveredArg, 10091 bool IgnoreStringsWithoutSpecifiers) { 10092 // CHECK: is the format string a wide literal? 10093 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 10094 CheckFormatHandler::EmitFormatDiagnostic( 10095 S, inFunctionCall, Args[format_idx], 10096 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 10097 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 10098 return; 10099 } 10100 10101 // Str - The format string. NOTE: this is NOT null-terminated! 10102 StringRef StrRef = FExpr->getString(); 10103 const char *Str = StrRef.data(); 10104 // Account for cases where the string literal is truncated in a declaration. 10105 const ConstantArrayType *T = 10106 S.Context.getAsConstantArrayType(FExpr->getType()); 10107 assert(T && "String literal not of constant array type!"); 10108 size_t TypeSize = T->getSize().getZExtValue(); 10109 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 10110 const unsigned numDataArgs = Args.size() - firstDataArg; 10111 10112 if (IgnoreStringsWithoutSpecifiers && 10113 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 10114 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 10115 return; 10116 10117 // Emit a warning if the string literal is truncated and does not contain an 10118 // embedded null character. 10119 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) { 10120 CheckFormatHandler::EmitFormatDiagnostic( 10121 S, inFunctionCall, Args[format_idx], 10122 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 10123 FExpr->getBeginLoc(), 10124 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 10125 return; 10126 } 10127 10128 // CHECK: empty format string? 10129 if (StrLen == 0 && numDataArgs > 0) { 10130 CheckFormatHandler::EmitFormatDiagnostic( 10131 S, inFunctionCall, Args[format_idx], 10132 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 10133 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 10134 return; 10135 } 10136 10137 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 10138 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 10139 Type == Sema::FST_OSTrace) { 10140 CheckPrintfHandler H( 10141 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 10142 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 10143 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 10144 CheckedVarArgs, UncoveredArg); 10145 10146 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 10147 S.getLangOpts(), 10148 S.Context.getTargetInfo(), 10149 Type == Sema::FST_FreeBSDKPrintf)) 10150 H.DoneProcessing(); 10151 } else if (Type == Sema::FST_Scanf) { 10152 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 10153 numDataArgs, Str, HasVAListArg, Args, format_idx, 10154 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 10155 10156 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 10157 S.getLangOpts(), 10158 S.Context.getTargetInfo())) 10159 H.DoneProcessing(); 10160 } // TODO: handle other formats 10161 } 10162 10163 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 10164 // Str - The format string. NOTE: this is NOT null-terminated! 10165 StringRef StrRef = FExpr->getString(); 10166 const char *Str = StrRef.data(); 10167 // Account for cases where the string literal is truncated in a declaration. 10168 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 10169 assert(T && "String literal not of constant array type!"); 10170 size_t TypeSize = T->getSize().getZExtValue(); 10171 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 10172 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 10173 getLangOpts(), 10174 Context.getTargetInfo()); 10175 } 10176 10177 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 10178 10179 // Returns the related absolute value function that is larger, of 0 if one 10180 // does not exist. 10181 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 10182 switch (AbsFunction) { 10183 default: 10184 return 0; 10185 10186 case Builtin::BI__builtin_abs: 10187 return Builtin::BI__builtin_labs; 10188 case Builtin::BI__builtin_labs: 10189 return Builtin::BI__builtin_llabs; 10190 case Builtin::BI__builtin_llabs: 10191 return 0; 10192 10193 case Builtin::BI__builtin_fabsf: 10194 return Builtin::BI__builtin_fabs; 10195 case Builtin::BI__builtin_fabs: 10196 return Builtin::BI__builtin_fabsl; 10197 case Builtin::BI__builtin_fabsl: 10198 return 0; 10199 10200 case Builtin::BI__builtin_cabsf: 10201 return Builtin::BI__builtin_cabs; 10202 case Builtin::BI__builtin_cabs: 10203 return Builtin::BI__builtin_cabsl; 10204 case Builtin::BI__builtin_cabsl: 10205 return 0; 10206 10207 case Builtin::BIabs: 10208 return Builtin::BIlabs; 10209 case Builtin::BIlabs: 10210 return Builtin::BIllabs; 10211 case Builtin::BIllabs: 10212 return 0; 10213 10214 case Builtin::BIfabsf: 10215 return Builtin::BIfabs; 10216 case Builtin::BIfabs: 10217 return Builtin::BIfabsl; 10218 case Builtin::BIfabsl: 10219 return 0; 10220 10221 case Builtin::BIcabsf: 10222 return Builtin::BIcabs; 10223 case Builtin::BIcabs: 10224 return Builtin::BIcabsl; 10225 case Builtin::BIcabsl: 10226 return 0; 10227 } 10228 } 10229 10230 // Returns the argument type of the absolute value function. 10231 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 10232 unsigned AbsType) { 10233 if (AbsType == 0) 10234 return QualType(); 10235 10236 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 10237 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 10238 if (Error != ASTContext::GE_None) 10239 return QualType(); 10240 10241 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 10242 if (!FT) 10243 return QualType(); 10244 10245 if (FT->getNumParams() != 1) 10246 return QualType(); 10247 10248 return FT->getParamType(0); 10249 } 10250 10251 // Returns the best absolute value function, or zero, based on type and 10252 // current absolute value function. 10253 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 10254 unsigned AbsFunctionKind) { 10255 unsigned BestKind = 0; 10256 uint64_t ArgSize = Context.getTypeSize(ArgType); 10257 for (unsigned Kind = AbsFunctionKind; Kind != 0; 10258 Kind = getLargerAbsoluteValueFunction(Kind)) { 10259 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 10260 if (Context.getTypeSize(ParamType) >= ArgSize) { 10261 if (BestKind == 0) 10262 BestKind = Kind; 10263 else if (Context.hasSameType(ParamType, ArgType)) { 10264 BestKind = Kind; 10265 break; 10266 } 10267 } 10268 } 10269 return BestKind; 10270 } 10271 10272 enum AbsoluteValueKind { 10273 AVK_Integer, 10274 AVK_Floating, 10275 AVK_Complex 10276 }; 10277 10278 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 10279 if (T->isIntegralOrEnumerationType()) 10280 return AVK_Integer; 10281 if (T->isRealFloatingType()) 10282 return AVK_Floating; 10283 if (T->isAnyComplexType()) 10284 return AVK_Complex; 10285 10286 llvm_unreachable("Type not integer, floating, or complex"); 10287 } 10288 10289 // Changes the absolute value function to a different type. Preserves whether 10290 // the function is a builtin. 10291 static unsigned changeAbsFunction(unsigned AbsKind, 10292 AbsoluteValueKind ValueKind) { 10293 switch (ValueKind) { 10294 case AVK_Integer: 10295 switch (AbsKind) { 10296 default: 10297 return 0; 10298 case Builtin::BI__builtin_fabsf: 10299 case Builtin::BI__builtin_fabs: 10300 case Builtin::BI__builtin_fabsl: 10301 case Builtin::BI__builtin_cabsf: 10302 case Builtin::BI__builtin_cabs: 10303 case Builtin::BI__builtin_cabsl: 10304 return Builtin::BI__builtin_abs; 10305 case Builtin::BIfabsf: 10306 case Builtin::BIfabs: 10307 case Builtin::BIfabsl: 10308 case Builtin::BIcabsf: 10309 case Builtin::BIcabs: 10310 case Builtin::BIcabsl: 10311 return Builtin::BIabs; 10312 } 10313 case AVK_Floating: 10314 switch (AbsKind) { 10315 default: 10316 return 0; 10317 case Builtin::BI__builtin_abs: 10318 case Builtin::BI__builtin_labs: 10319 case Builtin::BI__builtin_llabs: 10320 case Builtin::BI__builtin_cabsf: 10321 case Builtin::BI__builtin_cabs: 10322 case Builtin::BI__builtin_cabsl: 10323 return Builtin::BI__builtin_fabsf; 10324 case Builtin::BIabs: 10325 case Builtin::BIlabs: 10326 case Builtin::BIllabs: 10327 case Builtin::BIcabsf: 10328 case Builtin::BIcabs: 10329 case Builtin::BIcabsl: 10330 return Builtin::BIfabsf; 10331 } 10332 case AVK_Complex: 10333 switch (AbsKind) { 10334 default: 10335 return 0; 10336 case Builtin::BI__builtin_abs: 10337 case Builtin::BI__builtin_labs: 10338 case Builtin::BI__builtin_llabs: 10339 case Builtin::BI__builtin_fabsf: 10340 case Builtin::BI__builtin_fabs: 10341 case Builtin::BI__builtin_fabsl: 10342 return Builtin::BI__builtin_cabsf; 10343 case Builtin::BIabs: 10344 case Builtin::BIlabs: 10345 case Builtin::BIllabs: 10346 case Builtin::BIfabsf: 10347 case Builtin::BIfabs: 10348 case Builtin::BIfabsl: 10349 return Builtin::BIcabsf; 10350 } 10351 } 10352 llvm_unreachable("Unable to convert function"); 10353 } 10354 10355 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 10356 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 10357 if (!FnInfo) 10358 return 0; 10359 10360 switch (FDecl->getBuiltinID()) { 10361 default: 10362 return 0; 10363 case Builtin::BI__builtin_abs: 10364 case Builtin::BI__builtin_fabs: 10365 case Builtin::BI__builtin_fabsf: 10366 case Builtin::BI__builtin_fabsl: 10367 case Builtin::BI__builtin_labs: 10368 case Builtin::BI__builtin_llabs: 10369 case Builtin::BI__builtin_cabs: 10370 case Builtin::BI__builtin_cabsf: 10371 case Builtin::BI__builtin_cabsl: 10372 case Builtin::BIabs: 10373 case Builtin::BIlabs: 10374 case Builtin::BIllabs: 10375 case Builtin::BIfabs: 10376 case Builtin::BIfabsf: 10377 case Builtin::BIfabsl: 10378 case Builtin::BIcabs: 10379 case Builtin::BIcabsf: 10380 case Builtin::BIcabsl: 10381 return FDecl->getBuiltinID(); 10382 } 10383 llvm_unreachable("Unknown Builtin type"); 10384 } 10385 10386 // If the replacement is valid, emit a note with replacement function. 10387 // Additionally, suggest including the proper header if not already included. 10388 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 10389 unsigned AbsKind, QualType ArgType) { 10390 bool EmitHeaderHint = true; 10391 const char *HeaderName = nullptr; 10392 const char *FunctionName = nullptr; 10393 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 10394 FunctionName = "std::abs"; 10395 if (ArgType->isIntegralOrEnumerationType()) { 10396 HeaderName = "cstdlib"; 10397 } else if (ArgType->isRealFloatingType()) { 10398 HeaderName = "cmath"; 10399 } else { 10400 llvm_unreachable("Invalid Type"); 10401 } 10402 10403 // Lookup all std::abs 10404 if (NamespaceDecl *Std = S.getStdNamespace()) { 10405 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 10406 R.suppressDiagnostics(); 10407 S.LookupQualifiedName(R, Std); 10408 10409 for (const auto *I : R) { 10410 const FunctionDecl *FDecl = nullptr; 10411 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 10412 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 10413 } else { 10414 FDecl = dyn_cast<FunctionDecl>(I); 10415 } 10416 if (!FDecl) 10417 continue; 10418 10419 // Found std::abs(), check that they are the right ones. 10420 if (FDecl->getNumParams() != 1) 10421 continue; 10422 10423 // Check that the parameter type can handle the argument. 10424 QualType ParamType = FDecl->getParamDecl(0)->getType(); 10425 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 10426 S.Context.getTypeSize(ArgType) <= 10427 S.Context.getTypeSize(ParamType)) { 10428 // Found a function, don't need the header hint. 10429 EmitHeaderHint = false; 10430 break; 10431 } 10432 } 10433 } 10434 } else { 10435 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 10436 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 10437 10438 if (HeaderName) { 10439 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 10440 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 10441 R.suppressDiagnostics(); 10442 S.LookupName(R, S.getCurScope()); 10443 10444 if (R.isSingleResult()) { 10445 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 10446 if (FD && FD->getBuiltinID() == AbsKind) { 10447 EmitHeaderHint = false; 10448 } else { 10449 return; 10450 } 10451 } else if (!R.empty()) { 10452 return; 10453 } 10454 } 10455 } 10456 10457 S.Diag(Loc, diag::note_replace_abs_function) 10458 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 10459 10460 if (!HeaderName) 10461 return; 10462 10463 if (!EmitHeaderHint) 10464 return; 10465 10466 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 10467 << FunctionName; 10468 } 10469 10470 template <std::size_t StrLen> 10471 static bool IsStdFunction(const FunctionDecl *FDecl, 10472 const char (&Str)[StrLen]) { 10473 if (!FDecl) 10474 return false; 10475 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 10476 return false; 10477 if (!FDecl->isInStdNamespace()) 10478 return false; 10479 10480 return true; 10481 } 10482 10483 // Warn when using the wrong abs() function. 10484 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 10485 const FunctionDecl *FDecl) { 10486 if (Call->getNumArgs() != 1) 10487 return; 10488 10489 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 10490 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 10491 if (AbsKind == 0 && !IsStdAbs) 10492 return; 10493 10494 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10495 QualType ParamType = Call->getArg(0)->getType(); 10496 10497 // Unsigned types cannot be negative. Suggest removing the absolute value 10498 // function call. 10499 if (ArgType->isUnsignedIntegerType()) { 10500 const char *FunctionName = 10501 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 10502 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 10503 Diag(Call->getExprLoc(), diag::note_remove_abs) 10504 << FunctionName 10505 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 10506 return; 10507 } 10508 10509 // Taking the absolute value of a pointer is very suspicious, they probably 10510 // wanted to index into an array, dereference a pointer, call a function, etc. 10511 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 10512 unsigned DiagType = 0; 10513 if (ArgType->isFunctionType()) 10514 DiagType = 1; 10515 else if (ArgType->isArrayType()) 10516 DiagType = 2; 10517 10518 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 10519 return; 10520 } 10521 10522 // std::abs has overloads which prevent most of the absolute value problems 10523 // from occurring. 10524 if (IsStdAbs) 10525 return; 10526 10527 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 10528 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 10529 10530 // The argument and parameter are the same kind. Check if they are the right 10531 // size. 10532 if (ArgValueKind == ParamValueKind) { 10533 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 10534 return; 10535 10536 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 10537 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 10538 << FDecl << ArgType << ParamType; 10539 10540 if (NewAbsKind == 0) 10541 return; 10542 10543 emitReplacement(*this, Call->getExprLoc(), 10544 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10545 return; 10546 } 10547 10548 // ArgValueKind != ParamValueKind 10549 // The wrong type of absolute value function was used. Attempt to find the 10550 // proper one. 10551 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 10552 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 10553 if (NewAbsKind == 0) 10554 return; 10555 10556 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 10557 << FDecl << ParamValueKind << ArgValueKind; 10558 10559 emitReplacement(*this, Call->getExprLoc(), 10560 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10561 } 10562 10563 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 10564 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 10565 const FunctionDecl *FDecl) { 10566 if (!Call || !FDecl) return; 10567 10568 // Ignore template specializations and macros. 10569 if (inTemplateInstantiation()) return; 10570 if (Call->getExprLoc().isMacroID()) return; 10571 10572 // Only care about the one template argument, two function parameter std::max 10573 if (Call->getNumArgs() != 2) return; 10574 if (!IsStdFunction(FDecl, "max")) return; 10575 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 10576 if (!ArgList) return; 10577 if (ArgList->size() != 1) return; 10578 10579 // Check that template type argument is unsigned integer. 10580 const auto& TA = ArgList->get(0); 10581 if (TA.getKind() != TemplateArgument::Type) return; 10582 QualType ArgType = TA.getAsType(); 10583 if (!ArgType->isUnsignedIntegerType()) return; 10584 10585 // See if either argument is a literal zero. 10586 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 10587 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 10588 if (!MTE) return false; 10589 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 10590 if (!Num) return false; 10591 if (Num->getValue() != 0) return false; 10592 return true; 10593 }; 10594 10595 const Expr *FirstArg = Call->getArg(0); 10596 const Expr *SecondArg = Call->getArg(1); 10597 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 10598 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 10599 10600 // Only warn when exactly one argument is zero. 10601 if (IsFirstArgZero == IsSecondArgZero) return; 10602 10603 SourceRange FirstRange = FirstArg->getSourceRange(); 10604 SourceRange SecondRange = SecondArg->getSourceRange(); 10605 10606 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 10607 10608 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 10609 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 10610 10611 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 10612 SourceRange RemovalRange; 10613 if (IsFirstArgZero) { 10614 RemovalRange = SourceRange(FirstRange.getBegin(), 10615 SecondRange.getBegin().getLocWithOffset(-1)); 10616 } else { 10617 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 10618 SecondRange.getEnd()); 10619 } 10620 10621 Diag(Call->getExprLoc(), diag::note_remove_max_call) 10622 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 10623 << FixItHint::CreateRemoval(RemovalRange); 10624 } 10625 10626 //===--- CHECK: Standard memory functions ---------------------------------===// 10627 10628 /// Takes the expression passed to the size_t parameter of functions 10629 /// such as memcmp, strncat, etc and warns if it's a comparison. 10630 /// 10631 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 10632 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 10633 IdentifierInfo *FnName, 10634 SourceLocation FnLoc, 10635 SourceLocation RParenLoc) { 10636 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 10637 if (!Size) 10638 return false; 10639 10640 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 10641 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 10642 return false; 10643 10644 SourceRange SizeRange = Size->getSourceRange(); 10645 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 10646 << SizeRange << FnName; 10647 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 10648 << FnName 10649 << FixItHint::CreateInsertion( 10650 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 10651 << FixItHint::CreateRemoval(RParenLoc); 10652 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 10653 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 10654 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 10655 ")"); 10656 10657 return true; 10658 } 10659 10660 /// Determine whether the given type is or contains a dynamic class type 10661 /// (e.g., whether it has a vtable). 10662 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 10663 bool &IsContained) { 10664 // Look through array types while ignoring qualifiers. 10665 const Type *Ty = T->getBaseElementTypeUnsafe(); 10666 IsContained = false; 10667 10668 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 10669 RD = RD ? RD->getDefinition() : nullptr; 10670 if (!RD || RD->isInvalidDecl()) 10671 return nullptr; 10672 10673 if (RD->isDynamicClass()) 10674 return RD; 10675 10676 // Check all the fields. If any bases were dynamic, the class is dynamic. 10677 // It's impossible for a class to transitively contain itself by value, so 10678 // infinite recursion is impossible. 10679 for (auto *FD : RD->fields()) { 10680 bool SubContained; 10681 if (const CXXRecordDecl *ContainedRD = 10682 getContainedDynamicClass(FD->getType(), SubContained)) { 10683 IsContained = true; 10684 return ContainedRD; 10685 } 10686 } 10687 10688 return nullptr; 10689 } 10690 10691 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 10692 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 10693 if (Unary->getKind() == UETT_SizeOf) 10694 return Unary; 10695 return nullptr; 10696 } 10697 10698 /// If E is a sizeof expression, returns its argument expression, 10699 /// otherwise returns NULL. 10700 static const Expr *getSizeOfExprArg(const Expr *E) { 10701 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10702 if (!SizeOf->isArgumentType()) 10703 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 10704 return nullptr; 10705 } 10706 10707 /// If E is a sizeof expression, returns its argument type. 10708 static QualType getSizeOfArgType(const Expr *E) { 10709 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10710 return SizeOf->getTypeOfArgument(); 10711 return QualType(); 10712 } 10713 10714 namespace { 10715 10716 struct SearchNonTrivialToInitializeField 10717 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 10718 using Super = 10719 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 10720 10721 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 10722 10723 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 10724 SourceLocation SL) { 10725 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10726 asDerived().visitArray(PDIK, AT, SL); 10727 return; 10728 } 10729 10730 Super::visitWithKind(PDIK, FT, SL); 10731 } 10732 10733 void visitARCStrong(QualType FT, SourceLocation SL) { 10734 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10735 } 10736 void visitARCWeak(QualType FT, SourceLocation SL) { 10737 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10738 } 10739 void visitStruct(QualType FT, SourceLocation SL) { 10740 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10741 visit(FD->getType(), FD->getLocation()); 10742 } 10743 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 10744 const ArrayType *AT, SourceLocation SL) { 10745 visit(getContext().getBaseElementType(AT), SL); 10746 } 10747 void visitTrivial(QualType FT, SourceLocation SL) {} 10748 10749 static void diag(QualType RT, const Expr *E, Sema &S) { 10750 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 10751 } 10752 10753 ASTContext &getContext() { return S.getASTContext(); } 10754 10755 const Expr *E; 10756 Sema &S; 10757 }; 10758 10759 struct SearchNonTrivialToCopyField 10760 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 10761 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 10762 10763 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 10764 10765 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 10766 SourceLocation SL) { 10767 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10768 asDerived().visitArray(PCK, AT, SL); 10769 return; 10770 } 10771 10772 Super::visitWithKind(PCK, FT, SL); 10773 } 10774 10775 void visitARCStrong(QualType FT, SourceLocation SL) { 10776 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10777 } 10778 void visitARCWeak(QualType FT, SourceLocation SL) { 10779 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10780 } 10781 void visitStruct(QualType FT, SourceLocation SL) { 10782 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10783 visit(FD->getType(), FD->getLocation()); 10784 } 10785 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 10786 SourceLocation SL) { 10787 visit(getContext().getBaseElementType(AT), SL); 10788 } 10789 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 10790 SourceLocation SL) {} 10791 void visitTrivial(QualType FT, SourceLocation SL) {} 10792 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 10793 10794 static void diag(QualType RT, const Expr *E, Sema &S) { 10795 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 10796 } 10797 10798 ASTContext &getContext() { return S.getASTContext(); } 10799 10800 const Expr *E; 10801 Sema &S; 10802 }; 10803 10804 } 10805 10806 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 10807 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 10808 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 10809 10810 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 10811 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 10812 return false; 10813 10814 return doesExprLikelyComputeSize(BO->getLHS()) || 10815 doesExprLikelyComputeSize(BO->getRHS()); 10816 } 10817 10818 return getAsSizeOfExpr(SizeofExpr) != nullptr; 10819 } 10820 10821 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 10822 /// 10823 /// \code 10824 /// #define MACRO 0 10825 /// foo(MACRO); 10826 /// foo(0); 10827 /// \endcode 10828 /// 10829 /// This should return true for the first call to foo, but not for the second 10830 /// (regardless of whether foo is a macro or function). 10831 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10832 SourceLocation CallLoc, 10833 SourceLocation ArgLoc) { 10834 if (!CallLoc.isMacroID()) 10835 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10836 10837 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10838 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10839 } 10840 10841 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10842 /// last two arguments transposed. 10843 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10844 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10845 return; 10846 10847 const Expr *SizeArg = 10848 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10849 10850 auto isLiteralZero = [](const Expr *E) { 10851 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10852 }; 10853 10854 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10855 SourceLocation CallLoc = Call->getRParenLoc(); 10856 SourceManager &SM = S.getSourceManager(); 10857 if (isLiteralZero(SizeArg) && 10858 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10859 10860 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10861 10862 // Some platforms #define bzero to __builtin_memset. See if this is the 10863 // case, and if so, emit a better diagnostic. 10864 if (BId == Builtin::BIbzero || 10865 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10866 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10867 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10868 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10869 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10870 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10871 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10872 } 10873 return; 10874 } 10875 10876 // If the second argument to a memset is a sizeof expression and the third 10877 // isn't, this is also likely an error. This should catch 10878 // 'memset(buf, sizeof(buf), 0xff)'. 10879 if (BId == Builtin::BImemset && 10880 doesExprLikelyComputeSize(Call->getArg(1)) && 10881 !doesExprLikelyComputeSize(Call->getArg(2))) { 10882 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10883 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10884 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10885 return; 10886 } 10887 } 10888 10889 /// Check for dangerous or invalid arguments to memset(). 10890 /// 10891 /// This issues warnings on known problematic, dangerous or unspecified 10892 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10893 /// function calls. 10894 /// 10895 /// \param Call The call expression to diagnose. 10896 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10897 unsigned BId, 10898 IdentifierInfo *FnName) { 10899 assert(BId != 0); 10900 10901 // It is possible to have a non-standard definition of memset. Validate 10902 // we have enough arguments, and if not, abort further checking. 10903 unsigned ExpectedNumArgs = 10904 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10905 if (Call->getNumArgs() < ExpectedNumArgs) 10906 return; 10907 10908 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10909 BId == Builtin::BIstrndup ? 1 : 2); 10910 unsigned LenArg = 10911 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10912 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10913 10914 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10915 Call->getBeginLoc(), Call->getRParenLoc())) 10916 return; 10917 10918 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10919 CheckMemaccessSize(*this, BId, Call); 10920 10921 // We have special checking when the length is a sizeof expression. 10922 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10923 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10924 llvm::FoldingSetNodeID SizeOfArgID; 10925 10926 // Although widely used, 'bzero' is not a standard function. Be more strict 10927 // with the argument types before allowing diagnostics and only allow the 10928 // form bzero(ptr, sizeof(...)). 10929 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10930 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10931 return; 10932 10933 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10934 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10935 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10936 10937 QualType DestTy = Dest->getType(); 10938 QualType PointeeTy; 10939 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10940 PointeeTy = DestPtrTy->getPointeeType(); 10941 10942 // Never warn about void type pointers. This can be used to suppress 10943 // false positives. 10944 if (PointeeTy->isVoidType()) 10945 continue; 10946 10947 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10948 // actually comparing the expressions for equality. Because computing the 10949 // expression IDs can be expensive, we only do this if the diagnostic is 10950 // enabled. 10951 if (SizeOfArg && 10952 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10953 SizeOfArg->getExprLoc())) { 10954 // We only compute IDs for expressions if the warning is enabled, and 10955 // cache the sizeof arg's ID. 10956 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10957 SizeOfArg->Profile(SizeOfArgID, Context, true); 10958 llvm::FoldingSetNodeID DestID; 10959 Dest->Profile(DestID, Context, true); 10960 if (DestID == SizeOfArgID) { 10961 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10962 // over sizeof(src) as well. 10963 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10964 StringRef ReadableName = FnName->getName(); 10965 10966 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10967 if (UnaryOp->getOpcode() == UO_AddrOf) 10968 ActionIdx = 1; // If its an address-of operator, just remove it. 10969 if (!PointeeTy->isIncompleteType() && 10970 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10971 ActionIdx = 2; // If the pointee's size is sizeof(char), 10972 // suggest an explicit length. 10973 10974 // If the function is defined as a builtin macro, do not show macro 10975 // expansion. 10976 SourceLocation SL = SizeOfArg->getExprLoc(); 10977 SourceRange DSR = Dest->getSourceRange(); 10978 SourceRange SSR = SizeOfArg->getSourceRange(); 10979 SourceManager &SM = getSourceManager(); 10980 10981 if (SM.isMacroArgExpansion(SL)) { 10982 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10983 SL = SM.getSpellingLoc(SL); 10984 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10985 SM.getSpellingLoc(DSR.getEnd())); 10986 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10987 SM.getSpellingLoc(SSR.getEnd())); 10988 } 10989 10990 DiagRuntimeBehavior(SL, SizeOfArg, 10991 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10992 << ReadableName 10993 << PointeeTy 10994 << DestTy 10995 << DSR 10996 << SSR); 10997 DiagRuntimeBehavior(SL, SizeOfArg, 10998 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10999 << ActionIdx 11000 << SSR); 11001 11002 break; 11003 } 11004 } 11005 11006 // Also check for cases where the sizeof argument is the exact same 11007 // type as the memory argument, and where it points to a user-defined 11008 // record type. 11009 if (SizeOfArgTy != QualType()) { 11010 if (PointeeTy->isRecordType() && 11011 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 11012 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 11013 PDiag(diag::warn_sizeof_pointer_type_memaccess) 11014 << FnName << SizeOfArgTy << ArgIdx 11015 << PointeeTy << Dest->getSourceRange() 11016 << LenExpr->getSourceRange()); 11017 break; 11018 } 11019 } 11020 } else if (DestTy->isArrayType()) { 11021 PointeeTy = DestTy; 11022 } 11023 11024 if (PointeeTy == QualType()) 11025 continue; 11026 11027 // Always complain about dynamic classes. 11028 bool IsContained; 11029 if (const CXXRecordDecl *ContainedRD = 11030 getContainedDynamicClass(PointeeTy, IsContained)) { 11031 11032 unsigned OperationType = 0; 11033 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 11034 // "overwritten" if we're warning about the destination for any call 11035 // but memcmp; otherwise a verb appropriate to the call. 11036 if (ArgIdx != 0 || IsCmp) { 11037 if (BId == Builtin::BImemcpy) 11038 OperationType = 1; 11039 else if(BId == Builtin::BImemmove) 11040 OperationType = 2; 11041 else if (IsCmp) 11042 OperationType = 3; 11043 } 11044 11045 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 11046 PDiag(diag::warn_dyn_class_memaccess) 11047 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 11048 << IsContained << ContainedRD << OperationType 11049 << Call->getCallee()->getSourceRange()); 11050 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 11051 BId != Builtin::BImemset) 11052 DiagRuntimeBehavior( 11053 Dest->getExprLoc(), Dest, 11054 PDiag(diag::warn_arc_object_memaccess) 11055 << ArgIdx << FnName << PointeeTy 11056 << Call->getCallee()->getSourceRange()); 11057 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 11058 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 11059 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 11060 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 11061 PDiag(diag::warn_cstruct_memaccess) 11062 << ArgIdx << FnName << PointeeTy << 0); 11063 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 11064 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 11065 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 11066 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 11067 PDiag(diag::warn_cstruct_memaccess) 11068 << ArgIdx << FnName << PointeeTy << 1); 11069 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 11070 } else { 11071 continue; 11072 } 11073 } else 11074 continue; 11075 11076 DiagRuntimeBehavior( 11077 Dest->getExprLoc(), Dest, 11078 PDiag(diag::note_bad_memaccess_silence) 11079 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 11080 break; 11081 } 11082 } 11083 11084 // A little helper routine: ignore addition and subtraction of integer literals. 11085 // This intentionally does not ignore all integer constant expressions because 11086 // we don't want to remove sizeof(). 11087 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 11088 Ex = Ex->IgnoreParenCasts(); 11089 11090 while (true) { 11091 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 11092 if (!BO || !BO->isAdditiveOp()) 11093 break; 11094 11095 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 11096 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 11097 11098 if (isa<IntegerLiteral>(RHS)) 11099 Ex = LHS; 11100 else if (isa<IntegerLiteral>(LHS)) 11101 Ex = RHS; 11102 else 11103 break; 11104 } 11105 11106 return Ex; 11107 } 11108 11109 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 11110 ASTContext &Context) { 11111 // Only handle constant-sized or VLAs, but not flexible members. 11112 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 11113 // Only issue the FIXIT for arrays of size > 1. 11114 if (CAT->getSize().getSExtValue() <= 1) 11115 return false; 11116 } else if (!Ty->isVariableArrayType()) { 11117 return false; 11118 } 11119 return true; 11120 } 11121 11122 // Warn if the user has made the 'size' argument to strlcpy or strlcat 11123 // be the size of the source, instead of the destination. 11124 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 11125 IdentifierInfo *FnName) { 11126 11127 // Don't crash if the user has the wrong number of arguments 11128 unsigned NumArgs = Call->getNumArgs(); 11129 if ((NumArgs != 3) && (NumArgs != 4)) 11130 return; 11131 11132 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 11133 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 11134 const Expr *CompareWithSrc = nullptr; 11135 11136 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 11137 Call->getBeginLoc(), Call->getRParenLoc())) 11138 return; 11139 11140 // Look for 'strlcpy(dst, x, sizeof(x))' 11141 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 11142 CompareWithSrc = Ex; 11143 else { 11144 // Look for 'strlcpy(dst, x, strlen(x))' 11145 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 11146 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 11147 SizeCall->getNumArgs() == 1) 11148 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 11149 } 11150 } 11151 11152 if (!CompareWithSrc) 11153 return; 11154 11155 // Determine if the argument to sizeof/strlen is equal to the source 11156 // argument. In principle there's all kinds of things you could do 11157 // here, for instance creating an == expression and evaluating it with 11158 // EvaluateAsBooleanCondition, but this uses a more direct technique: 11159 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 11160 if (!SrcArgDRE) 11161 return; 11162 11163 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 11164 if (!CompareWithSrcDRE || 11165 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 11166 return; 11167 11168 const Expr *OriginalSizeArg = Call->getArg(2); 11169 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 11170 << OriginalSizeArg->getSourceRange() << FnName; 11171 11172 // Output a FIXIT hint if the destination is an array (rather than a 11173 // pointer to an array). This could be enhanced to handle some 11174 // pointers if we know the actual size, like if DstArg is 'array+2' 11175 // we could say 'sizeof(array)-2'. 11176 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 11177 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 11178 return; 11179 11180 SmallString<128> sizeString; 11181 llvm::raw_svector_ostream OS(sizeString); 11182 OS << "sizeof("; 11183 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11184 OS << ")"; 11185 11186 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 11187 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 11188 OS.str()); 11189 } 11190 11191 /// Check if two expressions refer to the same declaration. 11192 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 11193 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 11194 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 11195 return D1->getDecl() == D2->getDecl(); 11196 return false; 11197 } 11198 11199 static const Expr *getStrlenExprArg(const Expr *E) { 11200 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 11201 const FunctionDecl *FD = CE->getDirectCallee(); 11202 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 11203 return nullptr; 11204 return CE->getArg(0)->IgnoreParenCasts(); 11205 } 11206 return nullptr; 11207 } 11208 11209 // Warn on anti-patterns as the 'size' argument to strncat. 11210 // The correct size argument should look like following: 11211 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 11212 void Sema::CheckStrncatArguments(const CallExpr *CE, 11213 IdentifierInfo *FnName) { 11214 // Don't crash if the user has the wrong number of arguments. 11215 if (CE->getNumArgs() < 3) 11216 return; 11217 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 11218 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 11219 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 11220 11221 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 11222 CE->getRParenLoc())) 11223 return; 11224 11225 // Identify common expressions, which are wrongly used as the size argument 11226 // to strncat and may lead to buffer overflows. 11227 unsigned PatternType = 0; 11228 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 11229 // - sizeof(dst) 11230 if (referToTheSameDecl(SizeOfArg, DstArg)) 11231 PatternType = 1; 11232 // - sizeof(src) 11233 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 11234 PatternType = 2; 11235 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 11236 if (BE->getOpcode() == BO_Sub) { 11237 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 11238 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 11239 // - sizeof(dst) - strlen(dst) 11240 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 11241 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 11242 PatternType = 1; 11243 // - sizeof(src) - (anything) 11244 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 11245 PatternType = 2; 11246 } 11247 } 11248 11249 if (PatternType == 0) 11250 return; 11251 11252 // Generate the diagnostic. 11253 SourceLocation SL = LenArg->getBeginLoc(); 11254 SourceRange SR = LenArg->getSourceRange(); 11255 SourceManager &SM = getSourceManager(); 11256 11257 // If the function is defined as a builtin macro, do not show macro expansion. 11258 if (SM.isMacroArgExpansion(SL)) { 11259 SL = SM.getSpellingLoc(SL); 11260 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 11261 SM.getSpellingLoc(SR.getEnd())); 11262 } 11263 11264 // Check if the destination is an array (rather than a pointer to an array). 11265 QualType DstTy = DstArg->getType(); 11266 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 11267 Context); 11268 if (!isKnownSizeArray) { 11269 if (PatternType == 1) 11270 Diag(SL, diag::warn_strncat_wrong_size) << SR; 11271 else 11272 Diag(SL, diag::warn_strncat_src_size) << SR; 11273 return; 11274 } 11275 11276 if (PatternType == 1) 11277 Diag(SL, diag::warn_strncat_large_size) << SR; 11278 else 11279 Diag(SL, diag::warn_strncat_src_size) << SR; 11280 11281 SmallString<128> sizeString; 11282 llvm::raw_svector_ostream OS(sizeString); 11283 OS << "sizeof("; 11284 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11285 OS << ") - "; 11286 OS << "strlen("; 11287 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 11288 OS << ") - 1"; 11289 11290 Diag(SL, diag::note_strncat_wrong_size) 11291 << FixItHint::CreateReplacement(SR, OS.str()); 11292 } 11293 11294 namespace { 11295 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 11296 const UnaryOperator *UnaryExpr, const Decl *D) { 11297 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 11298 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 11299 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 11300 return; 11301 } 11302 } 11303 11304 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 11305 const UnaryOperator *UnaryExpr) { 11306 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 11307 const Decl *D = Lvalue->getDecl(); 11308 if (isa<DeclaratorDecl>(D)) 11309 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType()) 11310 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 11311 } 11312 11313 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 11314 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 11315 Lvalue->getMemberDecl()); 11316 } 11317 11318 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 11319 const UnaryOperator *UnaryExpr) { 11320 const auto *Lambda = dyn_cast<LambdaExpr>( 11321 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 11322 if (!Lambda) 11323 return; 11324 11325 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 11326 << CalleeName << 2 /*object: lambda expression*/; 11327 } 11328 11329 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 11330 const DeclRefExpr *Lvalue) { 11331 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 11332 if (Var == nullptr) 11333 return; 11334 11335 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 11336 << CalleeName << 0 /*object: */ << Var; 11337 } 11338 11339 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 11340 const CastExpr *Cast) { 11341 SmallString<128> SizeString; 11342 llvm::raw_svector_ostream OS(SizeString); 11343 11344 clang::CastKind Kind = Cast->getCastKind(); 11345 if (Kind == clang::CK_BitCast && 11346 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 11347 return; 11348 if (Kind == clang::CK_IntegralToPointer && 11349 !isa<IntegerLiteral>( 11350 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 11351 return; 11352 11353 switch (Cast->getCastKind()) { 11354 case clang::CK_BitCast: 11355 case clang::CK_IntegralToPointer: 11356 case clang::CK_FunctionToPointerDecay: 11357 OS << '\''; 11358 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 11359 OS << '\''; 11360 break; 11361 default: 11362 return; 11363 } 11364 11365 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 11366 << CalleeName << 0 /*object: */ << OS.str(); 11367 } 11368 } // namespace 11369 11370 /// Alerts the user that they are attempting to free a non-malloc'd object. 11371 void Sema::CheckFreeArguments(const CallExpr *E) { 11372 const std::string CalleeName = 11373 cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 11374 11375 { // Prefer something that doesn't involve a cast to make things simpler. 11376 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 11377 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 11378 switch (UnaryExpr->getOpcode()) { 11379 case UnaryOperator::Opcode::UO_AddrOf: 11380 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 11381 case UnaryOperator::Opcode::UO_Plus: 11382 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 11383 default: 11384 break; 11385 } 11386 11387 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 11388 if (Lvalue->getType()->isArrayType()) 11389 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 11390 11391 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 11392 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 11393 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 11394 return; 11395 } 11396 11397 if (isa<BlockExpr>(Arg)) { 11398 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 11399 << CalleeName << 1 /*object: block*/; 11400 return; 11401 } 11402 } 11403 // Maybe the cast was important, check after the other cases. 11404 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 11405 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 11406 } 11407 11408 void 11409 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 11410 SourceLocation ReturnLoc, 11411 bool isObjCMethod, 11412 const AttrVec *Attrs, 11413 const FunctionDecl *FD) { 11414 // Check if the return value is null but should not be. 11415 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 11416 (!isObjCMethod && isNonNullType(Context, lhsType))) && 11417 CheckNonNullExpr(*this, RetValExp)) 11418 Diag(ReturnLoc, diag::warn_null_ret) 11419 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 11420 11421 // C++11 [basic.stc.dynamic.allocation]p4: 11422 // If an allocation function declared with a non-throwing 11423 // exception-specification fails to allocate storage, it shall return 11424 // a null pointer. Any other allocation function that fails to allocate 11425 // storage shall indicate failure only by throwing an exception [...] 11426 if (FD) { 11427 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 11428 if (Op == OO_New || Op == OO_Array_New) { 11429 const FunctionProtoType *Proto 11430 = FD->getType()->castAs<FunctionProtoType>(); 11431 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 11432 CheckNonNullExpr(*this, RetValExp)) 11433 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 11434 << FD << getLangOpts().CPlusPlus11; 11435 } 11436 } 11437 11438 // PPC MMA non-pointer types are not allowed as return type. Checking the type 11439 // here prevent the user from using a PPC MMA type as trailing return type. 11440 if (Context.getTargetInfo().getTriple().isPPC64()) 11441 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 11442 } 11443 11444 /// Check for comparisons of floating-point values using == and !=. Issue a 11445 /// warning if the comparison is not likely to do what the programmer intended. 11446 void Sema::CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS, 11447 BinaryOperatorKind Opcode) { 11448 // Match and capture subexpressions such as "(float) X == 0.1". 11449 FloatingLiteral *FPLiteral; 11450 CastExpr *FPCast; 11451 auto getCastAndLiteral = [&FPLiteral, &FPCast](Expr *L, Expr *R) { 11452 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens()); 11453 FPCast = dyn_cast<CastExpr>(R->IgnoreParens()); 11454 return FPLiteral && FPCast; 11455 }; 11456 11457 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) { 11458 auto *SourceTy = FPCast->getSubExpr()->getType()->getAs<BuiltinType>(); 11459 auto *TargetTy = FPLiteral->getType()->getAs<BuiltinType>(); 11460 if (SourceTy && TargetTy && SourceTy->isFloatingPoint() && 11461 TargetTy->isFloatingPoint()) { 11462 bool Lossy; 11463 llvm::APFloat TargetC = FPLiteral->getValue(); 11464 TargetC.convert(Context.getFloatTypeSemantics(QualType(SourceTy, 0)), 11465 llvm::APFloat::rmNearestTiesToEven, &Lossy); 11466 if (Lossy) { 11467 // If the literal cannot be represented in the source type, then a 11468 // check for == is always false and check for != is always true. 11469 Diag(Loc, diag::warn_float_compare_literal) 11470 << (Opcode == BO_EQ) << QualType(SourceTy, 0) 11471 << LHS->getSourceRange() << RHS->getSourceRange(); 11472 return; 11473 } 11474 } 11475 } 11476 11477 // Match a more general floating-point equality comparison (-Wfloat-equal). 11478 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 11479 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 11480 11481 // Special case: check for x == x (which is OK). 11482 // Do not emit warnings for such cases. 11483 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 11484 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 11485 if (DRL->getDecl() == DRR->getDecl()) 11486 return; 11487 11488 // Special case: check for comparisons against literals that can be exactly 11489 // represented by APFloat. In such cases, do not emit a warning. This 11490 // is a heuristic: often comparison against such literals are used to 11491 // detect if a value in a variable has not changed. This clearly can 11492 // lead to false negatives. 11493 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 11494 if (FLL->isExact()) 11495 return; 11496 } else 11497 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 11498 if (FLR->isExact()) 11499 return; 11500 11501 // Check for comparisons with builtin types. 11502 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 11503 if (CL->getBuiltinCallee()) 11504 return; 11505 11506 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 11507 if (CR->getBuiltinCallee()) 11508 return; 11509 11510 // Emit the diagnostic. 11511 Diag(Loc, diag::warn_floatingpoint_eq) 11512 << LHS->getSourceRange() << RHS->getSourceRange(); 11513 } 11514 11515 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 11516 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 11517 11518 namespace { 11519 11520 /// Structure recording the 'active' range of an integer-valued 11521 /// expression. 11522 struct IntRange { 11523 /// The number of bits active in the int. Note that this includes exactly one 11524 /// sign bit if !NonNegative. 11525 unsigned Width; 11526 11527 /// True if the int is known not to have negative values. If so, all leading 11528 /// bits before Width are known zero, otherwise they are known to be the 11529 /// same as the MSB within Width. 11530 bool NonNegative; 11531 11532 IntRange(unsigned Width, bool NonNegative) 11533 : Width(Width), NonNegative(NonNegative) {} 11534 11535 /// Number of bits excluding the sign bit. 11536 unsigned valueBits() const { 11537 return NonNegative ? Width : Width - 1; 11538 } 11539 11540 /// Returns the range of the bool type. 11541 static IntRange forBoolType() { 11542 return IntRange(1, true); 11543 } 11544 11545 /// Returns the range of an opaque value of the given integral type. 11546 static IntRange forValueOfType(ASTContext &C, QualType T) { 11547 return forValueOfCanonicalType(C, 11548 T->getCanonicalTypeInternal().getTypePtr()); 11549 } 11550 11551 /// Returns the range of an opaque value of a canonical integral type. 11552 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 11553 assert(T->isCanonicalUnqualified()); 11554 11555 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11556 T = VT->getElementType().getTypePtr(); 11557 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11558 T = CT->getElementType().getTypePtr(); 11559 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11560 T = AT->getValueType().getTypePtr(); 11561 11562 if (!C.getLangOpts().CPlusPlus) { 11563 // For enum types in C code, use the underlying datatype. 11564 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11565 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 11566 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 11567 // For enum types in C++, use the known bit width of the enumerators. 11568 EnumDecl *Enum = ET->getDecl(); 11569 // In C++11, enums can have a fixed underlying type. Use this type to 11570 // compute the range. 11571 if (Enum->isFixed()) { 11572 return IntRange(C.getIntWidth(QualType(T, 0)), 11573 !ET->isSignedIntegerOrEnumerationType()); 11574 } 11575 11576 unsigned NumPositive = Enum->getNumPositiveBits(); 11577 unsigned NumNegative = Enum->getNumNegativeBits(); 11578 11579 if (NumNegative == 0) 11580 return IntRange(NumPositive, true/*NonNegative*/); 11581 else 11582 return IntRange(std::max(NumPositive + 1, NumNegative), 11583 false/*NonNegative*/); 11584 } 11585 11586 if (const auto *EIT = dyn_cast<BitIntType>(T)) 11587 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11588 11589 const BuiltinType *BT = cast<BuiltinType>(T); 11590 assert(BT->isInteger()); 11591 11592 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11593 } 11594 11595 /// Returns the "target" range of a canonical integral type, i.e. 11596 /// the range of values expressible in the type. 11597 /// 11598 /// This matches forValueOfCanonicalType except that enums have the 11599 /// full range of their type, not the range of their enumerators. 11600 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 11601 assert(T->isCanonicalUnqualified()); 11602 11603 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11604 T = VT->getElementType().getTypePtr(); 11605 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11606 T = CT->getElementType().getTypePtr(); 11607 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11608 T = AT->getValueType().getTypePtr(); 11609 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11610 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 11611 11612 if (const auto *EIT = dyn_cast<BitIntType>(T)) 11613 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11614 11615 const BuiltinType *BT = cast<BuiltinType>(T); 11616 assert(BT->isInteger()); 11617 11618 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11619 } 11620 11621 /// Returns the supremum of two ranges: i.e. their conservative merge. 11622 static IntRange join(IntRange L, IntRange R) { 11623 bool Unsigned = L.NonNegative && R.NonNegative; 11624 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 11625 L.NonNegative && R.NonNegative); 11626 } 11627 11628 /// Return the range of a bitwise-AND of the two ranges. 11629 static IntRange bit_and(IntRange L, IntRange R) { 11630 unsigned Bits = std::max(L.Width, R.Width); 11631 bool NonNegative = false; 11632 if (L.NonNegative) { 11633 Bits = std::min(Bits, L.Width); 11634 NonNegative = true; 11635 } 11636 if (R.NonNegative) { 11637 Bits = std::min(Bits, R.Width); 11638 NonNegative = true; 11639 } 11640 return IntRange(Bits, NonNegative); 11641 } 11642 11643 /// Return the range of a sum of the two ranges. 11644 static IntRange sum(IntRange L, IntRange R) { 11645 bool Unsigned = L.NonNegative && R.NonNegative; 11646 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 11647 Unsigned); 11648 } 11649 11650 /// Return the range of a difference of the two ranges. 11651 static IntRange difference(IntRange L, IntRange R) { 11652 // We need a 1-bit-wider range if: 11653 // 1) LHS can be negative: least value can be reduced. 11654 // 2) RHS can be negative: greatest value can be increased. 11655 bool CanWiden = !L.NonNegative || !R.NonNegative; 11656 bool Unsigned = L.NonNegative && R.Width == 0; 11657 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 11658 !Unsigned, 11659 Unsigned); 11660 } 11661 11662 /// Return the range of a product of the two ranges. 11663 static IntRange product(IntRange L, IntRange R) { 11664 // If both LHS and RHS can be negative, we can form 11665 // -2^L * -2^R = 2^(L + R) 11666 // which requires L + R + 1 value bits to represent. 11667 bool CanWiden = !L.NonNegative && !R.NonNegative; 11668 bool Unsigned = L.NonNegative && R.NonNegative; 11669 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 11670 Unsigned); 11671 } 11672 11673 /// Return the range of a remainder operation between the two ranges. 11674 static IntRange rem(IntRange L, IntRange R) { 11675 // The result of a remainder can't be larger than the result of 11676 // either side. The sign of the result is the sign of the LHS. 11677 bool Unsigned = L.NonNegative; 11678 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 11679 Unsigned); 11680 } 11681 }; 11682 11683 } // namespace 11684 11685 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 11686 unsigned MaxWidth) { 11687 if (value.isSigned() && value.isNegative()) 11688 return IntRange(value.getMinSignedBits(), false); 11689 11690 if (value.getBitWidth() > MaxWidth) 11691 value = value.trunc(MaxWidth); 11692 11693 // isNonNegative() just checks the sign bit without considering 11694 // signedness. 11695 return IntRange(value.getActiveBits(), true); 11696 } 11697 11698 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 11699 unsigned MaxWidth) { 11700 if (result.isInt()) 11701 return GetValueRange(C, result.getInt(), MaxWidth); 11702 11703 if (result.isVector()) { 11704 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 11705 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 11706 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 11707 R = IntRange::join(R, El); 11708 } 11709 return R; 11710 } 11711 11712 if (result.isComplexInt()) { 11713 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 11714 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 11715 return IntRange::join(R, I); 11716 } 11717 11718 // This can happen with lossless casts to intptr_t of "based" lvalues. 11719 // Assume it might use arbitrary bits. 11720 // FIXME: The only reason we need to pass the type in here is to get 11721 // the sign right on this one case. It would be nice if APValue 11722 // preserved this. 11723 assert(result.isLValue() || result.isAddrLabelDiff()); 11724 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 11725 } 11726 11727 static QualType GetExprType(const Expr *E) { 11728 QualType Ty = E->getType(); 11729 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 11730 Ty = AtomicRHS->getValueType(); 11731 return Ty; 11732 } 11733 11734 /// Pseudo-evaluate the given integer expression, estimating the 11735 /// range of values it might take. 11736 /// 11737 /// \param MaxWidth The width to which the value will be truncated. 11738 /// \param Approximate If \c true, return a likely range for the result: in 11739 /// particular, assume that arithmetic on narrower types doesn't leave 11740 /// those types. If \c false, return a range including all possible 11741 /// result values. 11742 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 11743 bool InConstantContext, bool Approximate) { 11744 E = E->IgnoreParens(); 11745 11746 // Try a full evaluation first. 11747 Expr::EvalResult result; 11748 if (E->EvaluateAsRValue(result, C, InConstantContext)) 11749 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 11750 11751 // I think we only want to look through implicit casts here; if the 11752 // user has an explicit widening cast, we should treat the value as 11753 // being of the new, wider type. 11754 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 11755 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 11756 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 11757 Approximate); 11758 11759 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 11760 11761 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 11762 CE->getCastKind() == CK_BooleanToSignedIntegral; 11763 11764 // Assume that non-integer casts can span the full range of the type. 11765 if (!isIntegerCast) 11766 return OutputTypeRange; 11767 11768 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 11769 std::min(MaxWidth, OutputTypeRange.Width), 11770 InConstantContext, Approximate); 11771 11772 // Bail out if the subexpr's range is as wide as the cast type. 11773 if (SubRange.Width >= OutputTypeRange.Width) 11774 return OutputTypeRange; 11775 11776 // Otherwise, we take the smaller width, and we're non-negative if 11777 // either the output type or the subexpr is. 11778 return IntRange(SubRange.Width, 11779 SubRange.NonNegative || OutputTypeRange.NonNegative); 11780 } 11781 11782 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11783 // If we can fold the condition, just take that operand. 11784 bool CondResult; 11785 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 11786 return GetExprRange(C, 11787 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 11788 MaxWidth, InConstantContext, Approximate); 11789 11790 // Otherwise, conservatively merge. 11791 // GetExprRange requires an integer expression, but a throw expression 11792 // results in a void type. 11793 Expr *E = CO->getTrueExpr(); 11794 IntRange L = E->getType()->isVoidType() 11795 ? IntRange{0, true} 11796 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11797 E = CO->getFalseExpr(); 11798 IntRange R = E->getType()->isVoidType() 11799 ? IntRange{0, true} 11800 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11801 return IntRange::join(L, R); 11802 } 11803 11804 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11805 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 11806 11807 switch (BO->getOpcode()) { 11808 case BO_Cmp: 11809 llvm_unreachable("builtin <=> should have class type"); 11810 11811 // Boolean-valued operations are single-bit and positive. 11812 case BO_LAnd: 11813 case BO_LOr: 11814 case BO_LT: 11815 case BO_GT: 11816 case BO_LE: 11817 case BO_GE: 11818 case BO_EQ: 11819 case BO_NE: 11820 return IntRange::forBoolType(); 11821 11822 // The type of the assignments is the type of the LHS, so the RHS 11823 // is not necessarily the same type. 11824 case BO_MulAssign: 11825 case BO_DivAssign: 11826 case BO_RemAssign: 11827 case BO_AddAssign: 11828 case BO_SubAssign: 11829 case BO_XorAssign: 11830 case BO_OrAssign: 11831 // TODO: bitfields? 11832 return IntRange::forValueOfType(C, GetExprType(E)); 11833 11834 // Simple assignments just pass through the RHS, which will have 11835 // been coerced to the LHS type. 11836 case BO_Assign: 11837 // TODO: bitfields? 11838 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11839 Approximate); 11840 11841 // Operations with opaque sources are black-listed. 11842 case BO_PtrMemD: 11843 case BO_PtrMemI: 11844 return IntRange::forValueOfType(C, GetExprType(E)); 11845 11846 // Bitwise-and uses the *infinum* of the two source ranges. 11847 case BO_And: 11848 case BO_AndAssign: 11849 Combine = IntRange::bit_and; 11850 break; 11851 11852 // Left shift gets black-listed based on a judgement call. 11853 case BO_Shl: 11854 // ...except that we want to treat '1 << (blah)' as logically 11855 // positive. It's an important idiom. 11856 if (IntegerLiteral *I 11857 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11858 if (I->getValue() == 1) { 11859 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11860 return IntRange(R.Width, /*NonNegative*/ true); 11861 } 11862 } 11863 LLVM_FALLTHROUGH; 11864 11865 case BO_ShlAssign: 11866 return IntRange::forValueOfType(C, GetExprType(E)); 11867 11868 // Right shift by a constant can narrow its left argument. 11869 case BO_Shr: 11870 case BO_ShrAssign: { 11871 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11872 Approximate); 11873 11874 // If the shift amount is a positive constant, drop the width by 11875 // that much. 11876 if (Optional<llvm::APSInt> shift = 11877 BO->getRHS()->getIntegerConstantExpr(C)) { 11878 if (shift->isNonNegative()) { 11879 unsigned zext = shift->getZExtValue(); 11880 if (zext >= L.Width) 11881 L.Width = (L.NonNegative ? 0 : 1); 11882 else 11883 L.Width -= zext; 11884 } 11885 } 11886 11887 return L; 11888 } 11889 11890 // Comma acts as its right operand. 11891 case BO_Comma: 11892 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11893 Approximate); 11894 11895 case BO_Add: 11896 if (!Approximate) 11897 Combine = IntRange::sum; 11898 break; 11899 11900 case BO_Sub: 11901 if (BO->getLHS()->getType()->isPointerType()) 11902 return IntRange::forValueOfType(C, GetExprType(E)); 11903 if (!Approximate) 11904 Combine = IntRange::difference; 11905 break; 11906 11907 case BO_Mul: 11908 if (!Approximate) 11909 Combine = IntRange::product; 11910 break; 11911 11912 // The width of a division result is mostly determined by the size 11913 // of the LHS. 11914 case BO_Div: { 11915 // Don't 'pre-truncate' the operands. 11916 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11917 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11918 Approximate); 11919 11920 // If the divisor is constant, use that. 11921 if (Optional<llvm::APSInt> divisor = 11922 BO->getRHS()->getIntegerConstantExpr(C)) { 11923 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11924 if (log2 >= L.Width) 11925 L.Width = (L.NonNegative ? 0 : 1); 11926 else 11927 L.Width = std::min(L.Width - log2, MaxWidth); 11928 return L; 11929 } 11930 11931 // Otherwise, just use the LHS's width. 11932 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11933 // could be -1. 11934 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11935 Approximate); 11936 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11937 } 11938 11939 case BO_Rem: 11940 Combine = IntRange::rem; 11941 break; 11942 11943 // The default behavior is okay for these. 11944 case BO_Xor: 11945 case BO_Or: 11946 break; 11947 } 11948 11949 // Combine the two ranges, but limit the result to the type in which we 11950 // performed the computation. 11951 QualType T = GetExprType(E); 11952 unsigned opWidth = C.getIntWidth(T); 11953 IntRange L = 11954 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11955 IntRange R = 11956 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11957 IntRange C = Combine(L, R); 11958 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11959 C.Width = std::min(C.Width, MaxWidth); 11960 return C; 11961 } 11962 11963 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11964 switch (UO->getOpcode()) { 11965 // Boolean-valued operations are white-listed. 11966 case UO_LNot: 11967 return IntRange::forBoolType(); 11968 11969 // Operations with opaque sources are black-listed. 11970 case UO_Deref: 11971 case UO_AddrOf: // should be impossible 11972 return IntRange::forValueOfType(C, GetExprType(E)); 11973 11974 default: 11975 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11976 Approximate); 11977 } 11978 } 11979 11980 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11981 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11982 Approximate); 11983 11984 if (const auto *BitField = E->getSourceBitField()) 11985 return IntRange(BitField->getBitWidthValue(C), 11986 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11987 11988 return IntRange::forValueOfType(C, GetExprType(E)); 11989 } 11990 11991 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11992 bool InConstantContext, bool Approximate) { 11993 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11994 Approximate); 11995 } 11996 11997 /// Checks whether the given value, which currently has the given 11998 /// source semantics, has the same value when coerced through the 11999 /// target semantics. 12000 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 12001 const llvm::fltSemantics &Src, 12002 const llvm::fltSemantics &Tgt) { 12003 llvm::APFloat truncated = value; 12004 12005 bool ignored; 12006 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 12007 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 12008 12009 return truncated.bitwiseIsEqual(value); 12010 } 12011 12012 /// Checks whether the given value, which currently has the given 12013 /// source semantics, has the same value when coerced through the 12014 /// target semantics. 12015 /// 12016 /// The value might be a vector of floats (or a complex number). 12017 static bool IsSameFloatAfterCast(const APValue &value, 12018 const llvm::fltSemantics &Src, 12019 const llvm::fltSemantics &Tgt) { 12020 if (value.isFloat()) 12021 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 12022 12023 if (value.isVector()) { 12024 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 12025 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 12026 return false; 12027 return true; 12028 } 12029 12030 assert(value.isComplexFloat()); 12031 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 12032 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 12033 } 12034 12035 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 12036 bool IsListInit = false); 12037 12038 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 12039 // Suppress cases where we are comparing against an enum constant. 12040 if (const DeclRefExpr *DR = 12041 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 12042 if (isa<EnumConstantDecl>(DR->getDecl())) 12043 return true; 12044 12045 // Suppress cases where the value is expanded from a macro, unless that macro 12046 // is how a language represents a boolean literal. This is the case in both C 12047 // and Objective-C. 12048 SourceLocation BeginLoc = E->getBeginLoc(); 12049 if (BeginLoc.isMacroID()) { 12050 StringRef MacroName = Lexer::getImmediateMacroName( 12051 BeginLoc, S.getSourceManager(), S.getLangOpts()); 12052 return MacroName != "YES" && MacroName != "NO" && 12053 MacroName != "true" && MacroName != "false"; 12054 } 12055 12056 return false; 12057 } 12058 12059 static bool isKnownToHaveUnsignedValue(Expr *E) { 12060 return E->getType()->isIntegerType() && 12061 (!E->getType()->isSignedIntegerType() || 12062 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 12063 } 12064 12065 namespace { 12066 /// The promoted range of values of a type. In general this has the 12067 /// following structure: 12068 /// 12069 /// |-----------| . . . |-----------| 12070 /// ^ ^ ^ ^ 12071 /// Min HoleMin HoleMax Max 12072 /// 12073 /// ... where there is only a hole if a signed type is promoted to unsigned 12074 /// (in which case Min and Max are the smallest and largest representable 12075 /// values). 12076 struct PromotedRange { 12077 // Min, or HoleMax if there is a hole. 12078 llvm::APSInt PromotedMin; 12079 // Max, or HoleMin if there is a hole. 12080 llvm::APSInt PromotedMax; 12081 12082 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 12083 if (R.Width == 0) 12084 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 12085 else if (R.Width >= BitWidth && !Unsigned) { 12086 // Promotion made the type *narrower*. This happens when promoting 12087 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 12088 // Treat all values of 'signed int' as being in range for now. 12089 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 12090 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 12091 } else { 12092 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 12093 .extOrTrunc(BitWidth); 12094 PromotedMin.setIsUnsigned(Unsigned); 12095 12096 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 12097 .extOrTrunc(BitWidth); 12098 PromotedMax.setIsUnsigned(Unsigned); 12099 } 12100 } 12101 12102 // Determine whether this range is contiguous (has no hole). 12103 bool isContiguous() const { return PromotedMin <= PromotedMax; } 12104 12105 // Where a constant value is within the range. 12106 enum ComparisonResult { 12107 LT = 0x1, 12108 LE = 0x2, 12109 GT = 0x4, 12110 GE = 0x8, 12111 EQ = 0x10, 12112 NE = 0x20, 12113 InRangeFlag = 0x40, 12114 12115 Less = LE | LT | NE, 12116 Min = LE | InRangeFlag, 12117 InRange = InRangeFlag, 12118 Max = GE | InRangeFlag, 12119 Greater = GE | GT | NE, 12120 12121 OnlyValue = LE | GE | EQ | InRangeFlag, 12122 InHole = NE 12123 }; 12124 12125 ComparisonResult compare(const llvm::APSInt &Value) const { 12126 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 12127 Value.isUnsigned() == PromotedMin.isUnsigned()); 12128 if (!isContiguous()) { 12129 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 12130 if (Value.isMinValue()) return Min; 12131 if (Value.isMaxValue()) return Max; 12132 if (Value >= PromotedMin) return InRange; 12133 if (Value <= PromotedMax) return InRange; 12134 return InHole; 12135 } 12136 12137 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 12138 case -1: return Less; 12139 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 12140 case 1: 12141 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 12142 case -1: return InRange; 12143 case 0: return Max; 12144 case 1: return Greater; 12145 } 12146 } 12147 12148 llvm_unreachable("impossible compare result"); 12149 } 12150 12151 static llvm::Optional<StringRef> 12152 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 12153 if (Op == BO_Cmp) { 12154 ComparisonResult LTFlag = LT, GTFlag = GT; 12155 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 12156 12157 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 12158 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 12159 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 12160 return llvm::None; 12161 } 12162 12163 ComparisonResult TrueFlag, FalseFlag; 12164 if (Op == BO_EQ) { 12165 TrueFlag = EQ; 12166 FalseFlag = NE; 12167 } else if (Op == BO_NE) { 12168 TrueFlag = NE; 12169 FalseFlag = EQ; 12170 } else { 12171 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 12172 TrueFlag = LT; 12173 FalseFlag = GE; 12174 } else { 12175 TrueFlag = GT; 12176 FalseFlag = LE; 12177 } 12178 if (Op == BO_GE || Op == BO_LE) 12179 std::swap(TrueFlag, FalseFlag); 12180 } 12181 if (R & TrueFlag) 12182 return StringRef("true"); 12183 if (R & FalseFlag) 12184 return StringRef("false"); 12185 return llvm::None; 12186 } 12187 }; 12188 } 12189 12190 static bool HasEnumType(Expr *E) { 12191 // Strip off implicit integral promotions. 12192 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 12193 if (ICE->getCastKind() != CK_IntegralCast && 12194 ICE->getCastKind() != CK_NoOp) 12195 break; 12196 E = ICE->getSubExpr(); 12197 } 12198 12199 return E->getType()->isEnumeralType(); 12200 } 12201 12202 static int classifyConstantValue(Expr *Constant) { 12203 // The values of this enumeration are used in the diagnostics 12204 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 12205 enum ConstantValueKind { 12206 Miscellaneous = 0, 12207 LiteralTrue, 12208 LiteralFalse 12209 }; 12210 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 12211 return BL->getValue() ? ConstantValueKind::LiteralTrue 12212 : ConstantValueKind::LiteralFalse; 12213 return ConstantValueKind::Miscellaneous; 12214 } 12215 12216 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 12217 Expr *Constant, Expr *Other, 12218 const llvm::APSInt &Value, 12219 bool RhsConstant) { 12220 if (S.inTemplateInstantiation()) 12221 return false; 12222 12223 Expr *OriginalOther = Other; 12224 12225 Constant = Constant->IgnoreParenImpCasts(); 12226 Other = Other->IgnoreParenImpCasts(); 12227 12228 // Suppress warnings on tautological comparisons between values of the same 12229 // enumeration type. There are only two ways we could warn on this: 12230 // - If the constant is outside the range of representable values of 12231 // the enumeration. In such a case, we should warn about the cast 12232 // to enumeration type, not about the comparison. 12233 // - If the constant is the maximum / minimum in-range value. For an 12234 // enumeratin type, such comparisons can be meaningful and useful. 12235 if (Constant->getType()->isEnumeralType() && 12236 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 12237 return false; 12238 12239 IntRange OtherValueRange = GetExprRange( 12240 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 12241 12242 QualType OtherT = Other->getType(); 12243 if (const auto *AT = OtherT->getAs<AtomicType>()) 12244 OtherT = AT->getValueType(); 12245 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 12246 12247 // Special case for ObjC BOOL on targets where its a typedef for a signed char 12248 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 12249 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 12250 S.NSAPIObj->isObjCBOOLType(OtherT) && 12251 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 12252 12253 // Whether we're treating Other as being a bool because of the form of 12254 // expression despite it having another type (typically 'int' in C). 12255 bool OtherIsBooleanDespiteType = 12256 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 12257 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 12258 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 12259 12260 // Check if all values in the range of possible values of this expression 12261 // lead to the same comparison outcome. 12262 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 12263 Value.isUnsigned()); 12264 auto Cmp = OtherPromotedValueRange.compare(Value); 12265 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 12266 if (!Result) 12267 return false; 12268 12269 // Also consider the range determined by the type alone. This allows us to 12270 // classify the warning under the proper diagnostic group. 12271 bool TautologicalTypeCompare = false; 12272 { 12273 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 12274 Value.isUnsigned()); 12275 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 12276 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 12277 RhsConstant)) { 12278 TautologicalTypeCompare = true; 12279 Cmp = TypeCmp; 12280 Result = TypeResult; 12281 } 12282 } 12283 12284 // Don't warn if the non-constant operand actually always evaluates to the 12285 // same value. 12286 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 12287 return false; 12288 12289 // Suppress the diagnostic for an in-range comparison if the constant comes 12290 // from a macro or enumerator. We don't want to diagnose 12291 // 12292 // some_long_value <= INT_MAX 12293 // 12294 // when sizeof(int) == sizeof(long). 12295 bool InRange = Cmp & PromotedRange::InRangeFlag; 12296 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 12297 return false; 12298 12299 // A comparison of an unsigned bit-field against 0 is really a type problem, 12300 // even though at the type level the bit-field might promote to 'signed int'. 12301 if (Other->refersToBitField() && InRange && Value == 0 && 12302 Other->getType()->isUnsignedIntegerOrEnumerationType()) 12303 TautologicalTypeCompare = true; 12304 12305 // If this is a comparison to an enum constant, include that 12306 // constant in the diagnostic. 12307 const EnumConstantDecl *ED = nullptr; 12308 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 12309 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 12310 12311 // Should be enough for uint128 (39 decimal digits) 12312 SmallString<64> PrettySourceValue; 12313 llvm::raw_svector_ostream OS(PrettySourceValue); 12314 if (ED) { 12315 OS << '\'' << *ED << "' (" << Value << ")"; 12316 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 12317 Constant->IgnoreParenImpCasts())) { 12318 OS << (BL->getValue() ? "YES" : "NO"); 12319 } else { 12320 OS << Value; 12321 } 12322 12323 if (!TautologicalTypeCompare) { 12324 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 12325 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 12326 << E->getOpcodeStr() << OS.str() << *Result 12327 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 12328 return true; 12329 } 12330 12331 if (IsObjCSignedCharBool) { 12332 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12333 S.PDiag(diag::warn_tautological_compare_objc_bool) 12334 << OS.str() << *Result); 12335 return true; 12336 } 12337 12338 // FIXME: We use a somewhat different formatting for the in-range cases and 12339 // cases involving boolean values for historical reasons. We should pick a 12340 // consistent way of presenting these diagnostics. 12341 if (!InRange || Other->isKnownToHaveBooleanValue()) { 12342 12343 S.DiagRuntimeBehavior( 12344 E->getOperatorLoc(), E, 12345 S.PDiag(!InRange ? diag::warn_out_of_range_compare 12346 : diag::warn_tautological_bool_compare) 12347 << OS.str() << classifyConstantValue(Constant) << OtherT 12348 << OtherIsBooleanDespiteType << *Result 12349 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 12350 } else { 12351 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 12352 unsigned Diag = 12353 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 12354 ? (HasEnumType(OriginalOther) 12355 ? diag::warn_unsigned_enum_always_true_comparison 12356 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 12357 : diag::warn_unsigned_always_true_comparison) 12358 : diag::warn_tautological_constant_compare; 12359 12360 S.Diag(E->getOperatorLoc(), Diag) 12361 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 12362 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 12363 } 12364 12365 return true; 12366 } 12367 12368 /// Analyze the operands of the given comparison. Implements the 12369 /// fallback case from AnalyzeComparison. 12370 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 12371 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12372 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12373 } 12374 12375 /// Implements -Wsign-compare. 12376 /// 12377 /// \param E the binary operator to check for warnings 12378 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 12379 // The type the comparison is being performed in. 12380 QualType T = E->getLHS()->getType(); 12381 12382 // Only analyze comparison operators where both sides have been converted to 12383 // the same type. 12384 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 12385 return AnalyzeImpConvsInComparison(S, E); 12386 12387 // Don't analyze value-dependent comparisons directly. 12388 if (E->isValueDependent()) 12389 return AnalyzeImpConvsInComparison(S, E); 12390 12391 Expr *LHS = E->getLHS(); 12392 Expr *RHS = E->getRHS(); 12393 12394 if (T->isIntegralType(S.Context)) { 12395 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 12396 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 12397 12398 // We don't care about expressions whose result is a constant. 12399 if (RHSValue && LHSValue) 12400 return AnalyzeImpConvsInComparison(S, E); 12401 12402 // We only care about expressions where just one side is literal 12403 if ((bool)RHSValue ^ (bool)LHSValue) { 12404 // Is the constant on the RHS or LHS? 12405 const bool RhsConstant = (bool)RHSValue; 12406 Expr *Const = RhsConstant ? RHS : LHS; 12407 Expr *Other = RhsConstant ? LHS : RHS; 12408 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 12409 12410 // Check whether an integer constant comparison results in a value 12411 // of 'true' or 'false'. 12412 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 12413 return AnalyzeImpConvsInComparison(S, E); 12414 } 12415 } 12416 12417 if (!T->hasUnsignedIntegerRepresentation()) { 12418 // We don't do anything special if this isn't an unsigned integral 12419 // comparison: we're only interested in integral comparisons, and 12420 // signed comparisons only happen in cases we don't care to warn about. 12421 return AnalyzeImpConvsInComparison(S, E); 12422 } 12423 12424 LHS = LHS->IgnoreParenImpCasts(); 12425 RHS = RHS->IgnoreParenImpCasts(); 12426 12427 if (!S.getLangOpts().CPlusPlus) { 12428 // Avoid warning about comparison of integers with different signs when 12429 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 12430 // the type of `E`. 12431 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 12432 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12433 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 12434 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12435 } 12436 12437 // Check to see if one of the (unmodified) operands is of different 12438 // signedness. 12439 Expr *signedOperand, *unsignedOperand; 12440 if (LHS->getType()->hasSignedIntegerRepresentation()) { 12441 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 12442 "unsigned comparison between two signed integer expressions?"); 12443 signedOperand = LHS; 12444 unsignedOperand = RHS; 12445 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 12446 signedOperand = RHS; 12447 unsignedOperand = LHS; 12448 } else { 12449 return AnalyzeImpConvsInComparison(S, E); 12450 } 12451 12452 // Otherwise, calculate the effective range of the signed operand. 12453 IntRange signedRange = GetExprRange( 12454 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 12455 12456 // Go ahead and analyze implicit conversions in the operands. Note 12457 // that we skip the implicit conversions on both sides. 12458 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 12459 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 12460 12461 // If the signed range is non-negative, -Wsign-compare won't fire. 12462 if (signedRange.NonNegative) 12463 return; 12464 12465 // For (in)equality comparisons, if the unsigned operand is a 12466 // constant which cannot collide with a overflowed signed operand, 12467 // then reinterpreting the signed operand as unsigned will not 12468 // change the result of the comparison. 12469 if (E->isEqualityOp()) { 12470 unsigned comparisonWidth = S.Context.getIntWidth(T); 12471 IntRange unsignedRange = 12472 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 12473 /*Approximate*/ true); 12474 12475 // We should never be unable to prove that the unsigned operand is 12476 // non-negative. 12477 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 12478 12479 if (unsignedRange.Width < comparisonWidth) 12480 return; 12481 } 12482 12483 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12484 S.PDiag(diag::warn_mixed_sign_comparison) 12485 << LHS->getType() << RHS->getType() 12486 << LHS->getSourceRange() << RHS->getSourceRange()); 12487 } 12488 12489 /// Analyzes an attempt to assign the given value to a bitfield. 12490 /// 12491 /// Returns true if there was something fishy about the attempt. 12492 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 12493 SourceLocation InitLoc) { 12494 assert(Bitfield->isBitField()); 12495 if (Bitfield->isInvalidDecl()) 12496 return false; 12497 12498 // White-list bool bitfields. 12499 QualType BitfieldType = Bitfield->getType(); 12500 if (BitfieldType->isBooleanType()) 12501 return false; 12502 12503 if (BitfieldType->isEnumeralType()) { 12504 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 12505 // If the underlying enum type was not explicitly specified as an unsigned 12506 // type and the enum contain only positive values, MSVC++ will cause an 12507 // inconsistency by storing this as a signed type. 12508 if (S.getLangOpts().CPlusPlus11 && 12509 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 12510 BitfieldEnumDecl->getNumPositiveBits() > 0 && 12511 BitfieldEnumDecl->getNumNegativeBits() == 0) { 12512 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 12513 << BitfieldEnumDecl; 12514 } 12515 } 12516 12517 if (Bitfield->getType()->isBooleanType()) 12518 return false; 12519 12520 // Ignore value- or type-dependent expressions. 12521 if (Bitfield->getBitWidth()->isValueDependent() || 12522 Bitfield->getBitWidth()->isTypeDependent() || 12523 Init->isValueDependent() || 12524 Init->isTypeDependent()) 12525 return false; 12526 12527 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 12528 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 12529 12530 Expr::EvalResult Result; 12531 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 12532 Expr::SE_AllowSideEffects)) { 12533 // The RHS is not constant. If the RHS has an enum type, make sure the 12534 // bitfield is wide enough to hold all the values of the enum without 12535 // truncation. 12536 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 12537 EnumDecl *ED = EnumTy->getDecl(); 12538 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 12539 12540 // Enum types are implicitly signed on Windows, so check if there are any 12541 // negative enumerators to see if the enum was intended to be signed or 12542 // not. 12543 bool SignedEnum = ED->getNumNegativeBits() > 0; 12544 12545 // Check for surprising sign changes when assigning enum values to a 12546 // bitfield of different signedness. If the bitfield is signed and we 12547 // have exactly the right number of bits to store this unsigned enum, 12548 // suggest changing the enum to an unsigned type. This typically happens 12549 // on Windows where unfixed enums always use an underlying type of 'int'. 12550 unsigned DiagID = 0; 12551 if (SignedEnum && !SignedBitfield) { 12552 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 12553 } else if (SignedBitfield && !SignedEnum && 12554 ED->getNumPositiveBits() == FieldWidth) { 12555 DiagID = diag::warn_signed_bitfield_enum_conversion; 12556 } 12557 12558 if (DiagID) { 12559 S.Diag(InitLoc, DiagID) << Bitfield << ED; 12560 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 12561 SourceRange TypeRange = 12562 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 12563 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 12564 << SignedEnum << TypeRange; 12565 } 12566 12567 // Compute the required bitwidth. If the enum has negative values, we need 12568 // one more bit than the normal number of positive bits to represent the 12569 // sign bit. 12570 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 12571 ED->getNumNegativeBits()) 12572 : ED->getNumPositiveBits(); 12573 12574 // Check the bitwidth. 12575 if (BitsNeeded > FieldWidth) { 12576 Expr *WidthExpr = Bitfield->getBitWidth(); 12577 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 12578 << Bitfield << ED; 12579 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 12580 << BitsNeeded << ED << WidthExpr->getSourceRange(); 12581 } 12582 } 12583 12584 return false; 12585 } 12586 12587 llvm::APSInt Value = Result.Val.getInt(); 12588 12589 unsigned OriginalWidth = Value.getBitWidth(); 12590 12591 if (!Value.isSigned() || Value.isNegative()) 12592 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 12593 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 12594 OriginalWidth = Value.getMinSignedBits(); 12595 12596 if (OriginalWidth <= FieldWidth) 12597 return false; 12598 12599 // Compute the value which the bitfield will contain. 12600 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 12601 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 12602 12603 // Check whether the stored value is equal to the original value. 12604 TruncatedValue = TruncatedValue.extend(OriginalWidth); 12605 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 12606 return false; 12607 12608 // Special-case bitfields of width 1: booleans are naturally 0/1, and 12609 // therefore don't strictly fit into a signed bitfield of width 1. 12610 if (FieldWidth == 1 && Value == 1) 12611 return false; 12612 12613 std::string PrettyValue = toString(Value, 10); 12614 std::string PrettyTrunc = toString(TruncatedValue, 10); 12615 12616 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 12617 << PrettyValue << PrettyTrunc << OriginalInit->getType() 12618 << Init->getSourceRange(); 12619 12620 return true; 12621 } 12622 12623 /// Analyze the given simple or compound assignment for warning-worthy 12624 /// operations. 12625 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 12626 // Just recurse on the LHS. 12627 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12628 12629 // We want to recurse on the RHS as normal unless we're assigning to 12630 // a bitfield. 12631 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 12632 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 12633 E->getOperatorLoc())) { 12634 // Recurse, ignoring any implicit conversions on the RHS. 12635 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 12636 E->getOperatorLoc()); 12637 } 12638 } 12639 12640 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12641 12642 // Diagnose implicitly sequentially-consistent atomic assignment. 12643 if (E->getLHS()->getType()->isAtomicType()) 12644 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12645 } 12646 12647 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12648 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 12649 SourceLocation CContext, unsigned diag, 12650 bool pruneControlFlow = false) { 12651 if (pruneControlFlow) { 12652 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12653 S.PDiag(diag) 12654 << SourceType << T << E->getSourceRange() 12655 << SourceRange(CContext)); 12656 return; 12657 } 12658 S.Diag(E->getExprLoc(), diag) 12659 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 12660 } 12661 12662 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12663 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 12664 SourceLocation CContext, 12665 unsigned diag, bool pruneControlFlow = false) { 12666 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 12667 } 12668 12669 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 12670 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 12671 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 12672 } 12673 12674 static void adornObjCBoolConversionDiagWithTernaryFixit( 12675 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 12676 Expr *Ignored = SourceExpr->IgnoreImplicit(); 12677 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 12678 Ignored = OVE->getSourceExpr(); 12679 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 12680 isa<BinaryOperator>(Ignored) || 12681 isa<CXXOperatorCallExpr>(Ignored); 12682 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 12683 if (NeedsParens) 12684 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 12685 << FixItHint::CreateInsertion(EndLoc, ")"); 12686 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 12687 } 12688 12689 /// Diagnose an implicit cast from a floating point value to an integer value. 12690 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 12691 SourceLocation CContext) { 12692 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 12693 const bool PruneWarnings = S.inTemplateInstantiation(); 12694 12695 Expr *InnerE = E->IgnoreParenImpCasts(); 12696 // We also want to warn on, e.g., "int i = -1.234" 12697 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 12698 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 12699 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 12700 12701 const bool IsLiteral = 12702 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 12703 12704 llvm::APFloat Value(0.0); 12705 bool IsConstant = 12706 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 12707 if (!IsConstant) { 12708 if (isObjCSignedCharBool(S, T)) { 12709 return adornObjCBoolConversionDiagWithTernaryFixit( 12710 S, E, 12711 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 12712 << E->getType()); 12713 } 12714 12715 return DiagnoseImpCast(S, E, T, CContext, 12716 diag::warn_impcast_float_integer, PruneWarnings); 12717 } 12718 12719 bool isExact = false; 12720 12721 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 12722 T->hasUnsignedIntegerRepresentation()); 12723 llvm::APFloat::opStatus Result = Value.convertToInteger( 12724 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 12725 12726 // FIXME: Force the precision of the source value down so we don't print 12727 // digits which are usually useless (we don't really care here if we 12728 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 12729 // would automatically print the shortest representation, but it's a bit 12730 // tricky to implement. 12731 SmallString<16> PrettySourceValue; 12732 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 12733 precision = (precision * 59 + 195) / 196; 12734 Value.toString(PrettySourceValue, precision); 12735 12736 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 12737 return adornObjCBoolConversionDiagWithTernaryFixit( 12738 S, E, 12739 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 12740 << PrettySourceValue); 12741 } 12742 12743 if (Result == llvm::APFloat::opOK && isExact) { 12744 if (IsLiteral) return; 12745 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 12746 PruneWarnings); 12747 } 12748 12749 // Conversion of a floating-point value to a non-bool integer where the 12750 // integral part cannot be represented by the integer type is undefined. 12751 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 12752 return DiagnoseImpCast( 12753 S, E, T, CContext, 12754 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 12755 : diag::warn_impcast_float_to_integer_out_of_range, 12756 PruneWarnings); 12757 12758 unsigned DiagID = 0; 12759 if (IsLiteral) { 12760 // Warn on floating point literal to integer. 12761 DiagID = diag::warn_impcast_literal_float_to_integer; 12762 } else if (IntegerValue == 0) { 12763 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 12764 return DiagnoseImpCast(S, E, T, CContext, 12765 diag::warn_impcast_float_integer, PruneWarnings); 12766 } 12767 // Warn on non-zero to zero conversion. 12768 DiagID = diag::warn_impcast_float_to_integer_zero; 12769 } else { 12770 if (IntegerValue.isUnsigned()) { 12771 if (!IntegerValue.isMaxValue()) { 12772 return DiagnoseImpCast(S, E, T, CContext, 12773 diag::warn_impcast_float_integer, PruneWarnings); 12774 } 12775 } else { // IntegerValue.isSigned() 12776 if (!IntegerValue.isMaxSignedValue() && 12777 !IntegerValue.isMinSignedValue()) { 12778 return DiagnoseImpCast(S, E, T, CContext, 12779 diag::warn_impcast_float_integer, PruneWarnings); 12780 } 12781 } 12782 // Warn on evaluatable floating point expression to integer conversion. 12783 DiagID = diag::warn_impcast_float_to_integer; 12784 } 12785 12786 SmallString<16> PrettyTargetValue; 12787 if (IsBool) 12788 PrettyTargetValue = Value.isZero() ? "false" : "true"; 12789 else 12790 IntegerValue.toString(PrettyTargetValue); 12791 12792 if (PruneWarnings) { 12793 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12794 S.PDiag(DiagID) 12795 << E->getType() << T.getUnqualifiedType() 12796 << PrettySourceValue << PrettyTargetValue 12797 << E->getSourceRange() << SourceRange(CContext)); 12798 } else { 12799 S.Diag(E->getExprLoc(), DiagID) 12800 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 12801 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 12802 } 12803 } 12804 12805 /// Analyze the given compound assignment for the possible losing of 12806 /// floating-point precision. 12807 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 12808 assert(isa<CompoundAssignOperator>(E) && 12809 "Must be compound assignment operation"); 12810 // Recurse on the LHS and RHS in here 12811 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12812 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12813 12814 if (E->getLHS()->getType()->isAtomicType()) 12815 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 12816 12817 // Now check the outermost expression 12818 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 12819 const auto *RBT = cast<CompoundAssignOperator>(E) 12820 ->getComputationResultType() 12821 ->getAs<BuiltinType>(); 12822 12823 // The below checks assume source is floating point. 12824 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 12825 12826 // If source is floating point but target is an integer. 12827 if (ResultBT->isInteger()) 12828 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 12829 E->getExprLoc(), diag::warn_impcast_float_integer); 12830 12831 if (!ResultBT->isFloatingPoint()) 12832 return; 12833 12834 // If both source and target are floating points, warn about losing precision. 12835 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12836 QualType(ResultBT, 0), QualType(RBT, 0)); 12837 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 12838 // warn about dropping FP rank. 12839 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 12840 diag::warn_impcast_float_result_precision); 12841 } 12842 12843 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 12844 IntRange Range) { 12845 if (!Range.Width) return "0"; 12846 12847 llvm::APSInt ValueInRange = Value; 12848 ValueInRange.setIsSigned(!Range.NonNegative); 12849 ValueInRange = ValueInRange.trunc(Range.Width); 12850 return toString(ValueInRange, 10); 12851 } 12852 12853 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 12854 if (!isa<ImplicitCastExpr>(Ex)) 12855 return false; 12856 12857 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12858 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12859 const Type *Source = 12860 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12861 if (Target->isDependentType()) 12862 return false; 12863 12864 const BuiltinType *FloatCandidateBT = 12865 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12866 const Type *BoolCandidateType = ToBool ? Target : Source; 12867 12868 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12869 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12870 } 12871 12872 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12873 SourceLocation CC) { 12874 unsigned NumArgs = TheCall->getNumArgs(); 12875 for (unsigned i = 0; i < NumArgs; ++i) { 12876 Expr *CurrA = TheCall->getArg(i); 12877 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12878 continue; 12879 12880 bool IsSwapped = ((i > 0) && 12881 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12882 IsSwapped |= ((i < (NumArgs - 1)) && 12883 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12884 if (IsSwapped) { 12885 // Warn on this floating-point to bool conversion. 12886 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12887 CurrA->getType(), CC, 12888 diag::warn_impcast_floating_point_to_bool); 12889 } 12890 } 12891 } 12892 12893 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12894 SourceLocation CC) { 12895 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12896 E->getExprLoc())) 12897 return; 12898 12899 // Don't warn on functions which have return type nullptr_t. 12900 if (isa<CallExpr>(E)) 12901 return; 12902 12903 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12904 const Expr::NullPointerConstantKind NullKind = 12905 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12906 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12907 return; 12908 12909 // Return if target type is a safe conversion. 12910 if (T->isAnyPointerType() || T->isBlockPointerType() || 12911 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12912 return; 12913 12914 SourceLocation Loc = E->getSourceRange().getBegin(); 12915 12916 // Venture through the macro stacks to get to the source of macro arguments. 12917 // The new location is a better location than the complete location that was 12918 // passed in. 12919 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12920 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12921 12922 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12923 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12924 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12925 Loc, S.SourceMgr, S.getLangOpts()); 12926 if (MacroName == "NULL") 12927 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12928 } 12929 12930 // Only warn if the null and context location are in the same macro expansion. 12931 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12932 return; 12933 12934 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12935 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12936 << FixItHint::CreateReplacement(Loc, 12937 S.getFixItZeroLiteralForType(T, Loc)); 12938 } 12939 12940 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12941 ObjCArrayLiteral *ArrayLiteral); 12942 12943 static void 12944 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12945 ObjCDictionaryLiteral *DictionaryLiteral); 12946 12947 /// Check a single element within a collection literal against the 12948 /// target element type. 12949 static void checkObjCCollectionLiteralElement(Sema &S, 12950 QualType TargetElementType, 12951 Expr *Element, 12952 unsigned ElementKind) { 12953 // Skip a bitcast to 'id' or qualified 'id'. 12954 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12955 if (ICE->getCastKind() == CK_BitCast && 12956 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12957 Element = ICE->getSubExpr(); 12958 } 12959 12960 QualType ElementType = Element->getType(); 12961 ExprResult ElementResult(Element); 12962 if (ElementType->getAs<ObjCObjectPointerType>() && 12963 S.CheckSingleAssignmentConstraints(TargetElementType, 12964 ElementResult, 12965 false, false) 12966 != Sema::Compatible) { 12967 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12968 << ElementType << ElementKind << TargetElementType 12969 << Element->getSourceRange(); 12970 } 12971 12972 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12973 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12974 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12975 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12976 } 12977 12978 /// Check an Objective-C array literal being converted to the given 12979 /// target type. 12980 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12981 ObjCArrayLiteral *ArrayLiteral) { 12982 if (!S.NSArrayDecl) 12983 return; 12984 12985 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12986 if (!TargetObjCPtr) 12987 return; 12988 12989 if (TargetObjCPtr->isUnspecialized() || 12990 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12991 != S.NSArrayDecl->getCanonicalDecl()) 12992 return; 12993 12994 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12995 if (TypeArgs.size() != 1) 12996 return; 12997 12998 QualType TargetElementType = TypeArgs[0]; 12999 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 13000 checkObjCCollectionLiteralElement(S, TargetElementType, 13001 ArrayLiteral->getElement(I), 13002 0); 13003 } 13004 } 13005 13006 /// Check an Objective-C dictionary literal being converted to the given 13007 /// target type. 13008 static void 13009 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 13010 ObjCDictionaryLiteral *DictionaryLiteral) { 13011 if (!S.NSDictionaryDecl) 13012 return; 13013 13014 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 13015 if (!TargetObjCPtr) 13016 return; 13017 13018 if (TargetObjCPtr->isUnspecialized() || 13019 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 13020 != S.NSDictionaryDecl->getCanonicalDecl()) 13021 return; 13022 13023 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 13024 if (TypeArgs.size() != 2) 13025 return; 13026 13027 QualType TargetKeyType = TypeArgs[0]; 13028 QualType TargetObjectType = TypeArgs[1]; 13029 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 13030 auto Element = DictionaryLiteral->getKeyValueElement(I); 13031 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 13032 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 13033 } 13034 } 13035 13036 // Helper function to filter out cases for constant width constant conversion. 13037 // Don't warn on char array initialization or for non-decimal values. 13038 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 13039 SourceLocation CC) { 13040 // If initializing from a constant, and the constant starts with '0', 13041 // then it is a binary, octal, or hexadecimal. Allow these constants 13042 // to fill all the bits, even if there is a sign change. 13043 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 13044 const char FirstLiteralCharacter = 13045 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 13046 if (FirstLiteralCharacter == '0') 13047 return false; 13048 } 13049 13050 // If the CC location points to a '{', and the type is char, then assume 13051 // assume it is an array initialization. 13052 if (CC.isValid() && T->isCharType()) { 13053 const char FirstContextCharacter = 13054 S.getSourceManager().getCharacterData(CC)[0]; 13055 if (FirstContextCharacter == '{') 13056 return false; 13057 } 13058 13059 return true; 13060 } 13061 13062 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 13063 const auto *IL = dyn_cast<IntegerLiteral>(E); 13064 if (!IL) { 13065 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 13066 if (UO->getOpcode() == UO_Minus) 13067 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 13068 } 13069 } 13070 13071 return IL; 13072 } 13073 13074 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 13075 E = E->IgnoreParenImpCasts(); 13076 SourceLocation ExprLoc = E->getExprLoc(); 13077 13078 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 13079 BinaryOperator::Opcode Opc = BO->getOpcode(); 13080 Expr::EvalResult Result; 13081 // Do not diagnose unsigned shifts. 13082 if (Opc == BO_Shl) { 13083 const auto *LHS = getIntegerLiteral(BO->getLHS()); 13084 const auto *RHS = getIntegerLiteral(BO->getRHS()); 13085 if (LHS && LHS->getValue() == 0) 13086 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 13087 else if (!E->isValueDependent() && LHS && RHS && 13088 RHS->getValue().isNonNegative() && 13089 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 13090 S.Diag(ExprLoc, diag::warn_left_shift_always) 13091 << (Result.Val.getInt() != 0); 13092 else if (E->getType()->isSignedIntegerType()) 13093 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 13094 } 13095 } 13096 13097 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 13098 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 13099 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 13100 if (!LHS || !RHS) 13101 return; 13102 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 13103 (RHS->getValue() == 0 || RHS->getValue() == 1)) 13104 // Do not diagnose common idioms. 13105 return; 13106 if (LHS->getValue() != 0 && RHS->getValue() != 0) 13107 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 13108 } 13109 } 13110 13111 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 13112 SourceLocation CC, 13113 bool *ICContext = nullptr, 13114 bool IsListInit = false) { 13115 if (E->isTypeDependent() || E->isValueDependent()) return; 13116 13117 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 13118 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 13119 if (Source == Target) return; 13120 if (Target->isDependentType()) return; 13121 13122 // If the conversion context location is invalid don't complain. We also 13123 // don't want to emit a warning if the issue occurs from the expansion of 13124 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 13125 // delay this check as long as possible. Once we detect we are in that 13126 // scenario, we just return. 13127 if (CC.isInvalid()) 13128 return; 13129 13130 if (Source->isAtomicType()) 13131 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 13132 13133 // Diagnose implicit casts to bool. 13134 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 13135 if (isa<StringLiteral>(E)) 13136 // Warn on string literal to bool. Checks for string literals in logical 13137 // and expressions, for instance, assert(0 && "error here"), are 13138 // prevented by a check in AnalyzeImplicitConversions(). 13139 return DiagnoseImpCast(S, E, T, CC, 13140 diag::warn_impcast_string_literal_to_bool); 13141 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 13142 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 13143 // This covers the literal expressions that evaluate to Objective-C 13144 // objects. 13145 return DiagnoseImpCast(S, E, T, CC, 13146 diag::warn_impcast_objective_c_literal_to_bool); 13147 } 13148 if (Source->isPointerType() || Source->canDecayToPointerType()) { 13149 // Warn on pointer to bool conversion that is always true. 13150 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 13151 SourceRange(CC)); 13152 } 13153 } 13154 13155 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 13156 // is a typedef for signed char (macOS), then that constant value has to be 1 13157 // or 0. 13158 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 13159 Expr::EvalResult Result; 13160 if (E->EvaluateAsInt(Result, S.getASTContext(), 13161 Expr::SE_AllowSideEffects)) { 13162 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 13163 adornObjCBoolConversionDiagWithTernaryFixit( 13164 S, E, 13165 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 13166 << toString(Result.Val.getInt(), 10)); 13167 } 13168 return; 13169 } 13170 } 13171 13172 // Check implicit casts from Objective-C collection literals to specialized 13173 // collection types, e.g., NSArray<NSString *> *. 13174 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 13175 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 13176 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 13177 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 13178 13179 // Strip vector types. 13180 if (isa<VectorType>(Source)) { 13181 if (Target->isVLSTBuiltinType() && 13182 (S.Context.areCompatibleSveTypes(QualType(Target, 0), 13183 QualType(Source, 0)) || 13184 S.Context.areLaxCompatibleSveTypes(QualType(Target, 0), 13185 QualType(Source, 0)))) 13186 return; 13187 13188 if (!isa<VectorType>(Target)) { 13189 if (S.SourceMgr.isInSystemMacro(CC)) 13190 return; 13191 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 13192 } 13193 13194 // If the vector cast is cast between two vectors of the same size, it is 13195 // a bitcast, not a conversion. 13196 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 13197 return; 13198 13199 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 13200 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 13201 } 13202 if (auto VecTy = dyn_cast<VectorType>(Target)) 13203 Target = VecTy->getElementType().getTypePtr(); 13204 13205 // Strip complex types. 13206 if (isa<ComplexType>(Source)) { 13207 if (!isa<ComplexType>(Target)) { 13208 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 13209 return; 13210 13211 return DiagnoseImpCast(S, E, T, CC, 13212 S.getLangOpts().CPlusPlus 13213 ? diag::err_impcast_complex_scalar 13214 : diag::warn_impcast_complex_scalar); 13215 } 13216 13217 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 13218 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 13219 } 13220 13221 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 13222 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 13223 13224 // If the source is floating point... 13225 if (SourceBT && SourceBT->isFloatingPoint()) { 13226 // ...and the target is floating point... 13227 if (TargetBT && TargetBT->isFloatingPoint()) { 13228 // ...then warn if we're dropping FP rank. 13229 13230 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 13231 QualType(SourceBT, 0), QualType(TargetBT, 0)); 13232 if (Order > 0) { 13233 // Don't warn about float constants that are precisely 13234 // representable in the target type. 13235 Expr::EvalResult result; 13236 if (E->EvaluateAsRValue(result, S.Context)) { 13237 // Value might be a float, a float vector, or a float complex. 13238 if (IsSameFloatAfterCast(result.Val, 13239 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 13240 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 13241 return; 13242 } 13243 13244 if (S.SourceMgr.isInSystemMacro(CC)) 13245 return; 13246 13247 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 13248 } 13249 // ... or possibly if we're increasing rank, too 13250 else if (Order < 0) { 13251 if (S.SourceMgr.isInSystemMacro(CC)) 13252 return; 13253 13254 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 13255 } 13256 return; 13257 } 13258 13259 // If the target is integral, always warn. 13260 if (TargetBT && TargetBT->isInteger()) { 13261 if (S.SourceMgr.isInSystemMacro(CC)) 13262 return; 13263 13264 DiagnoseFloatingImpCast(S, E, T, CC); 13265 } 13266 13267 // Detect the case where a call result is converted from floating-point to 13268 // to bool, and the final argument to the call is converted from bool, to 13269 // discover this typo: 13270 // 13271 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 13272 // 13273 // FIXME: This is an incredibly special case; is there some more general 13274 // way to detect this class of misplaced-parentheses bug? 13275 if (Target->isBooleanType() && isa<CallExpr>(E)) { 13276 // Check last argument of function call to see if it is an 13277 // implicit cast from a type matching the type the result 13278 // is being cast to. 13279 CallExpr *CEx = cast<CallExpr>(E); 13280 if (unsigned NumArgs = CEx->getNumArgs()) { 13281 Expr *LastA = CEx->getArg(NumArgs - 1); 13282 Expr *InnerE = LastA->IgnoreParenImpCasts(); 13283 if (isa<ImplicitCastExpr>(LastA) && 13284 InnerE->getType()->isBooleanType()) { 13285 // Warn on this floating-point to bool conversion 13286 DiagnoseImpCast(S, E, T, CC, 13287 diag::warn_impcast_floating_point_to_bool); 13288 } 13289 } 13290 } 13291 return; 13292 } 13293 13294 // Valid casts involving fixed point types should be accounted for here. 13295 if (Source->isFixedPointType()) { 13296 if (Target->isUnsaturatedFixedPointType()) { 13297 Expr::EvalResult Result; 13298 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 13299 S.isConstantEvaluated())) { 13300 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 13301 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 13302 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 13303 if (Value > MaxVal || Value < MinVal) { 13304 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13305 S.PDiag(diag::warn_impcast_fixed_point_range) 13306 << Value.toString() << T 13307 << E->getSourceRange() 13308 << clang::SourceRange(CC)); 13309 return; 13310 } 13311 } 13312 } else if (Target->isIntegerType()) { 13313 Expr::EvalResult Result; 13314 if (!S.isConstantEvaluated() && 13315 E->EvaluateAsFixedPoint(Result, S.Context, 13316 Expr::SE_AllowSideEffects)) { 13317 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 13318 13319 bool Overflowed; 13320 llvm::APSInt IntResult = FXResult.convertToInt( 13321 S.Context.getIntWidth(T), 13322 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 13323 13324 if (Overflowed) { 13325 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13326 S.PDiag(diag::warn_impcast_fixed_point_range) 13327 << FXResult.toString() << T 13328 << E->getSourceRange() 13329 << clang::SourceRange(CC)); 13330 return; 13331 } 13332 } 13333 } 13334 } else if (Target->isUnsaturatedFixedPointType()) { 13335 if (Source->isIntegerType()) { 13336 Expr::EvalResult Result; 13337 if (!S.isConstantEvaluated() && 13338 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 13339 llvm::APSInt Value = Result.Val.getInt(); 13340 13341 bool Overflowed; 13342 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 13343 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 13344 13345 if (Overflowed) { 13346 S.DiagRuntimeBehavior(E->getExprLoc(), E, 13347 S.PDiag(diag::warn_impcast_fixed_point_range) 13348 << toString(Value, /*Radix=*/10) << T 13349 << E->getSourceRange() 13350 << clang::SourceRange(CC)); 13351 return; 13352 } 13353 } 13354 } 13355 } 13356 13357 // If we are casting an integer type to a floating point type without 13358 // initialization-list syntax, we might lose accuracy if the floating 13359 // point type has a narrower significand than the integer type. 13360 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 13361 TargetBT->isFloatingType() && !IsListInit) { 13362 // Determine the number of precision bits in the source integer type. 13363 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 13364 /*Approximate*/ true); 13365 unsigned int SourcePrecision = SourceRange.Width; 13366 13367 // Determine the number of precision bits in the 13368 // target floating point type. 13369 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 13370 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13371 13372 if (SourcePrecision > 0 && TargetPrecision > 0 && 13373 SourcePrecision > TargetPrecision) { 13374 13375 if (Optional<llvm::APSInt> SourceInt = 13376 E->getIntegerConstantExpr(S.Context)) { 13377 // If the source integer is a constant, convert it to the target 13378 // floating point type. Issue a warning if the value changes 13379 // during the whole conversion. 13380 llvm::APFloat TargetFloatValue( 13381 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13382 llvm::APFloat::opStatus ConversionStatus = 13383 TargetFloatValue.convertFromAPInt( 13384 *SourceInt, SourceBT->isSignedInteger(), 13385 llvm::APFloat::rmNearestTiesToEven); 13386 13387 if (ConversionStatus != llvm::APFloat::opOK) { 13388 SmallString<32> PrettySourceValue; 13389 SourceInt->toString(PrettySourceValue, 10); 13390 SmallString<32> PrettyTargetValue; 13391 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 13392 13393 S.DiagRuntimeBehavior( 13394 E->getExprLoc(), E, 13395 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 13396 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13397 << E->getSourceRange() << clang::SourceRange(CC)); 13398 } 13399 } else { 13400 // Otherwise, the implicit conversion may lose precision. 13401 DiagnoseImpCast(S, E, T, CC, 13402 diag::warn_impcast_integer_float_precision); 13403 } 13404 } 13405 } 13406 13407 DiagnoseNullConversion(S, E, T, CC); 13408 13409 S.DiscardMisalignedMemberAddress(Target, E); 13410 13411 if (Target->isBooleanType()) 13412 DiagnoseIntInBoolContext(S, E); 13413 13414 if (!Source->isIntegerType() || !Target->isIntegerType()) 13415 return; 13416 13417 // TODO: remove this early return once the false positives for constant->bool 13418 // in templates, macros, etc, are reduced or removed. 13419 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 13420 return; 13421 13422 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 13423 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 13424 return adornObjCBoolConversionDiagWithTernaryFixit( 13425 S, E, 13426 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 13427 << E->getType()); 13428 } 13429 13430 IntRange SourceTypeRange = 13431 IntRange::forTargetOfCanonicalType(S.Context, Source); 13432 IntRange LikelySourceRange = 13433 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 13434 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 13435 13436 if (LikelySourceRange.Width > TargetRange.Width) { 13437 // If the source is a constant, use a default-on diagnostic. 13438 // TODO: this should happen for bitfield stores, too. 13439 Expr::EvalResult Result; 13440 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 13441 S.isConstantEvaluated())) { 13442 llvm::APSInt Value(32); 13443 Value = Result.Val.getInt(); 13444 13445 if (S.SourceMgr.isInSystemMacro(CC)) 13446 return; 13447 13448 std::string PrettySourceValue = toString(Value, 10); 13449 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13450 13451 S.DiagRuntimeBehavior( 13452 E->getExprLoc(), E, 13453 S.PDiag(diag::warn_impcast_integer_precision_constant) 13454 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13455 << E->getSourceRange() << SourceRange(CC)); 13456 return; 13457 } 13458 13459 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 13460 if (S.SourceMgr.isInSystemMacro(CC)) 13461 return; 13462 13463 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 13464 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 13465 /* pruneControlFlow */ true); 13466 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 13467 } 13468 13469 if (TargetRange.Width > SourceTypeRange.Width) { 13470 if (auto *UO = dyn_cast<UnaryOperator>(E)) 13471 if (UO->getOpcode() == UO_Minus) 13472 if (Source->isUnsignedIntegerType()) { 13473 if (Target->isUnsignedIntegerType()) 13474 return DiagnoseImpCast(S, E, T, CC, 13475 diag::warn_impcast_high_order_zero_bits); 13476 if (Target->isSignedIntegerType()) 13477 return DiagnoseImpCast(S, E, T, CC, 13478 diag::warn_impcast_nonnegative_result); 13479 } 13480 } 13481 13482 if (TargetRange.Width == LikelySourceRange.Width && 13483 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 13484 Source->isSignedIntegerType()) { 13485 // Warn when doing a signed to signed conversion, warn if the positive 13486 // source value is exactly the width of the target type, which will 13487 // cause a negative value to be stored. 13488 13489 Expr::EvalResult Result; 13490 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 13491 !S.SourceMgr.isInSystemMacro(CC)) { 13492 llvm::APSInt Value = Result.Val.getInt(); 13493 if (isSameWidthConstantConversion(S, E, T, CC)) { 13494 std::string PrettySourceValue = toString(Value, 10); 13495 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13496 13497 S.DiagRuntimeBehavior( 13498 E->getExprLoc(), E, 13499 S.PDiag(diag::warn_impcast_integer_precision_constant) 13500 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13501 << E->getSourceRange() << SourceRange(CC)); 13502 return; 13503 } 13504 } 13505 13506 // Fall through for non-constants to give a sign conversion warning. 13507 } 13508 13509 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 13510 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 13511 LikelySourceRange.Width == TargetRange.Width)) { 13512 if (S.SourceMgr.isInSystemMacro(CC)) 13513 return; 13514 13515 unsigned DiagID = diag::warn_impcast_integer_sign; 13516 13517 // Traditionally, gcc has warned about this under -Wsign-compare. 13518 // We also want to warn about it in -Wconversion. 13519 // So if -Wconversion is off, use a completely identical diagnostic 13520 // in the sign-compare group. 13521 // The conditional-checking code will 13522 if (ICContext) { 13523 DiagID = diag::warn_impcast_integer_sign_conditional; 13524 *ICContext = true; 13525 } 13526 13527 return DiagnoseImpCast(S, E, T, CC, DiagID); 13528 } 13529 13530 // Diagnose conversions between different enumeration types. 13531 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 13532 // type, to give us better diagnostics. 13533 QualType SourceType = E->getType(); 13534 if (!S.getLangOpts().CPlusPlus) { 13535 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13536 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 13537 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 13538 SourceType = S.Context.getTypeDeclType(Enum); 13539 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 13540 } 13541 } 13542 13543 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 13544 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 13545 if (SourceEnum->getDecl()->hasNameForLinkage() && 13546 TargetEnum->getDecl()->hasNameForLinkage() && 13547 SourceEnum != TargetEnum) { 13548 if (S.SourceMgr.isInSystemMacro(CC)) 13549 return; 13550 13551 return DiagnoseImpCast(S, E, SourceType, T, CC, 13552 diag::warn_impcast_different_enum_types); 13553 } 13554 } 13555 13556 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13557 SourceLocation CC, QualType T); 13558 13559 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 13560 SourceLocation CC, bool &ICContext) { 13561 E = E->IgnoreParenImpCasts(); 13562 13563 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 13564 return CheckConditionalOperator(S, CO, CC, T); 13565 13566 AnalyzeImplicitConversions(S, E, CC); 13567 if (E->getType() != T) 13568 return CheckImplicitConversion(S, E, T, CC, &ICContext); 13569 } 13570 13571 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13572 SourceLocation CC, QualType T) { 13573 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 13574 13575 Expr *TrueExpr = E->getTrueExpr(); 13576 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 13577 TrueExpr = BCO->getCommon(); 13578 13579 bool Suspicious = false; 13580 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 13581 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 13582 13583 if (T->isBooleanType()) 13584 DiagnoseIntInBoolContext(S, E); 13585 13586 // If -Wconversion would have warned about either of the candidates 13587 // for a signedness conversion to the context type... 13588 if (!Suspicious) return; 13589 13590 // ...but it's currently ignored... 13591 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 13592 return; 13593 13594 // ...then check whether it would have warned about either of the 13595 // candidates for a signedness conversion to the condition type. 13596 if (E->getType() == T) return; 13597 13598 Suspicious = false; 13599 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 13600 E->getType(), CC, &Suspicious); 13601 if (!Suspicious) 13602 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 13603 E->getType(), CC, &Suspicious); 13604 } 13605 13606 /// Check conversion of given expression to boolean. 13607 /// Input argument E is a logical expression. 13608 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 13609 if (S.getLangOpts().Bool) 13610 return; 13611 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 13612 return; 13613 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 13614 } 13615 13616 namespace { 13617 struct AnalyzeImplicitConversionsWorkItem { 13618 Expr *E; 13619 SourceLocation CC; 13620 bool IsListInit; 13621 }; 13622 } 13623 13624 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 13625 /// that should be visited are added to WorkList. 13626 static void AnalyzeImplicitConversions( 13627 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 13628 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 13629 Expr *OrigE = Item.E; 13630 SourceLocation CC = Item.CC; 13631 13632 QualType T = OrigE->getType(); 13633 Expr *E = OrigE->IgnoreParenImpCasts(); 13634 13635 // Propagate whether we are in a C++ list initialization expression. 13636 // If so, we do not issue warnings for implicit int-float conversion 13637 // precision loss, because C++11 narrowing already handles it. 13638 bool IsListInit = Item.IsListInit || 13639 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 13640 13641 if (E->isTypeDependent() || E->isValueDependent()) 13642 return; 13643 13644 Expr *SourceExpr = E; 13645 // Examine, but don't traverse into the source expression of an 13646 // OpaqueValueExpr, since it may have multiple parents and we don't want to 13647 // emit duplicate diagnostics. Its fine to examine the form or attempt to 13648 // evaluate it in the context of checking the specific conversion to T though. 13649 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 13650 if (auto *Src = OVE->getSourceExpr()) 13651 SourceExpr = Src; 13652 13653 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 13654 if (UO->getOpcode() == UO_Not && 13655 UO->getSubExpr()->isKnownToHaveBooleanValue()) 13656 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 13657 << OrigE->getSourceRange() << T->isBooleanType() 13658 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 13659 13660 if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) 13661 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) && 13662 BO->getLHS()->isKnownToHaveBooleanValue() && 13663 BO->getRHS()->isKnownToHaveBooleanValue() && 13664 BO->getLHS()->HasSideEffects(S.Context) && 13665 BO->getRHS()->HasSideEffects(S.Context)) { 13666 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical) 13667 << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange() 13668 << FixItHint::CreateReplacement( 13669 BO->getOperatorLoc(), 13670 (BO->getOpcode() == BO_And ? "&&" : "||")); 13671 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int); 13672 } 13673 13674 // For conditional operators, we analyze the arguments as if they 13675 // were being fed directly into the output. 13676 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 13677 CheckConditionalOperator(S, CO, CC, T); 13678 return; 13679 } 13680 13681 // Check implicit argument conversions for function calls. 13682 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 13683 CheckImplicitArgumentConversions(S, Call, CC); 13684 13685 // Go ahead and check any implicit conversions we might have skipped. 13686 // The non-canonical typecheck is just an optimization; 13687 // CheckImplicitConversion will filter out dead implicit conversions. 13688 if (SourceExpr->getType() != T) 13689 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 13690 13691 // Now continue drilling into this expression. 13692 13693 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 13694 // The bound subexpressions in a PseudoObjectExpr are not reachable 13695 // as transitive children. 13696 // FIXME: Use a more uniform representation for this. 13697 for (auto *SE : POE->semantics()) 13698 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 13699 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 13700 } 13701 13702 // Skip past explicit casts. 13703 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 13704 E = CE->getSubExpr()->IgnoreParenImpCasts(); 13705 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 13706 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 13707 WorkList.push_back({E, CC, IsListInit}); 13708 return; 13709 } 13710 13711 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13712 // Do a somewhat different check with comparison operators. 13713 if (BO->isComparisonOp()) 13714 return AnalyzeComparison(S, BO); 13715 13716 // And with simple assignments. 13717 if (BO->getOpcode() == BO_Assign) 13718 return AnalyzeAssignment(S, BO); 13719 // And with compound assignments. 13720 if (BO->isAssignmentOp()) 13721 return AnalyzeCompoundAssignment(S, BO); 13722 } 13723 13724 // These break the otherwise-useful invariant below. Fortunately, 13725 // we don't really need to recurse into them, because any internal 13726 // expressions should have been analyzed already when they were 13727 // built into statements. 13728 if (isa<StmtExpr>(E)) return; 13729 13730 // Don't descend into unevaluated contexts. 13731 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 13732 13733 // Now just recurse over the expression's children. 13734 CC = E->getExprLoc(); 13735 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 13736 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 13737 for (Stmt *SubStmt : E->children()) { 13738 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 13739 if (!ChildExpr) 13740 continue; 13741 13742 if (IsLogicalAndOperator && 13743 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 13744 // Ignore checking string literals that are in logical and operators. 13745 // This is a common pattern for asserts. 13746 continue; 13747 WorkList.push_back({ChildExpr, CC, IsListInit}); 13748 } 13749 13750 if (BO && BO->isLogicalOp()) { 13751 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 13752 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13753 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13754 13755 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 13756 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13757 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13758 } 13759 13760 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 13761 if (U->getOpcode() == UO_LNot) { 13762 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 13763 } else if (U->getOpcode() != UO_AddrOf) { 13764 if (U->getSubExpr()->getType()->isAtomicType()) 13765 S.Diag(U->getSubExpr()->getBeginLoc(), 13766 diag::warn_atomic_implicit_seq_cst); 13767 } 13768 } 13769 } 13770 13771 /// AnalyzeImplicitConversions - Find and report any interesting 13772 /// implicit conversions in the given expression. There are a couple 13773 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 13774 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 13775 bool IsListInit/*= false*/) { 13776 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 13777 WorkList.push_back({OrigE, CC, IsListInit}); 13778 while (!WorkList.empty()) 13779 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 13780 } 13781 13782 /// Diagnose integer type and any valid implicit conversion to it. 13783 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 13784 // Taking into account implicit conversions, 13785 // allow any integer. 13786 if (!E->getType()->isIntegerType()) { 13787 S.Diag(E->getBeginLoc(), 13788 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 13789 return true; 13790 } 13791 // Potentially emit standard warnings for implicit conversions if enabled 13792 // using -Wconversion. 13793 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 13794 return false; 13795 } 13796 13797 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 13798 // Returns true when emitting a warning about taking the address of a reference. 13799 static bool CheckForReference(Sema &SemaRef, const Expr *E, 13800 const PartialDiagnostic &PD) { 13801 E = E->IgnoreParenImpCasts(); 13802 13803 const FunctionDecl *FD = nullptr; 13804 13805 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13806 if (!DRE->getDecl()->getType()->isReferenceType()) 13807 return false; 13808 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13809 if (!M->getMemberDecl()->getType()->isReferenceType()) 13810 return false; 13811 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 13812 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 13813 return false; 13814 FD = Call->getDirectCallee(); 13815 } else { 13816 return false; 13817 } 13818 13819 SemaRef.Diag(E->getExprLoc(), PD); 13820 13821 // If possible, point to location of function. 13822 if (FD) { 13823 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 13824 } 13825 13826 return true; 13827 } 13828 13829 // Returns true if the SourceLocation is expanded from any macro body. 13830 // Returns false if the SourceLocation is invalid, is from not in a macro 13831 // expansion, or is from expanded from a top-level macro argument. 13832 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 13833 if (Loc.isInvalid()) 13834 return false; 13835 13836 while (Loc.isMacroID()) { 13837 if (SM.isMacroBodyExpansion(Loc)) 13838 return true; 13839 Loc = SM.getImmediateMacroCallerLoc(Loc); 13840 } 13841 13842 return false; 13843 } 13844 13845 /// Diagnose pointers that are always non-null. 13846 /// \param E the expression containing the pointer 13847 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 13848 /// compared to a null pointer 13849 /// \param IsEqual True when the comparison is equal to a null pointer 13850 /// \param Range Extra SourceRange to highlight in the diagnostic 13851 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 13852 Expr::NullPointerConstantKind NullKind, 13853 bool IsEqual, SourceRange Range) { 13854 if (!E) 13855 return; 13856 13857 // Don't warn inside macros. 13858 if (E->getExprLoc().isMacroID()) { 13859 const SourceManager &SM = getSourceManager(); 13860 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 13861 IsInAnyMacroBody(SM, Range.getBegin())) 13862 return; 13863 } 13864 E = E->IgnoreImpCasts(); 13865 13866 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 13867 13868 if (isa<CXXThisExpr>(E)) { 13869 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13870 : diag::warn_this_bool_conversion; 13871 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13872 return; 13873 } 13874 13875 bool IsAddressOf = false; 13876 13877 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13878 if (UO->getOpcode() != UO_AddrOf) 13879 return; 13880 IsAddressOf = true; 13881 E = UO->getSubExpr(); 13882 } 13883 13884 if (IsAddressOf) { 13885 unsigned DiagID = IsCompare 13886 ? diag::warn_address_of_reference_null_compare 13887 : diag::warn_address_of_reference_bool_conversion; 13888 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13889 << IsEqual; 13890 if (CheckForReference(*this, E, PD)) { 13891 return; 13892 } 13893 } 13894 13895 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13896 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13897 std::string Str; 13898 llvm::raw_string_ostream S(Str); 13899 E->printPretty(S, nullptr, getPrintingPolicy()); 13900 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13901 : diag::warn_cast_nonnull_to_bool; 13902 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13903 << E->getSourceRange() << Range << IsEqual; 13904 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13905 }; 13906 13907 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13908 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13909 if (auto *Callee = Call->getDirectCallee()) { 13910 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13911 ComplainAboutNonnullParamOrCall(A); 13912 return; 13913 } 13914 } 13915 } 13916 13917 // Expect to find a single Decl. Skip anything more complicated. 13918 ValueDecl *D = nullptr; 13919 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13920 D = R->getDecl(); 13921 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13922 D = M->getMemberDecl(); 13923 } 13924 13925 // Weak Decls can be null. 13926 if (!D || D->isWeak()) 13927 return; 13928 13929 // Check for parameter decl with nonnull attribute 13930 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13931 if (getCurFunction() && 13932 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13933 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13934 ComplainAboutNonnullParamOrCall(A); 13935 return; 13936 } 13937 13938 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13939 // Skip function template not specialized yet. 13940 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13941 return; 13942 auto ParamIter = llvm::find(FD->parameters(), PV); 13943 assert(ParamIter != FD->param_end()); 13944 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13945 13946 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13947 if (!NonNull->args_size()) { 13948 ComplainAboutNonnullParamOrCall(NonNull); 13949 return; 13950 } 13951 13952 for (const ParamIdx &ArgNo : NonNull->args()) { 13953 if (ArgNo.getASTIndex() == ParamNo) { 13954 ComplainAboutNonnullParamOrCall(NonNull); 13955 return; 13956 } 13957 } 13958 } 13959 } 13960 } 13961 } 13962 13963 QualType T = D->getType(); 13964 const bool IsArray = T->isArrayType(); 13965 const bool IsFunction = T->isFunctionType(); 13966 13967 // Address of function is used to silence the function warning. 13968 if (IsAddressOf && IsFunction) { 13969 return; 13970 } 13971 13972 // Found nothing. 13973 if (!IsAddressOf && !IsFunction && !IsArray) 13974 return; 13975 13976 // Pretty print the expression for the diagnostic. 13977 std::string Str; 13978 llvm::raw_string_ostream S(Str); 13979 E->printPretty(S, nullptr, getPrintingPolicy()); 13980 13981 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13982 : diag::warn_impcast_pointer_to_bool; 13983 enum { 13984 AddressOf, 13985 FunctionPointer, 13986 ArrayPointer 13987 } DiagType; 13988 if (IsAddressOf) 13989 DiagType = AddressOf; 13990 else if (IsFunction) 13991 DiagType = FunctionPointer; 13992 else if (IsArray) 13993 DiagType = ArrayPointer; 13994 else 13995 llvm_unreachable("Could not determine diagnostic."); 13996 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13997 << Range << IsEqual; 13998 13999 if (!IsFunction) 14000 return; 14001 14002 // Suggest '&' to silence the function warning. 14003 Diag(E->getExprLoc(), diag::note_function_warning_silence) 14004 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 14005 14006 // Check to see if '()' fixit should be emitted. 14007 QualType ReturnType; 14008 UnresolvedSet<4> NonTemplateOverloads; 14009 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 14010 if (ReturnType.isNull()) 14011 return; 14012 14013 if (IsCompare) { 14014 // There are two cases here. If there is null constant, the only suggest 14015 // for a pointer return type. If the null is 0, then suggest if the return 14016 // type is a pointer or an integer type. 14017 if (!ReturnType->isPointerType()) { 14018 if (NullKind == Expr::NPCK_ZeroExpression || 14019 NullKind == Expr::NPCK_ZeroLiteral) { 14020 if (!ReturnType->isIntegerType()) 14021 return; 14022 } else { 14023 return; 14024 } 14025 } 14026 } else { // !IsCompare 14027 // For function to bool, only suggest if the function pointer has bool 14028 // return type. 14029 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 14030 return; 14031 } 14032 Diag(E->getExprLoc(), diag::note_function_to_function_call) 14033 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 14034 } 14035 14036 /// Diagnoses "dangerous" implicit conversions within the given 14037 /// expression (which is a full expression). Implements -Wconversion 14038 /// and -Wsign-compare. 14039 /// 14040 /// \param CC the "context" location of the implicit conversion, i.e. 14041 /// the most location of the syntactic entity requiring the implicit 14042 /// conversion 14043 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 14044 // Don't diagnose in unevaluated contexts. 14045 if (isUnevaluatedContext()) 14046 return; 14047 14048 // Don't diagnose for value- or type-dependent expressions. 14049 if (E->isTypeDependent() || E->isValueDependent()) 14050 return; 14051 14052 // Check for array bounds violations in cases where the check isn't triggered 14053 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 14054 // ArraySubscriptExpr is on the RHS of a variable initialization. 14055 CheckArrayAccess(E); 14056 14057 // This is not the right CC for (e.g.) a variable initialization. 14058 AnalyzeImplicitConversions(*this, E, CC); 14059 } 14060 14061 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 14062 /// Input argument E is a logical expression. 14063 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 14064 ::CheckBoolLikeConversion(*this, E, CC); 14065 } 14066 14067 /// Diagnose when expression is an integer constant expression and its evaluation 14068 /// results in integer overflow 14069 void Sema::CheckForIntOverflow (Expr *E) { 14070 // Use a work list to deal with nested struct initializers. 14071 SmallVector<Expr *, 2> Exprs(1, E); 14072 14073 do { 14074 Expr *OriginalE = Exprs.pop_back_val(); 14075 Expr *E = OriginalE->IgnoreParenCasts(); 14076 14077 if (isa<BinaryOperator>(E)) { 14078 E->EvaluateForOverflow(Context); 14079 continue; 14080 } 14081 14082 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 14083 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 14084 else if (isa<ObjCBoxedExpr>(OriginalE)) 14085 E->EvaluateForOverflow(Context); 14086 else if (auto Call = dyn_cast<CallExpr>(E)) 14087 Exprs.append(Call->arg_begin(), Call->arg_end()); 14088 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 14089 Exprs.append(Message->arg_begin(), Message->arg_end()); 14090 } while (!Exprs.empty()); 14091 } 14092 14093 namespace { 14094 14095 /// Visitor for expressions which looks for unsequenced operations on the 14096 /// same object. 14097 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 14098 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 14099 14100 /// A tree of sequenced regions within an expression. Two regions are 14101 /// unsequenced if one is an ancestor or a descendent of the other. When we 14102 /// finish processing an expression with sequencing, such as a comma 14103 /// expression, we fold its tree nodes into its parent, since they are 14104 /// unsequenced with respect to nodes we will visit later. 14105 class SequenceTree { 14106 struct Value { 14107 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 14108 unsigned Parent : 31; 14109 unsigned Merged : 1; 14110 }; 14111 SmallVector<Value, 8> Values; 14112 14113 public: 14114 /// A region within an expression which may be sequenced with respect 14115 /// to some other region. 14116 class Seq { 14117 friend class SequenceTree; 14118 14119 unsigned Index; 14120 14121 explicit Seq(unsigned N) : Index(N) {} 14122 14123 public: 14124 Seq() : Index(0) {} 14125 }; 14126 14127 SequenceTree() { Values.push_back(Value(0)); } 14128 Seq root() const { return Seq(0); } 14129 14130 /// Create a new sequence of operations, which is an unsequenced 14131 /// subset of \p Parent. This sequence of operations is sequenced with 14132 /// respect to other children of \p Parent. 14133 Seq allocate(Seq Parent) { 14134 Values.push_back(Value(Parent.Index)); 14135 return Seq(Values.size() - 1); 14136 } 14137 14138 /// Merge a sequence of operations into its parent. 14139 void merge(Seq S) { 14140 Values[S.Index].Merged = true; 14141 } 14142 14143 /// Determine whether two operations are unsequenced. This operation 14144 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 14145 /// should have been merged into its parent as appropriate. 14146 bool isUnsequenced(Seq Cur, Seq Old) { 14147 unsigned C = representative(Cur.Index); 14148 unsigned Target = representative(Old.Index); 14149 while (C >= Target) { 14150 if (C == Target) 14151 return true; 14152 C = Values[C].Parent; 14153 } 14154 return false; 14155 } 14156 14157 private: 14158 /// Pick a representative for a sequence. 14159 unsigned representative(unsigned K) { 14160 if (Values[K].Merged) 14161 // Perform path compression as we go. 14162 return Values[K].Parent = representative(Values[K].Parent); 14163 return K; 14164 } 14165 }; 14166 14167 /// An object for which we can track unsequenced uses. 14168 using Object = const NamedDecl *; 14169 14170 /// Different flavors of object usage which we track. We only track the 14171 /// least-sequenced usage of each kind. 14172 enum UsageKind { 14173 /// A read of an object. Multiple unsequenced reads are OK. 14174 UK_Use, 14175 14176 /// A modification of an object which is sequenced before the value 14177 /// computation of the expression, such as ++n in C++. 14178 UK_ModAsValue, 14179 14180 /// A modification of an object which is not sequenced before the value 14181 /// computation of the expression, such as n++. 14182 UK_ModAsSideEffect, 14183 14184 UK_Count = UK_ModAsSideEffect + 1 14185 }; 14186 14187 /// Bundle together a sequencing region and the expression corresponding 14188 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 14189 struct Usage { 14190 const Expr *UsageExpr; 14191 SequenceTree::Seq Seq; 14192 14193 Usage() : UsageExpr(nullptr) {} 14194 }; 14195 14196 struct UsageInfo { 14197 Usage Uses[UK_Count]; 14198 14199 /// Have we issued a diagnostic for this object already? 14200 bool Diagnosed; 14201 14202 UsageInfo() : Diagnosed(false) {} 14203 }; 14204 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 14205 14206 Sema &SemaRef; 14207 14208 /// Sequenced regions within the expression. 14209 SequenceTree Tree; 14210 14211 /// Declaration modifications and references which we have seen. 14212 UsageInfoMap UsageMap; 14213 14214 /// The region we are currently within. 14215 SequenceTree::Seq Region; 14216 14217 /// Filled in with declarations which were modified as a side-effect 14218 /// (that is, post-increment operations). 14219 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 14220 14221 /// Expressions to check later. We defer checking these to reduce 14222 /// stack usage. 14223 SmallVectorImpl<const Expr *> &WorkList; 14224 14225 /// RAII object wrapping the visitation of a sequenced subexpression of an 14226 /// expression. At the end of this process, the side-effects of the evaluation 14227 /// become sequenced with respect to the value computation of the result, so 14228 /// we downgrade any UK_ModAsSideEffect within the evaluation to 14229 /// UK_ModAsValue. 14230 struct SequencedSubexpression { 14231 SequencedSubexpression(SequenceChecker &Self) 14232 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 14233 Self.ModAsSideEffect = &ModAsSideEffect; 14234 } 14235 14236 ~SequencedSubexpression() { 14237 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 14238 // Add a new usage with usage kind UK_ModAsValue, and then restore 14239 // the previous usage with UK_ModAsSideEffect (thus clearing it if 14240 // the previous one was empty). 14241 UsageInfo &UI = Self.UsageMap[M.first]; 14242 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 14243 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 14244 SideEffectUsage = M.second; 14245 } 14246 Self.ModAsSideEffect = OldModAsSideEffect; 14247 } 14248 14249 SequenceChecker &Self; 14250 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 14251 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 14252 }; 14253 14254 /// RAII object wrapping the visitation of a subexpression which we might 14255 /// choose to evaluate as a constant. If any subexpression is evaluated and 14256 /// found to be non-constant, this allows us to suppress the evaluation of 14257 /// the outer expression. 14258 class EvaluationTracker { 14259 public: 14260 EvaluationTracker(SequenceChecker &Self) 14261 : Self(Self), Prev(Self.EvalTracker) { 14262 Self.EvalTracker = this; 14263 } 14264 14265 ~EvaluationTracker() { 14266 Self.EvalTracker = Prev; 14267 if (Prev) 14268 Prev->EvalOK &= EvalOK; 14269 } 14270 14271 bool evaluate(const Expr *E, bool &Result) { 14272 if (!EvalOK || E->isValueDependent()) 14273 return false; 14274 EvalOK = E->EvaluateAsBooleanCondition( 14275 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 14276 return EvalOK; 14277 } 14278 14279 private: 14280 SequenceChecker &Self; 14281 EvaluationTracker *Prev; 14282 bool EvalOK = true; 14283 } *EvalTracker = nullptr; 14284 14285 /// Find the object which is produced by the specified expression, 14286 /// if any. 14287 Object getObject(const Expr *E, bool Mod) const { 14288 E = E->IgnoreParenCasts(); 14289 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 14290 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 14291 return getObject(UO->getSubExpr(), Mod); 14292 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 14293 if (BO->getOpcode() == BO_Comma) 14294 return getObject(BO->getRHS(), Mod); 14295 if (Mod && BO->isAssignmentOp()) 14296 return getObject(BO->getLHS(), Mod); 14297 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 14298 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 14299 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 14300 return ME->getMemberDecl(); 14301 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 14302 // FIXME: If this is a reference, map through to its value. 14303 return DRE->getDecl(); 14304 return nullptr; 14305 } 14306 14307 /// Note that an object \p O was modified or used by an expression 14308 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 14309 /// the object \p O as obtained via the \p UsageMap. 14310 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 14311 // Get the old usage for the given object and usage kind. 14312 Usage &U = UI.Uses[UK]; 14313 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 14314 // If we have a modification as side effect and are in a sequenced 14315 // subexpression, save the old Usage so that we can restore it later 14316 // in SequencedSubexpression::~SequencedSubexpression. 14317 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 14318 ModAsSideEffect->push_back(std::make_pair(O, U)); 14319 // Then record the new usage with the current sequencing region. 14320 U.UsageExpr = UsageExpr; 14321 U.Seq = Region; 14322 } 14323 } 14324 14325 /// Check whether a modification or use of an object \p O in an expression 14326 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 14327 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 14328 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 14329 /// usage and false we are checking for a mod-use unsequenced usage. 14330 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 14331 UsageKind OtherKind, bool IsModMod) { 14332 if (UI.Diagnosed) 14333 return; 14334 14335 const Usage &U = UI.Uses[OtherKind]; 14336 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 14337 return; 14338 14339 const Expr *Mod = U.UsageExpr; 14340 const Expr *ModOrUse = UsageExpr; 14341 if (OtherKind == UK_Use) 14342 std::swap(Mod, ModOrUse); 14343 14344 SemaRef.DiagRuntimeBehavior( 14345 Mod->getExprLoc(), {Mod, ModOrUse}, 14346 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 14347 : diag::warn_unsequenced_mod_use) 14348 << O << SourceRange(ModOrUse->getExprLoc())); 14349 UI.Diagnosed = true; 14350 } 14351 14352 // A note on note{Pre, Post}{Use, Mod}: 14353 // 14354 // (It helps to follow the algorithm with an expression such as 14355 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 14356 // operations before C++17 and both are well-defined in C++17). 14357 // 14358 // When visiting a node which uses/modify an object we first call notePreUse 14359 // or notePreMod before visiting its sub-expression(s). At this point the 14360 // children of the current node have not yet been visited and so the eventual 14361 // uses/modifications resulting from the children of the current node have not 14362 // been recorded yet. 14363 // 14364 // We then visit the children of the current node. After that notePostUse or 14365 // notePostMod is called. These will 1) detect an unsequenced modification 14366 // as side effect (as in "k++ + k") and 2) add a new usage with the 14367 // appropriate usage kind. 14368 // 14369 // We also have to be careful that some operation sequences modification as 14370 // side effect as well (for example: || or ,). To account for this we wrap 14371 // the visitation of such a sub-expression (for example: the LHS of || or ,) 14372 // with SequencedSubexpression. SequencedSubexpression is an RAII object 14373 // which record usages which are modifications as side effect, and then 14374 // downgrade them (or more accurately restore the previous usage which was a 14375 // modification as side effect) when exiting the scope of the sequenced 14376 // subexpression. 14377 14378 void notePreUse(Object O, const Expr *UseExpr) { 14379 UsageInfo &UI = UsageMap[O]; 14380 // Uses conflict with other modifications. 14381 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 14382 } 14383 14384 void notePostUse(Object O, const Expr *UseExpr) { 14385 UsageInfo &UI = UsageMap[O]; 14386 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 14387 /*IsModMod=*/false); 14388 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 14389 } 14390 14391 void notePreMod(Object O, const Expr *ModExpr) { 14392 UsageInfo &UI = UsageMap[O]; 14393 // Modifications conflict with other modifications and with uses. 14394 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 14395 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 14396 } 14397 14398 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 14399 UsageInfo &UI = UsageMap[O]; 14400 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 14401 /*IsModMod=*/true); 14402 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 14403 } 14404 14405 public: 14406 SequenceChecker(Sema &S, const Expr *E, 14407 SmallVectorImpl<const Expr *> &WorkList) 14408 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 14409 Visit(E); 14410 // Silence a -Wunused-private-field since WorkList is now unused. 14411 // TODO: Evaluate if it can be used, and if not remove it. 14412 (void)this->WorkList; 14413 } 14414 14415 void VisitStmt(const Stmt *S) { 14416 // Skip all statements which aren't expressions for now. 14417 } 14418 14419 void VisitExpr(const Expr *E) { 14420 // By default, just recurse to evaluated subexpressions. 14421 Base::VisitStmt(E); 14422 } 14423 14424 void VisitCastExpr(const CastExpr *E) { 14425 Object O = Object(); 14426 if (E->getCastKind() == CK_LValueToRValue) 14427 O = getObject(E->getSubExpr(), false); 14428 14429 if (O) 14430 notePreUse(O, E); 14431 VisitExpr(E); 14432 if (O) 14433 notePostUse(O, E); 14434 } 14435 14436 void VisitSequencedExpressions(const Expr *SequencedBefore, 14437 const Expr *SequencedAfter) { 14438 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 14439 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 14440 SequenceTree::Seq OldRegion = Region; 14441 14442 { 14443 SequencedSubexpression SeqBefore(*this); 14444 Region = BeforeRegion; 14445 Visit(SequencedBefore); 14446 } 14447 14448 Region = AfterRegion; 14449 Visit(SequencedAfter); 14450 14451 Region = OldRegion; 14452 14453 Tree.merge(BeforeRegion); 14454 Tree.merge(AfterRegion); 14455 } 14456 14457 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 14458 // C++17 [expr.sub]p1: 14459 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 14460 // expression E1 is sequenced before the expression E2. 14461 if (SemaRef.getLangOpts().CPlusPlus17) 14462 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 14463 else { 14464 Visit(ASE->getLHS()); 14465 Visit(ASE->getRHS()); 14466 } 14467 } 14468 14469 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14470 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14471 void VisitBinPtrMem(const BinaryOperator *BO) { 14472 // C++17 [expr.mptr.oper]p4: 14473 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 14474 // the expression E1 is sequenced before the expression E2. 14475 if (SemaRef.getLangOpts().CPlusPlus17) 14476 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14477 else { 14478 Visit(BO->getLHS()); 14479 Visit(BO->getRHS()); 14480 } 14481 } 14482 14483 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14484 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14485 void VisitBinShlShr(const BinaryOperator *BO) { 14486 // C++17 [expr.shift]p4: 14487 // The expression E1 is sequenced before the expression E2. 14488 if (SemaRef.getLangOpts().CPlusPlus17) 14489 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14490 else { 14491 Visit(BO->getLHS()); 14492 Visit(BO->getRHS()); 14493 } 14494 } 14495 14496 void VisitBinComma(const BinaryOperator *BO) { 14497 // C++11 [expr.comma]p1: 14498 // Every value computation and side effect associated with the left 14499 // expression is sequenced before every value computation and side 14500 // effect associated with the right expression. 14501 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14502 } 14503 14504 void VisitBinAssign(const BinaryOperator *BO) { 14505 SequenceTree::Seq RHSRegion; 14506 SequenceTree::Seq LHSRegion; 14507 if (SemaRef.getLangOpts().CPlusPlus17) { 14508 RHSRegion = Tree.allocate(Region); 14509 LHSRegion = Tree.allocate(Region); 14510 } else { 14511 RHSRegion = Region; 14512 LHSRegion = Region; 14513 } 14514 SequenceTree::Seq OldRegion = Region; 14515 14516 // C++11 [expr.ass]p1: 14517 // [...] the assignment is sequenced after the value computation 14518 // of the right and left operands, [...] 14519 // 14520 // so check it before inspecting the operands and update the 14521 // map afterwards. 14522 Object O = getObject(BO->getLHS(), /*Mod=*/true); 14523 if (O) 14524 notePreMod(O, BO); 14525 14526 if (SemaRef.getLangOpts().CPlusPlus17) { 14527 // C++17 [expr.ass]p1: 14528 // [...] The right operand is sequenced before the left operand. [...] 14529 { 14530 SequencedSubexpression SeqBefore(*this); 14531 Region = RHSRegion; 14532 Visit(BO->getRHS()); 14533 } 14534 14535 Region = LHSRegion; 14536 Visit(BO->getLHS()); 14537 14538 if (O && isa<CompoundAssignOperator>(BO)) 14539 notePostUse(O, BO); 14540 14541 } else { 14542 // C++11 does not specify any sequencing between the LHS and RHS. 14543 Region = LHSRegion; 14544 Visit(BO->getLHS()); 14545 14546 if (O && isa<CompoundAssignOperator>(BO)) 14547 notePostUse(O, BO); 14548 14549 Region = RHSRegion; 14550 Visit(BO->getRHS()); 14551 } 14552 14553 // C++11 [expr.ass]p1: 14554 // the assignment is sequenced [...] before the value computation of the 14555 // assignment expression. 14556 // C11 6.5.16/3 has no such rule. 14557 Region = OldRegion; 14558 if (O) 14559 notePostMod(O, BO, 14560 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14561 : UK_ModAsSideEffect); 14562 if (SemaRef.getLangOpts().CPlusPlus17) { 14563 Tree.merge(RHSRegion); 14564 Tree.merge(LHSRegion); 14565 } 14566 } 14567 14568 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 14569 VisitBinAssign(CAO); 14570 } 14571 14572 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14573 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14574 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 14575 Object O = getObject(UO->getSubExpr(), true); 14576 if (!O) 14577 return VisitExpr(UO); 14578 14579 notePreMod(O, UO); 14580 Visit(UO->getSubExpr()); 14581 // C++11 [expr.pre.incr]p1: 14582 // the expression ++x is equivalent to x+=1 14583 notePostMod(O, UO, 14584 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14585 : UK_ModAsSideEffect); 14586 } 14587 14588 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14589 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14590 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 14591 Object O = getObject(UO->getSubExpr(), true); 14592 if (!O) 14593 return VisitExpr(UO); 14594 14595 notePreMod(O, UO); 14596 Visit(UO->getSubExpr()); 14597 notePostMod(O, UO, UK_ModAsSideEffect); 14598 } 14599 14600 void VisitBinLOr(const BinaryOperator *BO) { 14601 // C++11 [expr.log.or]p2: 14602 // If the second expression is evaluated, every value computation and 14603 // side effect associated with the first expression is sequenced before 14604 // every value computation and side effect associated with the 14605 // second expression. 14606 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14607 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14608 SequenceTree::Seq OldRegion = Region; 14609 14610 EvaluationTracker Eval(*this); 14611 { 14612 SequencedSubexpression Sequenced(*this); 14613 Region = LHSRegion; 14614 Visit(BO->getLHS()); 14615 } 14616 14617 // C++11 [expr.log.or]p1: 14618 // [...] the second operand is not evaluated if the first operand 14619 // evaluates to true. 14620 bool EvalResult = false; 14621 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14622 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 14623 if (ShouldVisitRHS) { 14624 Region = RHSRegion; 14625 Visit(BO->getRHS()); 14626 } 14627 14628 Region = OldRegion; 14629 Tree.merge(LHSRegion); 14630 Tree.merge(RHSRegion); 14631 } 14632 14633 void VisitBinLAnd(const BinaryOperator *BO) { 14634 // C++11 [expr.log.and]p2: 14635 // If the second expression is evaluated, every value computation and 14636 // side effect associated with the first expression is sequenced before 14637 // every value computation and side effect associated with the 14638 // second expression. 14639 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14640 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14641 SequenceTree::Seq OldRegion = Region; 14642 14643 EvaluationTracker Eval(*this); 14644 { 14645 SequencedSubexpression Sequenced(*this); 14646 Region = LHSRegion; 14647 Visit(BO->getLHS()); 14648 } 14649 14650 // C++11 [expr.log.and]p1: 14651 // [...] the second operand is not evaluated if the first operand is false. 14652 bool EvalResult = false; 14653 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14654 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 14655 if (ShouldVisitRHS) { 14656 Region = RHSRegion; 14657 Visit(BO->getRHS()); 14658 } 14659 14660 Region = OldRegion; 14661 Tree.merge(LHSRegion); 14662 Tree.merge(RHSRegion); 14663 } 14664 14665 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 14666 // C++11 [expr.cond]p1: 14667 // [...] Every value computation and side effect associated with the first 14668 // expression is sequenced before every value computation and side effect 14669 // associated with the second or third expression. 14670 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 14671 14672 // No sequencing is specified between the true and false expression. 14673 // However since exactly one of both is going to be evaluated we can 14674 // consider them to be sequenced. This is needed to avoid warning on 14675 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 14676 // both the true and false expressions because we can't evaluate x. 14677 // This will still allow us to detect an expression like (pre C++17) 14678 // "(x ? y += 1 : y += 2) = y". 14679 // 14680 // We don't wrap the visitation of the true and false expression with 14681 // SequencedSubexpression because we don't want to downgrade modifications 14682 // as side effect in the true and false expressions after the visition 14683 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 14684 // not warn between the two "y++", but we should warn between the "y++" 14685 // and the "y". 14686 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 14687 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 14688 SequenceTree::Seq OldRegion = Region; 14689 14690 EvaluationTracker Eval(*this); 14691 { 14692 SequencedSubexpression Sequenced(*this); 14693 Region = ConditionRegion; 14694 Visit(CO->getCond()); 14695 } 14696 14697 // C++11 [expr.cond]p1: 14698 // [...] The first expression is contextually converted to bool (Clause 4). 14699 // It is evaluated and if it is true, the result of the conditional 14700 // expression is the value of the second expression, otherwise that of the 14701 // third expression. Only one of the second and third expressions is 14702 // evaluated. [...] 14703 bool EvalResult = false; 14704 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 14705 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 14706 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 14707 if (ShouldVisitTrueExpr) { 14708 Region = TrueRegion; 14709 Visit(CO->getTrueExpr()); 14710 } 14711 if (ShouldVisitFalseExpr) { 14712 Region = FalseRegion; 14713 Visit(CO->getFalseExpr()); 14714 } 14715 14716 Region = OldRegion; 14717 Tree.merge(ConditionRegion); 14718 Tree.merge(TrueRegion); 14719 Tree.merge(FalseRegion); 14720 } 14721 14722 void VisitCallExpr(const CallExpr *CE) { 14723 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 14724 14725 if (CE->isUnevaluatedBuiltinCall(Context)) 14726 return; 14727 14728 // C++11 [intro.execution]p15: 14729 // When calling a function [...], every value computation and side effect 14730 // associated with any argument expression, or with the postfix expression 14731 // designating the called function, is sequenced before execution of every 14732 // expression or statement in the body of the function [and thus before 14733 // the value computation of its result]. 14734 SequencedSubexpression Sequenced(*this); 14735 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 14736 // C++17 [expr.call]p5 14737 // The postfix-expression is sequenced before each expression in the 14738 // expression-list and any default argument. [...] 14739 SequenceTree::Seq CalleeRegion; 14740 SequenceTree::Seq OtherRegion; 14741 if (SemaRef.getLangOpts().CPlusPlus17) { 14742 CalleeRegion = Tree.allocate(Region); 14743 OtherRegion = Tree.allocate(Region); 14744 } else { 14745 CalleeRegion = Region; 14746 OtherRegion = Region; 14747 } 14748 SequenceTree::Seq OldRegion = Region; 14749 14750 // Visit the callee expression first. 14751 Region = CalleeRegion; 14752 if (SemaRef.getLangOpts().CPlusPlus17) { 14753 SequencedSubexpression Sequenced(*this); 14754 Visit(CE->getCallee()); 14755 } else { 14756 Visit(CE->getCallee()); 14757 } 14758 14759 // Then visit the argument expressions. 14760 Region = OtherRegion; 14761 for (const Expr *Argument : CE->arguments()) 14762 Visit(Argument); 14763 14764 Region = OldRegion; 14765 if (SemaRef.getLangOpts().CPlusPlus17) { 14766 Tree.merge(CalleeRegion); 14767 Tree.merge(OtherRegion); 14768 } 14769 }); 14770 } 14771 14772 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 14773 // C++17 [over.match.oper]p2: 14774 // [...] the operator notation is first transformed to the equivalent 14775 // function-call notation as summarized in Table 12 (where @ denotes one 14776 // of the operators covered in the specified subclause). However, the 14777 // operands are sequenced in the order prescribed for the built-in 14778 // operator (Clause 8). 14779 // 14780 // From the above only overloaded binary operators and overloaded call 14781 // operators have sequencing rules in C++17 that we need to handle 14782 // separately. 14783 if (!SemaRef.getLangOpts().CPlusPlus17 || 14784 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 14785 return VisitCallExpr(CXXOCE); 14786 14787 enum { 14788 NoSequencing, 14789 LHSBeforeRHS, 14790 RHSBeforeLHS, 14791 LHSBeforeRest 14792 } SequencingKind; 14793 switch (CXXOCE->getOperator()) { 14794 case OO_Equal: 14795 case OO_PlusEqual: 14796 case OO_MinusEqual: 14797 case OO_StarEqual: 14798 case OO_SlashEqual: 14799 case OO_PercentEqual: 14800 case OO_CaretEqual: 14801 case OO_AmpEqual: 14802 case OO_PipeEqual: 14803 case OO_LessLessEqual: 14804 case OO_GreaterGreaterEqual: 14805 SequencingKind = RHSBeforeLHS; 14806 break; 14807 14808 case OO_LessLess: 14809 case OO_GreaterGreater: 14810 case OO_AmpAmp: 14811 case OO_PipePipe: 14812 case OO_Comma: 14813 case OO_ArrowStar: 14814 case OO_Subscript: 14815 SequencingKind = LHSBeforeRHS; 14816 break; 14817 14818 case OO_Call: 14819 SequencingKind = LHSBeforeRest; 14820 break; 14821 14822 default: 14823 SequencingKind = NoSequencing; 14824 break; 14825 } 14826 14827 if (SequencingKind == NoSequencing) 14828 return VisitCallExpr(CXXOCE); 14829 14830 // This is a call, so all subexpressions are sequenced before the result. 14831 SequencedSubexpression Sequenced(*this); 14832 14833 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 14834 assert(SemaRef.getLangOpts().CPlusPlus17 && 14835 "Should only get there with C++17 and above!"); 14836 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 14837 "Should only get there with an overloaded binary operator" 14838 " or an overloaded call operator!"); 14839 14840 if (SequencingKind == LHSBeforeRest) { 14841 assert(CXXOCE->getOperator() == OO_Call && 14842 "We should only have an overloaded call operator here!"); 14843 14844 // This is very similar to VisitCallExpr, except that we only have the 14845 // C++17 case. The postfix-expression is the first argument of the 14846 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 14847 // are in the following arguments. 14848 // 14849 // Note that we intentionally do not visit the callee expression since 14850 // it is just a decayed reference to a function. 14851 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 14852 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 14853 SequenceTree::Seq OldRegion = Region; 14854 14855 assert(CXXOCE->getNumArgs() >= 1 && 14856 "An overloaded call operator must have at least one argument" 14857 " for the postfix-expression!"); 14858 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 14859 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 14860 CXXOCE->getNumArgs() - 1); 14861 14862 // Visit the postfix-expression first. 14863 { 14864 Region = PostfixExprRegion; 14865 SequencedSubexpression Sequenced(*this); 14866 Visit(PostfixExpr); 14867 } 14868 14869 // Then visit the argument expressions. 14870 Region = ArgsRegion; 14871 for (const Expr *Arg : Args) 14872 Visit(Arg); 14873 14874 Region = OldRegion; 14875 Tree.merge(PostfixExprRegion); 14876 Tree.merge(ArgsRegion); 14877 } else { 14878 assert(CXXOCE->getNumArgs() == 2 && 14879 "Should only have two arguments here!"); 14880 assert((SequencingKind == LHSBeforeRHS || 14881 SequencingKind == RHSBeforeLHS) && 14882 "Unexpected sequencing kind!"); 14883 14884 // We do not visit the callee expression since it is just a decayed 14885 // reference to a function. 14886 const Expr *E1 = CXXOCE->getArg(0); 14887 const Expr *E2 = CXXOCE->getArg(1); 14888 if (SequencingKind == RHSBeforeLHS) 14889 std::swap(E1, E2); 14890 14891 return VisitSequencedExpressions(E1, E2); 14892 } 14893 }); 14894 } 14895 14896 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14897 // This is a call, so all subexpressions are sequenced before the result. 14898 SequencedSubexpression Sequenced(*this); 14899 14900 if (!CCE->isListInitialization()) 14901 return VisitExpr(CCE); 14902 14903 // In C++11, list initializations are sequenced. 14904 SmallVector<SequenceTree::Seq, 32> Elts; 14905 SequenceTree::Seq Parent = Region; 14906 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14907 E = CCE->arg_end(); 14908 I != E; ++I) { 14909 Region = Tree.allocate(Parent); 14910 Elts.push_back(Region); 14911 Visit(*I); 14912 } 14913 14914 // Forget that the initializers are sequenced. 14915 Region = Parent; 14916 for (unsigned I = 0; I < Elts.size(); ++I) 14917 Tree.merge(Elts[I]); 14918 } 14919 14920 void VisitInitListExpr(const InitListExpr *ILE) { 14921 if (!SemaRef.getLangOpts().CPlusPlus11) 14922 return VisitExpr(ILE); 14923 14924 // In C++11, list initializations are sequenced. 14925 SmallVector<SequenceTree::Seq, 32> Elts; 14926 SequenceTree::Seq Parent = Region; 14927 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14928 const Expr *E = ILE->getInit(I); 14929 if (!E) 14930 continue; 14931 Region = Tree.allocate(Parent); 14932 Elts.push_back(Region); 14933 Visit(E); 14934 } 14935 14936 // Forget that the initializers are sequenced. 14937 Region = Parent; 14938 for (unsigned I = 0; I < Elts.size(); ++I) 14939 Tree.merge(Elts[I]); 14940 } 14941 }; 14942 14943 } // namespace 14944 14945 void Sema::CheckUnsequencedOperations(const Expr *E) { 14946 SmallVector<const Expr *, 8> WorkList; 14947 WorkList.push_back(E); 14948 while (!WorkList.empty()) { 14949 const Expr *Item = WorkList.pop_back_val(); 14950 SequenceChecker(*this, Item, WorkList); 14951 } 14952 } 14953 14954 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14955 bool IsConstexpr) { 14956 llvm::SaveAndRestore<bool> ConstantContext( 14957 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14958 CheckImplicitConversions(E, CheckLoc); 14959 if (!E->isInstantiationDependent()) 14960 CheckUnsequencedOperations(E); 14961 if (!IsConstexpr && !E->isValueDependent()) 14962 CheckForIntOverflow(E); 14963 DiagnoseMisalignedMembers(); 14964 } 14965 14966 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14967 FieldDecl *BitField, 14968 Expr *Init) { 14969 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14970 } 14971 14972 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14973 SourceLocation Loc) { 14974 if (!PType->isVariablyModifiedType()) 14975 return; 14976 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14977 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14978 return; 14979 } 14980 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14981 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14982 return; 14983 } 14984 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14985 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14986 return; 14987 } 14988 14989 const ArrayType *AT = S.Context.getAsArrayType(PType); 14990 if (!AT) 14991 return; 14992 14993 if (AT->getSizeModifier() != ArrayType::Star) { 14994 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14995 return; 14996 } 14997 14998 S.Diag(Loc, diag::err_array_star_in_function_definition); 14999 } 15000 15001 /// CheckParmsForFunctionDef - Check that the parameters of the given 15002 /// function are appropriate for the definition of a function. This 15003 /// takes care of any checks that cannot be performed on the 15004 /// declaration itself, e.g., that the types of each of the function 15005 /// parameters are complete. 15006 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 15007 bool CheckParameterNames) { 15008 bool HasInvalidParm = false; 15009 for (ParmVarDecl *Param : Parameters) { 15010 // C99 6.7.5.3p4: the parameters in a parameter type list in a 15011 // function declarator that is part of a function definition of 15012 // that function shall not have incomplete type. 15013 // 15014 // This is also C++ [dcl.fct]p6. 15015 if (!Param->isInvalidDecl() && 15016 RequireCompleteType(Param->getLocation(), Param->getType(), 15017 diag::err_typecheck_decl_incomplete_type)) { 15018 Param->setInvalidDecl(); 15019 HasInvalidParm = true; 15020 } 15021 15022 // C99 6.9.1p5: If the declarator includes a parameter type list, the 15023 // declaration of each parameter shall include an identifier. 15024 if (CheckParameterNames && Param->getIdentifier() == nullptr && 15025 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 15026 // Diagnose this as an extension in C17 and earlier. 15027 if (!getLangOpts().C2x) 15028 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 15029 } 15030 15031 // C99 6.7.5.3p12: 15032 // If the function declarator is not part of a definition of that 15033 // function, parameters may have incomplete type and may use the [*] 15034 // notation in their sequences of declarator specifiers to specify 15035 // variable length array types. 15036 QualType PType = Param->getOriginalType(); 15037 // FIXME: This diagnostic should point the '[*]' if source-location 15038 // information is added for it. 15039 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 15040 15041 // If the parameter is a c++ class type and it has to be destructed in the 15042 // callee function, declare the destructor so that it can be called by the 15043 // callee function. Do not perform any direct access check on the dtor here. 15044 if (!Param->isInvalidDecl()) { 15045 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 15046 if (!ClassDecl->isInvalidDecl() && 15047 !ClassDecl->hasIrrelevantDestructor() && 15048 !ClassDecl->isDependentContext() && 15049 ClassDecl->isParamDestroyedInCallee()) { 15050 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 15051 MarkFunctionReferenced(Param->getLocation(), Destructor); 15052 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 15053 } 15054 } 15055 } 15056 15057 // Parameters with the pass_object_size attribute only need to be marked 15058 // constant at function definitions. Because we lack information about 15059 // whether we're on a declaration or definition when we're instantiating the 15060 // attribute, we need to check for constness here. 15061 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 15062 if (!Param->getType().isConstQualified()) 15063 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 15064 << Attr->getSpelling() << 1; 15065 15066 // Check for parameter names shadowing fields from the class. 15067 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 15068 // The owning context for the parameter should be the function, but we 15069 // want to see if this function's declaration context is a record. 15070 DeclContext *DC = Param->getDeclContext(); 15071 if (DC && DC->isFunctionOrMethod()) { 15072 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 15073 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 15074 RD, /*DeclIsField*/ false); 15075 } 15076 } 15077 } 15078 15079 return HasInvalidParm; 15080 } 15081 15082 Optional<std::pair<CharUnits, CharUnits>> 15083 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 15084 15085 /// Compute the alignment and offset of the base class object given the 15086 /// derived-to-base cast expression and the alignment and offset of the derived 15087 /// class object. 15088 static std::pair<CharUnits, CharUnits> 15089 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 15090 CharUnits BaseAlignment, CharUnits Offset, 15091 ASTContext &Ctx) { 15092 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 15093 ++PathI) { 15094 const CXXBaseSpecifier *Base = *PathI; 15095 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 15096 if (Base->isVirtual()) { 15097 // The complete object may have a lower alignment than the non-virtual 15098 // alignment of the base, in which case the base may be misaligned. Choose 15099 // the smaller of the non-virtual alignment and BaseAlignment, which is a 15100 // conservative lower bound of the complete object alignment. 15101 CharUnits NonVirtualAlignment = 15102 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 15103 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 15104 Offset = CharUnits::Zero(); 15105 } else { 15106 const ASTRecordLayout &RL = 15107 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 15108 Offset += RL.getBaseClassOffset(BaseDecl); 15109 } 15110 DerivedType = Base->getType(); 15111 } 15112 15113 return std::make_pair(BaseAlignment, Offset); 15114 } 15115 15116 /// Compute the alignment and offset of a binary additive operator. 15117 static Optional<std::pair<CharUnits, CharUnits>> 15118 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 15119 bool IsSub, ASTContext &Ctx) { 15120 QualType PointeeType = PtrE->getType()->getPointeeType(); 15121 15122 if (!PointeeType->isConstantSizeType()) 15123 return llvm::None; 15124 15125 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 15126 15127 if (!P) 15128 return llvm::None; 15129 15130 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 15131 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 15132 CharUnits Offset = EltSize * IdxRes->getExtValue(); 15133 if (IsSub) 15134 Offset = -Offset; 15135 return std::make_pair(P->first, P->second + Offset); 15136 } 15137 15138 // If the integer expression isn't a constant expression, compute the lower 15139 // bound of the alignment using the alignment and offset of the pointer 15140 // expression and the element size. 15141 return std::make_pair( 15142 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 15143 CharUnits::Zero()); 15144 } 15145 15146 /// This helper function takes an lvalue expression and returns the alignment of 15147 /// a VarDecl and a constant offset from the VarDecl. 15148 Optional<std::pair<CharUnits, CharUnits>> 15149 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 15150 E = E->IgnoreParens(); 15151 switch (E->getStmtClass()) { 15152 default: 15153 break; 15154 case Stmt::CStyleCastExprClass: 15155 case Stmt::CXXStaticCastExprClass: 15156 case Stmt::ImplicitCastExprClass: { 15157 auto *CE = cast<CastExpr>(E); 15158 const Expr *From = CE->getSubExpr(); 15159 switch (CE->getCastKind()) { 15160 default: 15161 break; 15162 case CK_NoOp: 15163 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 15164 case CK_UncheckedDerivedToBase: 15165 case CK_DerivedToBase: { 15166 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 15167 if (!P) 15168 break; 15169 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 15170 P->second, Ctx); 15171 } 15172 } 15173 break; 15174 } 15175 case Stmt::ArraySubscriptExprClass: { 15176 auto *ASE = cast<ArraySubscriptExpr>(E); 15177 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 15178 false, Ctx); 15179 } 15180 case Stmt::DeclRefExprClass: { 15181 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 15182 // FIXME: If VD is captured by copy or is an escaping __block variable, 15183 // use the alignment of VD's type. 15184 if (!VD->getType()->isReferenceType()) 15185 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 15186 if (VD->hasInit()) 15187 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 15188 } 15189 break; 15190 } 15191 case Stmt::MemberExprClass: { 15192 auto *ME = cast<MemberExpr>(E); 15193 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 15194 if (!FD || FD->getType()->isReferenceType() || 15195 FD->getParent()->isInvalidDecl()) 15196 break; 15197 Optional<std::pair<CharUnits, CharUnits>> P; 15198 if (ME->isArrow()) 15199 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 15200 else 15201 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 15202 if (!P) 15203 break; 15204 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 15205 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 15206 return std::make_pair(P->first, 15207 P->second + CharUnits::fromQuantity(Offset)); 15208 } 15209 case Stmt::UnaryOperatorClass: { 15210 auto *UO = cast<UnaryOperator>(E); 15211 switch (UO->getOpcode()) { 15212 default: 15213 break; 15214 case UO_Deref: 15215 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 15216 } 15217 break; 15218 } 15219 case Stmt::BinaryOperatorClass: { 15220 auto *BO = cast<BinaryOperator>(E); 15221 auto Opcode = BO->getOpcode(); 15222 switch (Opcode) { 15223 default: 15224 break; 15225 case BO_Comma: 15226 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 15227 } 15228 break; 15229 } 15230 } 15231 return llvm::None; 15232 } 15233 15234 /// This helper function takes a pointer expression and returns the alignment of 15235 /// a VarDecl and a constant offset from the VarDecl. 15236 Optional<std::pair<CharUnits, CharUnits>> 15237 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 15238 E = E->IgnoreParens(); 15239 switch (E->getStmtClass()) { 15240 default: 15241 break; 15242 case Stmt::CStyleCastExprClass: 15243 case Stmt::CXXStaticCastExprClass: 15244 case Stmt::ImplicitCastExprClass: { 15245 auto *CE = cast<CastExpr>(E); 15246 const Expr *From = CE->getSubExpr(); 15247 switch (CE->getCastKind()) { 15248 default: 15249 break; 15250 case CK_NoOp: 15251 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 15252 case CK_ArrayToPointerDecay: 15253 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 15254 case CK_UncheckedDerivedToBase: 15255 case CK_DerivedToBase: { 15256 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 15257 if (!P) 15258 break; 15259 return getDerivedToBaseAlignmentAndOffset( 15260 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 15261 } 15262 } 15263 break; 15264 } 15265 case Stmt::CXXThisExprClass: { 15266 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 15267 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 15268 return std::make_pair(Alignment, CharUnits::Zero()); 15269 } 15270 case Stmt::UnaryOperatorClass: { 15271 auto *UO = cast<UnaryOperator>(E); 15272 if (UO->getOpcode() == UO_AddrOf) 15273 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 15274 break; 15275 } 15276 case Stmt::BinaryOperatorClass: { 15277 auto *BO = cast<BinaryOperator>(E); 15278 auto Opcode = BO->getOpcode(); 15279 switch (Opcode) { 15280 default: 15281 break; 15282 case BO_Add: 15283 case BO_Sub: { 15284 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 15285 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 15286 std::swap(LHS, RHS); 15287 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 15288 Ctx); 15289 } 15290 case BO_Comma: 15291 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 15292 } 15293 break; 15294 } 15295 } 15296 return llvm::None; 15297 } 15298 15299 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 15300 // See if we can compute the alignment of a VarDecl and an offset from it. 15301 Optional<std::pair<CharUnits, CharUnits>> P = 15302 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 15303 15304 if (P) 15305 return P->first.alignmentAtOffset(P->second); 15306 15307 // If that failed, return the type's alignment. 15308 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 15309 } 15310 15311 /// CheckCastAlign - Implements -Wcast-align, which warns when a 15312 /// pointer cast increases the alignment requirements. 15313 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 15314 // This is actually a lot of work to potentially be doing on every 15315 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 15316 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 15317 return; 15318 15319 // Ignore dependent types. 15320 if (T->isDependentType() || Op->getType()->isDependentType()) 15321 return; 15322 15323 // Require that the destination be a pointer type. 15324 const PointerType *DestPtr = T->getAs<PointerType>(); 15325 if (!DestPtr) return; 15326 15327 // If the destination has alignment 1, we're done. 15328 QualType DestPointee = DestPtr->getPointeeType(); 15329 if (DestPointee->isIncompleteType()) return; 15330 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 15331 if (DestAlign.isOne()) return; 15332 15333 // Require that the source be a pointer type. 15334 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 15335 if (!SrcPtr) return; 15336 QualType SrcPointee = SrcPtr->getPointeeType(); 15337 15338 // Explicitly allow casts from cv void*. We already implicitly 15339 // allowed casts to cv void*, since they have alignment 1. 15340 // Also allow casts involving incomplete types, which implicitly 15341 // includes 'void'. 15342 if (SrcPointee->isIncompleteType()) return; 15343 15344 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 15345 15346 if (SrcAlign >= DestAlign) return; 15347 15348 Diag(TRange.getBegin(), diag::warn_cast_align) 15349 << Op->getType() << T 15350 << static_cast<unsigned>(SrcAlign.getQuantity()) 15351 << static_cast<unsigned>(DestAlign.getQuantity()) 15352 << TRange << Op->getSourceRange(); 15353 } 15354 15355 /// Check whether this array fits the idiom of a size-one tail padded 15356 /// array member of a struct. 15357 /// 15358 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 15359 /// commonly used to emulate flexible arrays in C89 code. 15360 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 15361 const NamedDecl *ND) { 15362 if (Size != 1 || !ND) return false; 15363 15364 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 15365 if (!FD) return false; 15366 15367 // Don't consider sizes resulting from macro expansions or template argument 15368 // substitution to form C89 tail-padded arrays. 15369 15370 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 15371 while (TInfo) { 15372 TypeLoc TL = TInfo->getTypeLoc(); 15373 // Look through typedefs. 15374 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 15375 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 15376 TInfo = TDL->getTypeSourceInfo(); 15377 continue; 15378 } 15379 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 15380 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 15381 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 15382 return false; 15383 } 15384 break; 15385 } 15386 15387 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 15388 if (!RD) return false; 15389 if (RD->isUnion()) return false; 15390 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15391 if (!CRD->isStandardLayout()) return false; 15392 } 15393 15394 // See if this is the last field decl in the record. 15395 const Decl *D = FD; 15396 while ((D = D->getNextDeclInContext())) 15397 if (isa<FieldDecl>(D)) 15398 return false; 15399 return true; 15400 } 15401 15402 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 15403 const ArraySubscriptExpr *ASE, 15404 bool AllowOnePastEnd, bool IndexNegated) { 15405 // Already diagnosed by the constant evaluator. 15406 if (isConstantEvaluated()) 15407 return; 15408 15409 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 15410 if (IndexExpr->isValueDependent()) 15411 return; 15412 15413 const Type *EffectiveType = 15414 BaseExpr->getType()->getPointeeOrArrayElementType(); 15415 BaseExpr = BaseExpr->IgnoreParenCasts(); 15416 const ConstantArrayType *ArrayTy = 15417 Context.getAsConstantArrayType(BaseExpr->getType()); 15418 15419 const Type *BaseType = 15420 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 15421 bool IsUnboundedArray = (BaseType == nullptr); 15422 if (EffectiveType->isDependentType() || 15423 (!IsUnboundedArray && BaseType->isDependentType())) 15424 return; 15425 15426 Expr::EvalResult Result; 15427 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 15428 return; 15429 15430 llvm::APSInt index = Result.Val.getInt(); 15431 if (IndexNegated) { 15432 index.setIsUnsigned(false); 15433 index = -index; 15434 } 15435 15436 const NamedDecl *ND = nullptr; 15437 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15438 ND = DRE->getDecl(); 15439 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 15440 ND = ME->getMemberDecl(); 15441 15442 if (IsUnboundedArray) { 15443 if (index.isUnsigned() || !index.isNegative()) { 15444 const auto &ASTC = getASTContext(); 15445 unsigned AddrBits = 15446 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 15447 EffectiveType->getCanonicalTypeInternal())); 15448 if (index.getBitWidth() < AddrBits) 15449 index = index.zext(AddrBits); 15450 Optional<CharUnits> ElemCharUnits = 15451 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 15452 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 15453 // pointer) bounds-checking isn't meaningful. 15454 if (!ElemCharUnits) 15455 return; 15456 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 15457 // If index has more active bits than address space, we already know 15458 // we have a bounds violation to warn about. Otherwise, compute 15459 // address of (index + 1)th element, and warn about bounds violation 15460 // only if that address exceeds address space. 15461 if (index.getActiveBits() <= AddrBits) { 15462 bool Overflow; 15463 llvm::APInt Product(index); 15464 Product += 1; 15465 Product = Product.umul_ov(ElemBytes, Overflow); 15466 if (!Overflow && Product.getActiveBits() <= AddrBits) 15467 return; 15468 } 15469 15470 // Need to compute max possible elements in address space, since that 15471 // is included in diag message. 15472 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 15473 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 15474 MaxElems += 1; 15475 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 15476 MaxElems = MaxElems.udiv(ElemBytes); 15477 15478 unsigned DiagID = 15479 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 15480 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 15481 15482 // Diag message shows element size in bits and in "bytes" (platform- 15483 // dependent CharUnits) 15484 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15485 PDiag(DiagID) 15486 << toString(index, 10, true) << AddrBits 15487 << (unsigned)ASTC.toBits(*ElemCharUnits) 15488 << toString(ElemBytes, 10, false) 15489 << toString(MaxElems, 10, false) 15490 << (unsigned)MaxElems.getLimitedValue(~0U) 15491 << IndexExpr->getSourceRange()); 15492 15493 if (!ND) { 15494 // Try harder to find a NamedDecl to point at in the note. 15495 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15496 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15497 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15498 ND = DRE->getDecl(); 15499 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15500 ND = ME->getMemberDecl(); 15501 } 15502 15503 if (ND) 15504 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15505 PDiag(diag::note_array_declared_here) << ND); 15506 } 15507 return; 15508 } 15509 15510 if (index.isUnsigned() || !index.isNegative()) { 15511 // It is possible that the type of the base expression after 15512 // IgnoreParenCasts is incomplete, even though the type of the base 15513 // expression before IgnoreParenCasts is complete (see PR39746 for an 15514 // example). In this case we have no information about whether the array 15515 // access exceeds the array bounds. However we can still diagnose an array 15516 // access which precedes the array bounds. 15517 if (BaseType->isIncompleteType()) 15518 return; 15519 15520 llvm::APInt size = ArrayTy->getSize(); 15521 if (!size.isStrictlyPositive()) 15522 return; 15523 15524 if (BaseType != EffectiveType) { 15525 // Make sure we're comparing apples to apples when comparing index to size 15526 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 15527 uint64_t array_typesize = Context.getTypeSize(BaseType); 15528 // Handle ptrarith_typesize being zero, such as when casting to void* 15529 if (!ptrarith_typesize) ptrarith_typesize = 1; 15530 if (ptrarith_typesize != array_typesize) { 15531 // There's a cast to a different size type involved 15532 uint64_t ratio = array_typesize / ptrarith_typesize; 15533 // TODO: Be smarter about handling cases where array_typesize is not a 15534 // multiple of ptrarith_typesize 15535 if (ptrarith_typesize * ratio == array_typesize) 15536 size *= llvm::APInt(size.getBitWidth(), ratio); 15537 } 15538 } 15539 15540 if (size.getBitWidth() > index.getBitWidth()) 15541 index = index.zext(size.getBitWidth()); 15542 else if (size.getBitWidth() < index.getBitWidth()) 15543 size = size.zext(index.getBitWidth()); 15544 15545 // For array subscripting the index must be less than size, but for pointer 15546 // arithmetic also allow the index (offset) to be equal to size since 15547 // computing the next address after the end of the array is legal and 15548 // commonly done e.g. in C++ iterators and range-based for loops. 15549 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 15550 return; 15551 15552 // Also don't warn for arrays of size 1 which are members of some 15553 // structure. These are often used to approximate flexible arrays in C89 15554 // code. 15555 if (IsTailPaddedMemberArray(*this, size, ND)) 15556 return; 15557 15558 // Suppress the warning if the subscript expression (as identified by the 15559 // ']' location) and the index expression are both from macro expansions 15560 // within a system header. 15561 if (ASE) { 15562 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 15563 ASE->getRBracketLoc()); 15564 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 15565 SourceLocation IndexLoc = 15566 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 15567 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 15568 return; 15569 } 15570 } 15571 15572 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 15573 : diag::warn_ptr_arith_exceeds_bounds; 15574 15575 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15576 PDiag(DiagID) << toString(index, 10, true) 15577 << toString(size, 10, true) 15578 << (unsigned)size.getLimitedValue(~0U) 15579 << IndexExpr->getSourceRange()); 15580 } else { 15581 unsigned DiagID = diag::warn_array_index_precedes_bounds; 15582 if (!ASE) { 15583 DiagID = diag::warn_ptr_arith_precedes_bounds; 15584 if (index.isNegative()) index = -index; 15585 } 15586 15587 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15588 PDiag(DiagID) << toString(index, 10, true) 15589 << IndexExpr->getSourceRange()); 15590 } 15591 15592 if (!ND) { 15593 // Try harder to find a NamedDecl to point at in the note. 15594 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15595 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15596 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15597 ND = DRE->getDecl(); 15598 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15599 ND = ME->getMemberDecl(); 15600 } 15601 15602 if (ND) 15603 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15604 PDiag(diag::note_array_declared_here) << ND); 15605 } 15606 15607 void Sema::CheckArrayAccess(const Expr *expr) { 15608 int AllowOnePastEnd = 0; 15609 while (expr) { 15610 expr = expr->IgnoreParenImpCasts(); 15611 switch (expr->getStmtClass()) { 15612 case Stmt::ArraySubscriptExprClass: { 15613 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 15614 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 15615 AllowOnePastEnd > 0); 15616 expr = ASE->getBase(); 15617 break; 15618 } 15619 case Stmt::MemberExprClass: { 15620 expr = cast<MemberExpr>(expr)->getBase(); 15621 break; 15622 } 15623 case Stmt::OMPArraySectionExprClass: { 15624 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 15625 if (ASE->getLowerBound()) 15626 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 15627 /*ASE=*/nullptr, AllowOnePastEnd > 0); 15628 return; 15629 } 15630 case Stmt::UnaryOperatorClass: { 15631 // Only unwrap the * and & unary operators 15632 const UnaryOperator *UO = cast<UnaryOperator>(expr); 15633 expr = UO->getSubExpr(); 15634 switch (UO->getOpcode()) { 15635 case UO_AddrOf: 15636 AllowOnePastEnd++; 15637 break; 15638 case UO_Deref: 15639 AllowOnePastEnd--; 15640 break; 15641 default: 15642 return; 15643 } 15644 break; 15645 } 15646 case Stmt::ConditionalOperatorClass: { 15647 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 15648 if (const Expr *lhs = cond->getLHS()) 15649 CheckArrayAccess(lhs); 15650 if (const Expr *rhs = cond->getRHS()) 15651 CheckArrayAccess(rhs); 15652 return; 15653 } 15654 case Stmt::CXXOperatorCallExprClass: { 15655 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 15656 for (const auto *Arg : OCE->arguments()) 15657 CheckArrayAccess(Arg); 15658 return; 15659 } 15660 default: 15661 return; 15662 } 15663 } 15664 } 15665 15666 //===--- CHECK: Objective-C retain cycles ----------------------------------// 15667 15668 namespace { 15669 15670 struct RetainCycleOwner { 15671 VarDecl *Variable = nullptr; 15672 SourceRange Range; 15673 SourceLocation Loc; 15674 bool Indirect = false; 15675 15676 RetainCycleOwner() = default; 15677 15678 void setLocsFrom(Expr *e) { 15679 Loc = e->getExprLoc(); 15680 Range = e->getSourceRange(); 15681 } 15682 }; 15683 15684 } // namespace 15685 15686 /// Consider whether capturing the given variable can possibly lead to 15687 /// a retain cycle. 15688 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 15689 // In ARC, it's captured strongly iff the variable has __strong 15690 // lifetime. In MRR, it's captured strongly if the variable is 15691 // __block and has an appropriate type. 15692 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15693 return false; 15694 15695 owner.Variable = var; 15696 if (ref) 15697 owner.setLocsFrom(ref); 15698 return true; 15699 } 15700 15701 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 15702 while (true) { 15703 e = e->IgnoreParens(); 15704 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 15705 switch (cast->getCastKind()) { 15706 case CK_BitCast: 15707 case CK_LValueBitCast: 15708 case CK_LValueToRValue: 15709 case CK_ARCReclaimReturnedObject: 15710 e = cast->getSubExpr(); 15711 continue; 15712 15713 default: 15714 return false; 15715 } 15716 } 15717 15718 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 15719 ObjCIvarDecl *ivar = ref->getDecl(); 15720 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15721 return false; 15722 15723 // Try to find a retain cycle in the base. 15724 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 15725 return false; 15726 15727 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 15728 owner.Indirect = true; 15729 return true; 15730 } 15731 15732 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 15733 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 15734 if (!var) return false; 15735 return considerVariable(var, ref, owner); 15736 } 15737 15738 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 15739 if (member->isArrow()) return false; 15740 15741 // Don't count this as an indirect ownership. 15742 e = member->getBase(); 15743 continue; 15744 } 15745 15746 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 15747 // Only pay attention to pseudo-objects on property references. 15748 ObjCPropertyRefExpr *pre 15749 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 15750 ->IgnoreParens()); 15751 if (!pre) return false; 15752 if (pre->isImplicitProperty()) return false; 15753 ObjCPropertyDecl *property = pre->getExplicitProperty(); 15754 if (!property->isRetaining() && 15755 !(property->getPropertyIvarDecl() && 15756 property->getPropertyIvarDecl()->getType() 15757 .getObjCLifetime() == Qualifiers::OCL_Strong)) 15758 return false; 15759 15760 owner.Indirect = true; 15761 if (pre->isSuperReceiver()) { 15762 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 15763 if (!owner.Variable) 15764 return false; 15765 owner.Loc = pre->getLocation(); 15766 owner.Range = pre->getSourceRange(); 15767 return true; 15768 } 15769 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 15770 ->getSourceExpr()); 15771 continue; 15772 } 15773 15774 // Array ivars? 15775 15776 return false; 15777 } 15778 } 15779 15780 namespace { 15781 15782 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 15783 ASTContext &Context; 15784 VarDecl *Variable; 15785 Expr *Capturer = nullptr; 15786 bool VarWillBeReased = false; 15787 15788 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 15789 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 15790 Context(Context), Variable(variable) {} 15791 15792 void VisitDeclRefExpr(DeclRefExpr *ref) { 15793 if (ref->getDecl() == Variable && !Capturer) 15794 Capturer = ref; 15795 } 15796 15797 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 15798 if (Capturer) return; 15799 Visit(ref->getBase()); 15800 if (Capturer && ref->isFreeIvar()) 15801 Capturer = ref; 15802 } 15803 15804 void VisitBlockExpr(BlockExpr *block) { 15805 // Look inside nested blocks 15806 if (block->getBlockDecl()->capturesVariable(Variable)) 15807 Visit(block->getBlockDecl()->getBody()); 15808 } 15809 15810 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 15811 if (Capturer) return; 15812 if (OVE->getSourceExpr()) 15813 Visit(OVE->getSourceExpr()); 15814 } 15815 15816 void VisitBinaryOperator(BinaryOperator *BinOp) { 15817 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 15818 return; 15819 Expr *LHS = BinOp->getLHS(); 15820 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 15821 if (DRE->getDecl() != Variable) 15822 return; 15823 if (Expr *RHS = BinOp->getRHS()) { 15824 RHS = RHS->IgnoreParenCasts(); 15825 Optional<llvm::APSInt> Value; 15826 VarWillBeReased = 15827 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 15828 *Value == 0); 15829 } 15830 } 15831 } 15832 }; 15833 15834 } // namespace 15835 15836 /// Check whether the given argument is a block which captures a 15837 /// variable. 15838 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 15839 assert(owner.Variable && owner.Loc.isValid()); 15840 15841 e = e->IgnoreParenCasts(); 15842 15843 // Look through [^{...} copy] and Block_copy(^{...}). 15844 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 15845 Selector Cmd = ME->getSelector(); 15846 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 15847 e = ME->getInstanceReceiver(); 15848 if (!e) 15849 return nullptr; 15850 e = e->IgnoreParenCasts(); 15851 } 15852 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 15853 if (CE->getNumArgs() == 1) { 15854 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 15855 if (Fn) { 15856 const IdentifierInfo *FnI = Fn->getIdentifier(); 15857 if (FnI && FnI->isStr("_Block_copy")) { 15858 e = CE->getArg(0)->IgnoreParenCasts(); 15859 } 15860 } 15861 } 15862 } 15863 15864 BlockExpr *block = dyn_cast<BlockExpr>(e); 15865 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 15866 return nullptr; 15867 15868 FindCaptureVisitor visitor(S.Context, owner.Variable); 15869 visitor.Visit(block->getBlockDecl()->getBody()); 15870 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15871 } 15872 15873 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15874 RetainCycleOwner &owner) { 15875 assert(capturer); 15876 assert(owner.Variable && owner.Loc.isValid()); 15877 15878 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15879 << owner.Variable << capturer->getSourceRange(); 15880 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15881 << owner.Indirect << owner.Range; 15882 } 15883 15884 /// Check for a keyword selector that starts with the word 'add' or 15885 /// 'set'. 15886 static bool isSetterLikeSelector(Selector sel) { 15887 if (sel.isUnarySelector()) return false; 15888 15889 StringRef str = sel.getNameForSlot(0); 15890 while (!str.empty() && str.front() == '_') str = str.substr(1); 15891 if (str.startswith("set")) 15892 str = str.substr(3); 15893 else if (str.startswith("add")) { 15894 // Specially allow 'addOperationWithBlock:'. 15895 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15896 return false; 15897 str = str.substr(3); 15898 } 15899 else 15900 return false; 15901 15902 if (str.empty()) return true; 15903 return !isLowercase(str.front()); 15904 } 15905 15906 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15907 ObjCMessageExpr *Message) { 15908 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15909 Message->getReceiverInterface(), 15910 NSAPI::ClassId_NSMutableArray); 15911 if (!IsMutableArray) { 15912 return None; 15913 } 15914 15915 Selector Sel = Message->getSelector(); 15916 15917 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15918 S.NSAPIObj->getNSArrayMethodKind(Sel); 15919 if (!MKOpt) { 15920 return None; 15921 } 15922 15923 NSAPI::NSArrayMethodKind MK = *MKOpt; 15924 15925 switch (MK) { 15926 case NSAPI::NSMutableArr_addObject: 15927 case NSAPI::NSMutableArr_insertObjectAtIndex: 15928 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15929 return 0; 15930 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15931 return 1; 15932 15933 default: 15934 return None; 15935 } 15936 15937 return None; 15938 } 15939 15940 static 15941 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15942 ObjCMessageExpr *Message) { 15943 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15944 Message->getReceiverInterface(), 15945 NSAPI::ClassId_NSMutableDictionary); 15946 if (!IsMutableDictionary) { 15947 return None; 15948 } 15949 15950 Selector Sel = Message->getSelector(); 15951 15952 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 15953 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 15954 if (!MKOpt) { 15955 return None; 15956 } 15957 15958 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 15959 15960 switch (MK) { 15961 case NSAPI::NSMutableDict_setObjectForKey: 15962 case NSAPI::NSMutableDict_setValueForKey: 15963 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 15964 return 0; 15965 15966 default: 15967 return None; 15968 } 15969 15970 return None; 15971 } 15972 15973 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 15974 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 15975 Message->getReceiverInterface(), 15976 NSAPI::ClassId_NSMutableSet); 15977 15978 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 15979 Message->getReceiverInterface(), 15980 NSAPI::ClassId_NSMutableOrderedSet); 15981 if (!IsMutableSet && !IsMutableOrderedSet) { 15982 return None; 15983 } 15984 15985 Selector Sel = Message->getSelector(); 15986 15987 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15988 if (!MKOpt) { 15989 return None; 15990 } 15991 15992 NSAPI::NSSetMethodKind MK = *MKOpt; 15993 15994 switch (MK) { 15995 case NSAPI::NSMutableSet_addObject: 15996 case NSAPI::NSOrderedSet_setObjectAtIndex: 15997 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15998 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15999 return 0; 16000 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 16001 return 1; 16002 } 16003 16004 return None; 16005 } 16006 16007 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 16008 if (!Message->isInstanceMessage()) { 16009 return; 16010 } 16011 16012 Optional<int> ArgOpt; 16013 16014 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 16015 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 16016 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 16017 return; 16018 } 16019 16020 int ArgIndex = *ArgOpt; 16021 16022 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 16023 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 16024 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 16025 } 16026 16027 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 16028 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 16029 if (ArgRE->isObjCSelfExpr()) { 16030 Diag(Message->getSourceRange().getBegin(), 16031 diag::warn_objc_circular_container) 16032 << ArgRE->getDecl() << StringRef("'super'"); 16033 } 16034 } 16035 } else { 16036 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 16037 16038 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 16039 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 16040 } 16041 16042 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 16043 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 16044 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 16045 ValueDecl *Decl = ReceiverRE->getDecl(); 16046 Diag(Message->getSourceRange().getBegin(), 16047 diag::warn_objc_circular_container) 16048 << Decl << Decl; 16049 if (!ArgRE->isObjCSelfExpr()) { 16050 Diag(Decl->getLocation(), 16051 diag::note_objc_circular_container_declared_here) 16052 << Decl; 16053 } 16054 } 16055 } 16056 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 16057 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 16058 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 16059 ObjCIvarDecl *Decl = IvarRE->getDecl(); 16060 Diag(Message->getSourceRange().getBegin(), 16061 diag::warn_objc_circular_container) 16062 << Decl << Decl; 16063 Diag(Decl->getLocation(), 16064 diag::note_objc_circular_container_declared_here) 16065 << Decl; 16066 } 16067 } 16068 } 16069 } 16070 } 16071 16072 /// Check a message send to see if it's likely to cause a retain cycle. 16073 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 16074 // Only check instance methods whose selector looks like a setter. 16075 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 16076 return; 16077 16078 // Try to find a variable that the receiver is strongly owned by. 16079 RetainCycleOwner owner; 16080 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 16081 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 16082 return; 16083 } else { 16084 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 16085 owner.Variable = getCurMethodDecl()->getSelfDecl(); 16086 owner.Loc = msg->getSuperLoc(); 16087 owner.Range = msg->getSuperLoc(); 16088 } 16089 16090 // Check whether the receiver is captured by any of the arguments. 16091 const ObjCMethodDecl *MD = msg->getMethodDecl(); 16092 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 16093 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 16094 // noescape blocks should not be retained by the method. 16095 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 16096 continue; 16097 return diagnoseRetainCycle(*this, capturer, owner); 16098 } 16099 } 16100 } 16101 16102 /// Check a property assign to see if it's likely to cause a retain cycle. 16103 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 16104 RetainCycleOwner owner; 16105 if (!findRetainCycleOwner(*this, receiver, owner)) 16106 return; 16107 16108 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 16109 diagnoseRetainCycle(*this, capturer, owner); 16110 } 16111 16112 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 16113 RetainCycleOwner Owner; 16114 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 16115 return; 16116 16117 // Because we don't have an expression for the variable, we have to set the 16118 // location explicitly here. 16119 Owner.Loc = Var->getLocation(); 16120 Owner.Range = Var->getSourceRange(); 16121 16122 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 16123 diagnoseRetainCycle(*this, Capturer, Owner); 16124 } 16125 16126 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 16127 Expr *RHS, bool isProperty) { 16128 // Check if RHS is an Objective-C object literal, which also can get 16129 // immediately zapped in a weak reference. Note that we explicitly 16130 // allow ObjCStringLiterals, since those are designed to never really die. 16131 RHS = RHS->IgnoreParenImpCasts(); 16132 16133 // This enum needs to match with the 'select' in 16134 // warn_objc_arc_literal_assign (off-by-1). 16135 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 16136 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 16137 return false; 16138 16139 S.Diag(Loc, diag::warn_arc_literal_assign) 16140 << (unsigned) Kind 16141 << (isProperty ? 0 : 1) 16142 << RHS->getSourceRange(); 16143 16144 return true; 16145 } 16146 16147 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 16148 Qualifiers::ObjCLifetime LT, 16149 Expr *RHS, bool isProperty) { 16150 // Strip off any implicit cast added to get to the one ARC-specific. 16151 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 16152 if (cast->getCastKind() == CK_ARCConsumeObject) { 16153 S.Diag(Loc, diag::warn_arc_retained_assign) 16154 << (LT == Qualifiers::OCL_ExplicitNone) 16155 << (isProperty ? 0 : 1) 16156 << RHS->getSourceRange(); 16157 return true; 16158 } 16159 RHS = cast->getSubExpr(); 16160 } 16161 16162 if (LT == Qualifiers::OCL_Weak && 16163 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 16164 return true; 16165 16166 return false; 16167 } 16168 16169 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 16170 QualType LHS, Expr *RHS) { 16171 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 16172 16173 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 16174 return false; 16175 16176 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 16177 return true; 16178 16179 return false; 16180 } 16181 16182 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 16183 Expr *LHS, Expr *RHS) { 16184 QualType LHSType; 16185 // PropertyRef on LHS type need be directly obtained from 16186 // its declaration as it has a PseudoType. 16187 ObjCPropertyRefExpr *PRE 16188 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 16189 if (PRE && !PRE->isImplicitProperty()) { 16190 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 16191 if (PD) 16192 LHSType = PD->getType(); 16193 } 16194 16195 if (LHSType.isNull()) 16196 LHSType = LHS->getType(); 16197 16198 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 16199 16200 if (LT == Qualifiers::OCL_Weak) { 16201 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 16202 getCurFunction()->markSafeWeakUse(LHS); 16203 } 16204 16205 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 16206 return; 16207 16208 // FIXME. Check for other life times. 16209 if (LT != Qualifiers::OCL_None) 16210 return; 16211 16212 if (PRE) { 16213 if (PRE->isImplicitProperty()) 16214 return; 16215 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 16216 if (!PD) 16217 return; 16218 16219 unsigned Attributes = PD->getPropertyAttributes(); 16220 if (Attributes & ObjCPropertyAttribute::kind_assign) { 16221 // when 'assign' attribute was not explicitly specified 16222 // by user, ignore it and rely on property type itself 16223 // for lifetime info. 16224 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 16225 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 16226 LHSType->isObjCRetainableType()) 16227 return; 16228 16229 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 16230 if (cast->getCastKind() == CK_ARCConsumeObject) { 16231 Diag(Loc, diag::warn_arc_retained_property_assign) 16232 << RHS->getSourceRange(); 16233 return; 16234 } 16235 RHS = cast->getSubExpr(); 16236 } 16237 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 16238 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 16239 return; 16240 } 16241 } 16242 } 16243 16244 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 16245 16246 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 16247 SourceLocation StmtLoc, 16248 const NullStmt *Body) { 16249 // Do not warn if the body is a macro that expands to nothing, e.g: 16250 // 16251 // #define CALL(x) 16252 // if (condition) 16253 // CALL(0); 16254 if (Body->hasLeadingEmptyMacro()) 16255 return false; 16256 16257 // Get line numbers of statement and body. 16258 bool StmtLineInvalid; 16259 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 16260 &StmtLineInvalid); 16261 if (StmtLineInvalid) 16262 return false; 16263 16264 bool BodyLineInvalid; 16265 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 16266 &BodyLineInvalid); 16267 if (BodyLineInvalid) 16268 return false; 16269 16270 // Warn if null statement and body are on the same line. 16271 if (StmtLine != BodyLine) 16272 return false; 16273 16274 return true; 16275 } 16276 16277 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 16278 const Stmt *Body, 16279 unsigned DiagID) { 16280 // Since this is a syntactic check, don't emit diagnostic for template 16281 // instantiations, this just adds noise. 16282 if (CurrentInstantiationScope) 16283 return; 16284 16285 // The body should be a null statement. 16286 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 16287 if (!NBody) 16288 return; 16289 16290 // Do the usual checks. 16291 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 16292 return; 16293 16294 Diag(NBody->getSemiLoc(), DiagID); 16295 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 16296 } 16297 16298 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 16299 const Stmt *PossibleBody) { 16300 assert(!CurrentInstantiationScope); // Ensured by caller 16301 16302 SourceLocation StmtLoc; 16303 const Stmt *Body; 16304 unsigned DiagID; 16305 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 16306 StmtLoc = FS->getRParenLoc(); 16307 Body = FS->getBody(); 16308 DiagID = diag::warn_empty_for_body; 16309 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 16310 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 16311 Body = WS->getBody(); 16312 DiagID = diag::warn_empty_while_body; 16313 } else 16314 return; // Neither `for' nor `while'. 16315 16316 // The body should be a null statement. 16317 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 16318 if (!NBody) 16319 return; 16320 16321 // Skip expensive checks if diagnostic is disabled. 16322 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 16323 return; 16324 16325 // Do the usual checks. 16326 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 16327 return; 16328 16329 // `for(...);' and `while(...);' are popular idioms, so in order to keep 16330 // noise level low, emit diagnostics only if for/while is followed by a 16331 // CompoundStmt, e.g.: 16332 // for (int i = 0; i < n; i++); 16333 // { 16334 // a(i); 16335 // } 16336 // or if for/while is followed by a statement with more indentation 16337 // than for/while itself: 16338 // for (int i = 0; i < n; i++); 16339 // a(i); 16340 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 16341 if (!ProbableTypo) { 16342 bool BodyColInvalid; 16343 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 16344 PossibleBody->getBeginLoc(), &BodyColInvalid); 16345 if (BodyColInvalid) 16346 return; 16347 16348 bool StmtColInvalid; 16349 unsigned StmtCol = 16350 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 16351 if (StmtColInvalid) 16352 return; 16353 16354 if (BodyCol > StmtCol) 16355 ProbableTypo = true; 16356 } 16357 16358 if (ProbableTypo) { 16359 Diag(NBody->getSemiLoc(), DiagID); 16360 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 16361 } 16362 } 16363 16364 //===--- CHECK: Warn on self move with std::move. -------------------------===// 16365 16366 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 16367 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 16368 SourceLocation OpLoc) { 16369 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 16370 return; 16371 16372 if (inTemplateInstantiation()) 16373 return; 16374 16375 // Strip parens and casts away. 16376 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 16377 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 16378 16379 // Check for a call expression 16380 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 16381 if (!CE || CE->getNumArgs() != 1) 16382 return; 16383 16384 // Check for a call to std::move 16385 if (!CE->isCallToStdMove()) 16386 return; 16387 16388 // Get argument from std::move 16389 RHSExpr = CE->getArg(0); 16390 16391 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 16392 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 16393 16394 // Two DeclRefExpr's, check that the decls are the same. 16395 if (LHSDeclRef && RHSDeclRef) { 16396 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16397 return; 16398 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16399 RHSDeclRef->getDecl()->getCanonicalDecl()) 16400 return; 16401 16402 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16403 << LHSExpr->getSourceRange() 16404 << RHSExpr->getSourceRange(); 16405 return; 16406 } 16407 16408 // Member variables require a different approach to check for self moves. 16409 // MemberExpr's are the same if every nested MemberExpr refers to the same 16410 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 16411 // the base Expr's are CXXThisExpr's. 16412 const Expr *LHSBase = LHSExpr; 16413 const Expr *RHSBase = RHSExpr; 16414 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 16415 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 16416 if (!LHSME || !RHSME) 16417 return; 16418 16419 while (LHSME && RHSME) { 16420 if (LHSME->getMemberDecl()->getCanonicalDecl() != 16421 RHSME->getMemberDecl()->getCanonicalDecl()) 16422 return; 16423 16424 LHSBase = LHSME->getBase(); 16425 RHSBase = RHSME->getBase(); 16426 LHSME = dyn_cast<MemberExpr>(LHSBase); 16427 RHSME = dyn_cast<MemberExpr>(RHSBase); 16428 } 16429 16430 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 16431 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 16432 if (LHSDeclRef && RHSDeclRef) { 16433 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16434 return; 16435 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16436 RHSDeclRef->getDecl()->getCanonicalDecl()) 16437 return; 16438 16439 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16440 << LHSExpr->getSourceRange() 16441 << RHSExpr->getSourceRange(); 16442 return; 16443 } 16444 16445 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 16446 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16447 << LHSExpr->getSourceRange() 16448 << RHSExpr->getSourceRange(); 16449 } 16450 16451 //===--- Layout compatibility ----------------------------------------------// 16452 16453 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 16454 16455 /// Check if two enumeration types are layout-compatible. 16456 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 16457 // C++11 [dcl.enum] p8: 16458 // Two enumeration types are layout-compatible if they have the same 16459 // underlying type. 16460 return ED1->isComplete() && ED2->isComplete() && 16461 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 16462 } 16463 16464 /// Check if two fields are layout-compatible. 16465 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 16466 FieldDecl *Field2) { 16467 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 16468 return false; 16469 16470 if (Field1->isBitField() != Field2->isBitField()) 16471 return false; 16472 16473 if (Field1->isBitField()) { 16474 // Make sure that the bit-fields are the same length. 16475 unsigned Bits1 = Field1->getBitWidthValue(C); 16476 unsigned Bits2 = Field2->getBitWidthValue(C); 16477 16478 if (Bits1 != Bits2) 16479 return false; 16480 } 16481 16482 return true; 16483 } 16484 16485 /// Check if two standard-layout structs are layout-compatible. 16486 /// (C++11 [class.mem] p17) 16487 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 16488 RecordDecl *RD2) { 16489 // If both records are C++ classes, check that base classes match. 16490 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 16491 // If one of records is a CXXRecordDecl we are in C++ mode, 16492 // thus the other one is a CXXRecordDecl, too. 16493 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 16494 // Check number of base classes. 16495 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 16496 return false; 16497 16498 // Check the base classes. 16499 for (CXXRecordDecl::base_class_const_iterator 16500 Base1 = D1CXX->bases_begin(), 16501 BaseEnd1 = D1CXX->bases_end(), 16502 Base2 = D2CXX->bases_begin(); 16503 Base1 != BaseEnd1; 16504 ++Base1, ++Base2) { 16505 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 16506 return false; 16507 } 16508 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 16509 // If only RD2 is a C++ class, it should have zero base classes. 16510 if (D2CXX->getNumBases() > 0) 16511 return false; 16512 } 16513 16514 // Check the fields. 16515 RecordDecl::field_iterator Field2 = RD2->field_begin(), 16516 Field2End = RD2->field_end(), 16517 Field1 = RD1->field_begin(), 16518 Field1End = RD1->field_end(); 16519 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 16520 if (!isLayoutCompatible(C, *Field1, *Field2)) 16521 return false; 16522 } 16523 if (Field1 != Field1End || Field2 != Field2End) 16524 return false; 16525 16526 return true; 16527 } 16528 16529 /// Check if two standard-layout unions are layout-compatible. 16530 /// (C++11 [class.mem] p18) 16531 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 16532 RecordDecl *RD2) { 16533 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 16534 for (auto *Field2 : RD2->fields()) 16535 UnmatchedFields.insert(Field2); 16536 16537 for (auto *Field1 : RD1->fields()) { 16538 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 16539 I = UnmatchedFields.begin(), 16540 E = UnmatchedFields.end(); 16541 16542 for ( ; I != E; ++I) { 16543 if (isLayoutCompatible(C, Field1, *I)) { 16544 bool Result = UnmatchedFields.erase(*I); 16545 (void) Result; 16546 assert(Result); 16547 break; 16548 } 16549 } 16550 if (I == E) 16551 return false; 16552 } 16553 16554 return UnmatchedFields.empty(); 16555 } 16556 16557 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 16558 RecordDecl *RD2) { 16559 if (RD1->isUnion() != RD2->isUnion()) 16560 return false; 16561 16562 if (RD1->isUnion()) 16563 return isLayoutCompatibleUnion(C, RD1, RD2); 16564 else 16565 return isLayoutCompatibleStruct(C, RD1, RD2); 16566 } 16567 16568 /// Check if two types are layout-compatible in C++11 sense. 16569 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 16570 if (T1.isNull() || T2.isNull()) 16571 return false; 16572 16573 // C++11 [basic.types] p11: 16574 // If two types T1 and T2 are the same type, then T1 and T2 are 16575 // layout-compatible types. 16576 if (C.hasSameType(T1, T2)) 16577 return true; 16578 16579 T1 = T1.getCanonicalType().getUnqualifiedType(); 16580 T2 = T2.getCanonicalType().getUnqualifiedType(); 16581 16582 const Type::TypeClass TC1 = T1->getTypeClass(); 16583 const Type::TypeClass TC2 = T2->getTypeClass(); 16584 16585 if (TC1 != TC2) 16586 return false; 16587 16588 if (TC1 == Type::Enum) { 16589 return isLayoutCompatible(C, 16590 cast<EnumType>(T1)->getDecl(), 16591 cast<EnumType>(T2)->getDecl()); 16592 } else if (TC1 == Type::Record) { 16593 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 16594 return false; 16595 16596 return isLayoutCompatible(C, 16597 cast<RecordType>(T1)->getDecl(), 16598 cast<RecordType>(T2)->getDecl()); 16599 } 16600 16601 return false; 16602 } 16603 16604 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 16605 16606 /// Given a type tag expression find the type tag itself. 16607 /// 16608 /// \param TypeExpr Type tag expression, as it appears in user's code. 16609 /// 16610 /// \param VD Declaration of an identifier that appears in a type tag. 16611 /// 16612 /// \param MagicValue Type tag magic value. 16613 /// 16614 /// \param isConstantEvaluated whether the evalaution should be performed in 16615 16616 /// constant context. 16617 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 16618 const ValueDecl **VD, uint64_t *MagicValue, 16619 bool isConstantEvaluated) { 16620 while(true) { 16621 if (!TypeExpr) 16622 return false; 16623 16624 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 16625 16626 switch (TypeExpr->getStmtClass()) { 16627 case Stmt::UnaryOperatorClass: { 16628 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 16629 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 16630 TypeExpr = UO->getSubExpr(); 16631 continue; 16632 } 16633 return false; 16634 } 16635 16636 case Stmt::DeclRefExprClass: { 16637 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 16638 *VD = DRE->getDecl(); 16639 return true; 16640 } 16641 16642 case Stmt::IntegerLiteralClass: { 16643 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 16644 llvm::APInt MagicValueAPInt = IL->getValue(); 16645 if (MagicValueAPInt.getActiveBits() <= 64) { 16646 *MagicValue = MagicValueAPInt.getZExtValue(); 16647 return true; 16648 } else 16649 return false; 16650 } 16651 16652 case Stmt::BinaryConditionalOperatorClass: 16653 case Stmt::ConditionalOperatorClass: { 16654 const AbstractConditionalOperator *ACO = 16655 cast<AbstractConditionalOperator>(TypeExpr); 16656 bool Result; 16657 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 16658 isConstantEvaluated)) { 16659 if (Result) 16660 TypeExpr = ACO->getTrueExpr(); 16661 else 16662 TypeExpr = ACO->getFalseExpr(); 16663 continue; 16664 } 16665 return false; 16666 } 16667 16668 case Stmt::BinaryOperatorClass: { 16669 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 16670 if (BO->getOpcode() == BO_Comma) { 16671 TypeExpr = BO->getRHS(); 16672 continue; 16673 } 16674 return false; 16675 } 16676 16677 default: 16678 return false; 16679 } 16680 } 16681 } 16682 16683 /// Retrieve the C type corresponding to type tag TypeExpr. 16684 /// 16685 /// \param TypeExpr Expression that specifies a type tag. 16686 /// 16687 /// \param MagicValues Registered magic values. 16688 /// 16689 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 16690 /// kind. 16691 /// 16692 /// \param TypeInfo Information about the corresponding C type. 16693 /// 16694 /// \param isConstantEvaluated whether the evalaution should be performed in 16695 /// constant context. 16696 /// 16697 /// \returns true if the corresponding C type was found. 16698 static bool GetMatchingCType( 16699 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 16700 const ASTContext &Ctx, 16701 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 16702 *MagicValues, 16703 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 16704 bool isConstantEvaluated) { 16705 FoundWrongKind = false; 16706 16707 // Variable declaration that has type_tag_for_datatype attribute. 16708 const ValueDecl *VD = nullptr; 16709 16710 uint64_t MagicValue; 16711 16712 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 16713 return false; 16714 16715 if (VD) { 16716 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 16717 if (I->getArgumentKind() != ArgumentKind) { 16718 FoundWrongKind = true; 16719 return false; 16720 } 16721 TypeInfo.Type = I->getMatchingCType(); 16722 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 16723 TypeInfo.MustBeNull = I->getMustBeNull(); 16724 return true; 16725 } 16726 return false; 16727 } 16728 16729 if (!MagicValues) 16730 return false; 16731 16732 llvm::DenseMap<Sema::TypeTagMagicValue, 16733 Sema::TypeTagData>::const_iterator I = 16734 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 16735 if (I == MagicValues->end()) 16736 return false; 16737 16738 TypeInfo = I->second; 16739 return true; 16740 } 16741 16742 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 16743 uint64_t MagicValue, QualType Type, 16744 bool LayoutCompatible, 16745 bool MustBeNull) { 16746 if (!TypeTagForDatatypeMagicValues) 16747 TypeTagForDatatypeMagicValues.reset( 16748 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 16749 16750 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 16751 (*TypeTagForDatatypeMagicValues)[Magic] = 16752 TypeTagData(Type, LayoutCompatible, MustBeNull); 16753 } 16754 16755 static bool IsSameCharType(QualType T1, QualType T2) { 16756 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 16757 if (!BT1) 16758 return false; 16759 16760 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 16761 if (!BT2) 16762 return false; 16763 16764 BuiltinType::Kind T1Kind = BT1->getKind(); 16765 BuiltinType::Kind T2Kind = BT2->getKind(); 16766 16767 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 16768 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 16769 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 16770 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 16771 } 16772 16773 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 16774 const ArrayRef<const Expr *> ExprArgs, 16775 SourceLocation CallSiteLoc) { 16776 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 16777 bool IsPointerAttr = Attr->getIsPointer(); 16778 16779 // Retrieve the argument representing the 'type_tag'. 16780 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 16781 if (TypeTagIdxAST >= ExprArgs.size()) { 16782 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16783 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 16784 return; 16785 } 16786 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 16787 bool FoundWrongKind; 16788 TypeTagData TypeInfo; 16789 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 16790 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 16791 TypeInfo, isConstantEvaluated())) { 16792 if (FoundWrongKind) 16793 Diag(TypeTagExpr->getExprLoc(), 16794 diag::warn_type_tag_for_datatype_wrong_kind) 16795 << TypeTagExpr->getSourceRange(); 16796 return; 16797 } 16798 16799 // Retrieve the argument representing the 'arg_idx'. 16800 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 16801 if (ArgumentIdxAST >= ExprArgs.size()) { 16802 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16803 << 1 << Attr->getArgumentIdx().getSourceIndex(); 16804 return; 16805 } 16806 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 16807 if (IsPointerAttr) { 16808 // Skip implicit cast of pointer to `void *' (as a function argument). 16809 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 16810 if (ICE->getType()->isVoidPointerType() && 16811 ICE->getCastKind() == CK_BitCast) 16812 ArgumentExpr = ICE->getSubExpr(); 16813 } 16814 QualType ArgumentType = ArgumentExpr->getType(); 16815 16816 // Passing a `void*' pointer shouldn't trigger a warning. 16817 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 16818 return; 16819 16820 if (TypeInfo.MustBeNull) { 16821 // Type tag with matching void type requires a null pointer. 16822 if (!ArgumentExpr->isNullPointerConstant(Context, 16823 Expr::NPC_ValueDependentIsNotNull)) { 16824 Diag(ArgumentExpr->getExprLoc(), 16825 diag::warn_type_safety_null_pointer_required) 16826 << ArgumentKind->getName() 16827 << ArgumentExpr->getSourceRange() 16828 << TypeTagExpr->getSourceRange(); 16829 } 16830 return; 16831 } 16832 16833 QualType RequiredType = TypeInfo.Type; 16834 if (IsPointerAttr) 16835 RequiredType = Context.getPointerType(RequiredType); 16836 16837 bool mismatch = false; 16838 if (!TypeInfo.LayoutCompatible) { 16839 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 16840 16841 // C++11 [basic.fundamental] p1: 16842 // Plain char, signed char, and unsigned char are three distinct types. 16843 // 16844 // But we treat plain `char' as equivalent to `signed char' or `unsigned 16845 // char' depending on the current char signedness mode. 16846 if (mismatch) 16847 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 16848 RequiredType->getPointeeType())) || 16849 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 16850 mismatch = false; 16851 } else 16852 if (IsPointerAttr) 16853 mismatch = !isLayoutCompatible(Context, 16854 ArgumentType->getPointeeType(), 16855 RequiredType->getPointeeType()); 16856 else 16857 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 16858 16859 if (mismatch) 16860 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 16861 << ArgumentType << ArgumentKind 16862 << TypeInfo.LayoutCompatible << RequiredType 16863 << ArgumentExpr->getSourceRange() 16864 << TypeTagExpr->getSourceRange(); 16865 } 16866 16867 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 16868 CharUnits Alignment) { 16869 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16870 } 16871 16872 void Sema::DiagnoseMisalignedMembers() { 16873 for (MisalignedMember &m : MisalignedMembers) { 16874 const NamedDecl *ND = m.RD; 16875 if (ND->getName().empty()) { 16876 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16877 ND = TD; 16878 } 16879 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16880 << m.MD << ND << m.E->getSourceRange(); 16881 } 16882 MisalignedMembers.clear(); 16883 } 16884 16885 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16886 E = E->IgnoreParens(); 16887 if (!T->isPointerType() && !T->isIntegerType()) 16888 return; 16889 if (isa<UnaryOperator>(E) && 16890 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16891 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16892 if (isa<MemberExpr>(Op)) { 16893 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16894 if (MA != MisalignedMembers.end() && 16895 (T->isIntegerType() || 16896 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16897 Context.getTypeAlignInChars( 16898 T->getPointeeType()) <= MA->Alignment)))) 16899 MisalignedMembers.erase(MA); 16900 } 16901 } 16902 } 16903 16904 void Sema::RefersToMemberWithReducedAlignment( 16905 Expr *E, 16906 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16907 Action) { 16908 const auto *ME = dyn_cast<MemberExpr>(E); 16909 if (!ME) 16910 return; 16911 16912 // No need to check expressions with an __unaligned-qualified type. 16913 if (E->getType().getQualifiers().hasUnaligned()) 16914 return; 16915 16916 // For a chain of MemberExpr like "a.b.c.d" this list 16917 // will keep FieldDecl's like [d, c, b]. 16918 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16919 const MemberExpr *TopME = nullptr; 16920 bool AnyIsPacked = false; 16921 do { 16922 QualType BaseType = ME->getBase()->getType(); 16923 if (BaseType->isDependentType()) 16924 return; 16925 if (ME->isArrow()) 16926 BaseType = BaseType->getPointeeType(); 16927 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16928 if (RD->isInvalidDecl()) 16929 return; 16930 16931 ValueDecl *MD = ME->getMemberDecl(); 16932 auto *FD = dyn_cast<FieldDecl>(MD); 16933 // We do not care about non-data members. 16934 if (!FD || FD->isInvalidDecl()) 16935 return; 16936 16937 AnyIsPacked = 16938 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16939 ReverseMemberChain.push_back(FD); 16940 16941 TopME = ME; 16942 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16943 } while (ME); 16944 assert(TopME && "We did not compute a topmost MemberExpr!"); 16945 16946 // Not the scope of this diagnostic. 16947 if (!AnyIsPacked) 16948 return; 16949 16950 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 16951 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 16952 // TODO: The innermost base of the member expression may be too complicated. 16953 // For now, just disregard these cases. This is left for future 16954 // improvement. 16955 if (!DRE && !isa<CXXThisExpr>(TopBase)) 16956 return; 16957 16958 // Alignment expected by the whole expression. 16959 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 16960 16961 // No need to do anything else with this case. 16962 if (ExpectedAlignment.isOne()) 16963 return; 16964 16965 // Synthesize offset of the whole access. 16966 CharUnits Offset; 16967 for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain)) 16968 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD)); 16969 16970 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 16971 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 16972 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 16973 16974 // The base expression of the innermost MemberExpr may give 16975 // stronger guarantees than the class containing the member. 16976 if (DRE && !TopME->isArrow()) { 16977 const ValueDecl *VD = DRE->getDecl(); 16978 if (!VD->getType()->isReferenceType()) 16979 CompleteObjectAlignment = 16980 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 16981 } 16982 16983 // Check if the synthesized offset fulfills the alignment. 16984 if (Offset % ExpectedAlignment != 0 || 16985 // It may fulfill the offset it but the effective alignment may still be 16986 // lower than the expected expression alignment. 16987 CompleteObjectAlignment < ExpectedAlignment) { 16988 // If this happens, we want to determine a sensible culprit of this. 16989 // Intuitively, watching the chain of member expressions from right to 16990 // left, we start with the required alignment (as required by the field 16991 // type) but some packed attribute in that chain has reduced the alignment. 16992 // It may happen that another packed structure increases it again. But if 16993 // we are here such increase has not been enough. So pointing the first 16994 // FieldDecl that either is packed or else its RecordDecl is, 16995 // seems reasonable. 16996 FieldDecl *FD = nullptr; 16997 CharUnits Alignment; 16998 for (FieldDecl *FDI : ReverseMemberChain) { 16999 if (FDI->hasAttr<PackedAttr>() || 17000 FDI->getParent()->hasAttr<PackedAttr>()) { 17001 FD = FDI; 17002 Alignment = std::min( 17003 Context.getTypeAlignInChars(FD->getType()), 17004 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 17005 break; 17006 } 17007 } 17008 assert(FD && "We did not find a packed FieldDecl!"); 17009 Action(E, FD->getParent(), FD, Alignment); 17010 } 17011 } 17012 17013 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 17014 using namespace std::placeholders; 17015 17016 RefersToMemberWithReducedAlignment( 17017 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 17018 _2, _3, _4)); 17019 } 17020 17021 // Check if \p Ty is a valid type for the elementwise math builtins. If it is 17022 // not a valid type, emit an error message and return true. Otherwise return 17023 // false. 17024 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, 17025 QualType Ty) { 17026 if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) { 17027 S.Diag(Loc, diag::err_builtin_invalid_arg_type) 17028 << 1 << /* vector, integer or float ty*/ 0 << Ty; 17029 return true; 17030 } 17031 return false; 17032 } 17033 17034 bool Sema::PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall) { 17035 if (checkArgCount(*this, TheCall, 1)) 17036 return true; 17037 17038 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 17039 if (A.isInvalid()) 17040 return true; 17041 17042 TheCall->setArg(0, A.get()); 17043 QualType TyA = A.get()->getType(); 17044 17045 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA)) 17046 return true; 17047 17048 TheCall->setType(TyA); 17049 return false; 17050 } 17051 17052 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) { 17053 if (checkArgCount(*this, TheCall, 2)) 17054 return true; 17055 17056 ExprResult A = TheCall->getArg(0); 17057 ExprResult B = TheCall->getArg(1); 17058 // Do standard promotions between the two arguments, returning their common 17059 // type. 17060 QualType Res = 17061 UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison); 17062 if (A.isInvalid() || B.isInvalid()) 17063 return true; 17064 17065 QualType TyA = A.get()->getType(); 17066 QualType TyB = B.get()->getType(); 17067 17068 if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType()) 17069 return Diag(A.get()->getBeginLoc(), 17070 diag::err_typecheck_call_different_arg_types) 17071 << TyA << TyB; 17072 17073 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA)) 17074 return true; 17075 17076 TheCall->setArg(0, A.get()); 17077 TheCall->setArg(1, B.get()); 17078 TheCall->setType(Res); 17079 return false; 17080 } 17081 17082 bool Sema::PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall) { 17083 if (checkArgCount(*this, TheCall, 1)) 17084 return true; 17085 17086 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 17087 if (A.isInvalid()) 17088 return true; 17089 17090 TheCall->setArg(0, A.get()); 17091 return false; 17092 } 17093 17094 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 17095 ExprResult CallResult) { 17096 if (checkArgCount(*this, TheCall, 1)) 17097 return ExprError(); 17098 17099 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 17100 if (MatrixArg.isInvalid()) 17101 return MatrixArg; 17102 Expr *Matrix = MatrixArg.get(); 17103 17104 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 17105 if (!MType) { 17106 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17107 << 1 << /* matrix ty*/ 1 << Matrix->getType(); 17108 return ExprError(); 17109 } 17110 17111 // Create returned matrix type by swapping rows and columns of the argument 17112 // matrix type. 17113 QualType ResultType = Context.getConstantMatrixType( 17114 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 17115 17116 // Change the return type to the type of the returned matrix. 17117 TheCall->setType(ResultType); 17118 17119 // Update call argument to use the possibly converted matrix argument. 17120 TheCall->setArg(0, Matrix); 17121 return CallResult; 17122 } 17123 17124 // Get and verify the matrix dimensions. 17125 static llvm::Optional<unsigned> 17126 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 17127 SourceLocation ErrorPos; 17128 Optional<llvm::APSInt> Value = 17129 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 17130 if (!Value) { 17131 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 17132 << Name; 17133 return {}; 17134 } 17135 uint64_t Dim = Value->getZExtValue(); 17136 if (!ConstantMatrixType::isDimensionValid(Dim)) { 17137 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 17138 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 17139 return {}; 17140 } 17141 return Dim; 17142 } 17143 17144 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 17145 ExprResult CallResult) { 17146 if (!getLangOpts().MatrixTypes) { 17147 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 17148 return ExprError(); 17149 } 17150 17151 if (checkArgCount(*this, TheCall, 4)) 17152 return ExprError(); 17153 17154 unsigned PtrArgIdx = 0; 17155 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 17156 Expr *RowsExpr = TheCall->getArg(1); 17157 Expr *ColumnsExpr = TheCall->getArg(2); 17158 Expr *StrideExpr = TheCall->getArg(3); 17159 17160 bool ArgError = false; 17161 17162 // Check pointer argument. 17163 { 17164 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 17165 if (PtrConv.isInvalid()) 17166 return PtrConv; 17167 PtrExpr = PtrConv.get(); 17168 TheCall->setArg(0, PtrExpr); 17169 if (PtrExpr->isTypeDependent()) { 17170 TheCall->setType(Context.DependentTy); 17171 return TheCall; 17172 } 17173 } 17174 17175 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 17176 QualType ElementTy; 17177 if (!PtrTy) { 17178 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17179 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 17180 ArgError = true; 17181 } else { 17182 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 17183 17184 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 17185 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17186 << PtrArgIdx + 1 << /* pointer to element ty*/ 2 17187 << PtrExpr->getType(); 17188 ArgError = true; 17189 } 17190 } 17191 17192 // Apply default Lvalue conversions and convert the expression to size_t. 17193 auto ApplyArgumentConversions = [this](Expr *E) { 17194 ExprResult Conv = DefaultLvalueConversion(E); 17195 if (Conv.isInvalid()) 17196 return Conv; 17197 17198 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 17199 }; 17200 17201 // Apply conversion to row and column expressions. 17202 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 17203 if (!RowsConv.isInvalid()) { 17204 RowsExpr = RowsConv.get(); 17205 TheCall->setArg(1, RowsExpr); 17206 } else 17207 RowsExpr = nullptr; 17208 17209 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 17210 if (!ColumnsConv.isInvalid()) { 17211 ColumnsExpr = ColumnsConv.get(); 17212 TheCall->setArg(2, ColumnsExpr); 17213 } else 17214 ColumnsExpr = nullptr; 17215 17216 // If any any part of the result matrix type is still pending, just use 17217 // Context.DependentTy, until all parts are resolved. 17218 if ((RowsExpr && RowsExpr->isTypeDependent()) || 17219 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 17220 TheCall->setType(Context.DependentTy); 17221 return CallResult; 17222 } 17223 17224 // Check row and column dimensions. 17225 llvm::Optional<unsigned> MaybeRows; 17226 if (RowsExpr) 17227 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 17228 17229 llvm::Optional<unsigned> MaybeColumns; 17230 if (ColumnsExpr) 17231 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 17232 17233 // Check stride argument. 17234 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 17235 if (StrideConv.isInvalid()) 17236 return ExprError(); 17237 StrideExpr = StrideConv.get(); 17238 TheCall->setArg(3, StrideExpr); 17239 17240 if (MaybeRows) { 17241 if (Optional<llvm::APSInt> Value = 17242 StrideExpr->getIntegerConstantExpr(Context)) { 17243 uint64_t Stride = Value->getZExtValue(); 17244 if (Stride < *MaybeRows) { 17245 Diag(StrideExpr->getBeginLoc(), 17246 diag::err_builtin_matrix_stride_too_small); 17247 ArgError = true; 17248 } 17249 } 17250 } 17251 17252 if (ArgError || !MaybeRows || !MaybeColumns) 17253 return ExprError(); 17254 17255 TheCall->setType( 17256 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 17257 return CallResult; 17258 } 17259 17260 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 17261 ExprResult CallResult) { 17262 if (checkArgCount(*this, TheCall, 3)) 17263 return ExprError(); 17264 17265 unsigned PtrArgIdx = 1; 17266 Expr *MatrixExpr = TheCall->getArg(0); 17267 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 17268 Expr *StrideExpr = TheCall->getArg(2); 17269 17270 bool ArgError = false; 17271 17272 { 17273 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 17274 if (MatrixConv.isInvalid()) 17275 return MatrixConv; 17276 MatrixExpr = MatrixConv.get(); 17277 TheCall->setArg(0, MatrixExpr); 17278 } 17279 if (MatrixExpr->isTypeDependent()) { 17280 TheCall->setType(Context.DependentTy); 17281 return TheCall; 17282 } 17283 17284 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 17285 if (!MatrixTy) { 17286 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17287 << 1 << /*matrix ty */ 1 << MatrixExpr->getType(); 17288 ArgError = true; 17289 } 17290 17291 { 17292 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 17293 if (PtrConv.isInvalid()) 17294 return PtrConv; 17295 PtrExpr = PtrConv.get(); 17296 TheCall->setArg(1, PtrExpr); 17297 if (PtrExpr->isTypeDependent()) { 17298 TheCall->setType(Context.DependentTy); 17299 return TheCall; 17300 } 17301 } 17302 17303 // Check pointer argument. 17304 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 17305 if (!PtrTy) { 17306 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 17307 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 17308 ArgError = true; 17309 } else { 17310 QualType ElementTy = PtrTy->getPointeeType(); 17311 if (ElementTy.isConstQualified()) { 17312 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 17313 ArgError = true; 17314 } 17315 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 17316 if (MatrixTy && 17317 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 17318 Diag(PtrExpr->getBeginLoc(), 17319 diag::err_builtin_matrix_pointer_arg_mismatch) 17320 << ElementTy << MatrixTy->getElementType(); 17321 ArgError = true; 17322 } 17323 } 17324 17325 // Apply default Lvalue conversions and convert the stride expression to 17326 // size_t. 17327 { 17328 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 17329 if (StrideConv.isInvalid()) 17330 return StrideConv; 17331 17332 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 17333 if (StrideConv.isInvalid()) 17334 return StrideConv; 17335 StrideExpr = StrideConv.get(); 17336 TheCall->setArg(2, StrideExpr); 17337 } 17338 17339 // Check stride argument. 17340 if (MatrixTy) { 17341 if (Optional<llvm::APSInt> Value = 17342 StrideExpr->getIntegerConstantExpr(Context)) { 17343 uint64_t Stride = Value->getZExtValue(); 17344 if (Stride < MatrixTy->getNumRows()) { 17345 Diag(StrideExpr->getBeginLoc(), 17346 diag::err_builtin_matrix_stride_too_small); 17347 ArgError = true; 17348 } 17349 } 17350 } 17351 17352 if (ArgError) 17353 return ExprError(); 17354 17355 return CallResult; 17356 } 17357 17358 /// \brief Enforce the bounds of a TCB 17359 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 17360 /// directly calls other functions in the same TCB as marked by the enforce_tcb 17361 /// and enforce_tcb_leaf attributes. 17362 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 17363 const FunctionDecl *Callee) { 17364 const FunctionDecl *Caller = getCurFunctionDecl(); 17365 17366 // Calls to builtins are not enforced. 17367 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 17368 Callee->getBuiltinID() != 0) 17369 return; 17370 17371 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 17372 // all TCBs the callee is a part of. 17373 llvm::StringSet<> CalleeTCBs; 17374 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 17375 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 17376 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 17377 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 17378 17379 // Go through the TCBs the caller is a part of and emit warnings if Caller 17380 // is in a TCB that the Callee is not. 17381 for_each( 17382 Caller->specific_attrs<EnforceTCBAttr>(), 17383 [&](const auto *A) { 17384 StringRef CallerTCB = A->getTCBName(); 17385 if (CalleeTCBs.count(CallerTCB) == 0) { 17386 this->Diag(TheCall->getExprLoc(), 17387 diag::warn_tcb_enforcement_violation) << Callee 17388 << CallerTCB; 17389 } 17390 }); 17391 } 17392