1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements extra semantic analysis beyond what is enforced 10 // by the C type system. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/APValue.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/Attr.h" 17 #include "clang/AST/AttrIterator.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclBase.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/DeclarationName.h" 24 #include "clang/AST/EvaluatedExprVisitor.h" 25 #include "clang/AST/Expr.h" 26 #include "clang/AST/ExprCXX.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/ExprOpenMP.h" 29 #include "clang/AST/FormatString.h" 30 #include "clang/AST/NSAPI.h" 31 #include "clang/AST/NonTrivialTypeVisitor.h" 32 #include "clang/AST/OperationKinds.h" 33 #include "clang/AST/RecordLayout.h" 34 #include "clang/AST/Stmt.h" 35 #include "clang/AST/TemplateBase.h" 36 #include "clang/AST/Type.h" 37 #include "clang/AST/TypeLoc.h" 38 #include "clang/AST/UnresolvedSet.h" 39 #include "clang/Basic/AddressSpaces.h" 40 #include "clang/Basic/CharInfo.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/IdentifierTable.h" 43 #include "clang/Basic/LLVM.h" 44 #include "clang/Basic/LangOptions.h" 45 #include "clang/Basic/OpenCLOptions.h" 46 #include "clang/Basic/OperatorKinds.h" 47 #include "clang/Basic/PartialDiagnostic.h" 48 #include "clang/Basic/SourceLocation.h" 49 #include "clang/Basic/SourceManager.h" 50 #include "clang/Basic/Specifiers.h" 51 #include "clang/Basic/SyncScope.h" 52 #include "clang/Basic/TargetBuiltins.h" 53 #include "clang/Basic/TargetCXXABI.h" 54 #include "clang/Basic/TargetInfo.h" 55 #include "clang/Basic/TypeTraits.h" 56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering. 57 #include "clang/Sema/Initialization.h" 58 #include "clang/Sema/Lookup.h" 59 #include "clang/Sema/Ownership.h" 60 #include "clang/Sema/Scope.h" 61 #include "clang/Sema/ScopeInfo.h" 62 #include "clang/Sema/Sema.h" 63 #include "clang/Sema/SemaInternal.h" 64 #include "llvm/ADT/APFloat.h" 65 #include "llvm/ADT/APInt.h" 66 #include "llvm/ADT/APSInt.h" 67 #include "llvm/ADT/ArrayRef.h" 68 #include "llvm/ADT/DenseMap.h" 69 #include "llvm/ADT/FoldingSet.h" 70 #include "llvm/ADT/None.h" 71 #include "llvm/ADT/Optional.h" 72 #include "llvm/ADT/STLExtras.h" 73 #include "llvm/ADT/SmallBitVector.h" 74 #include "llvm/ADT/SmallPtrSet.h" 75 #include "llvm/ADT/SmallString.h" 76 #include "llvm/ADT/SmallVector.h" 77 #include "llvm/ADT/StringRef.h" 78 #include "llvm/ADT/StringSet.h" 79 #include "llvm/ADT/StringSwitch.h" 80 #include "llvm/ADT/Triple.h" 81 #include "llvm/Support/AtomicOrdering.h" 82 #include "llvm/Support/Casting.h" 83 #include "llvm/Support/Compiler.h" 84 #include "llvm/Support/ConvertUTF.h" 85 #include "llvm/Support/ErrorHandling.h" 86 #include "llvm/Support/Format.h" 87 #include "llvm/Support/Locale.h" 88 #include "llvm/Support/MathExtras.h" 89 #include "llvm/Support/SaveAndRestore.h" 90 #include "llvm/Support/raw_ostream.h" 91 #include <algorithm> 92 #include <bitset> 93 #include <cassert> 94 #include <cctype> 95 #include <cstddef> 96 #include <cstdint> 97 #include <functional> 98 #include <limits> 99 #include <string> 100 #include <tuple> 101 #include <utility> 102 103 using namespace clang; 104 using namespace sema; 105 106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 107 unsigned ByteNo) const { 108 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 109 Context.getTargetInfo()); 110 } 111 112 /// Checks that a call expression's argument count is the desired number. 113 /// This is useful when doing custom type-checking. Returns true on error. 114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 115 unsigned argCount = call->getNumArgs(); 116 if (argCount == desiredArgCount) return false; 117 118 if (argCount < desiredArgCount) 119 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 120 << 0 /*function call*/ << desiredArgCount << argCount 121 << call->getSourceRange(); 122 123 // Highlight all the excess arguments. 124 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 125 call->getArg(argCount - 1)->getEndLoc()); 126 127 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 128 << 0 /*function call*/ << desiredArgCount << argCount 129 << call->getArg(1)->getSourceRange(); 130 } 131 132 /// Check that the first argument to __builtin_annotation is an integer 133 /// and the second argument is a non-wide string literal. 134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 135 if (checkArgCount(S, TheCall, 2)) 136 return true; 137 138 // First argument should be an integer. 139 Expr *ValArg = TheCall->getArg(0); 140 QualType Ty = ValArg->getType(); 141 if (!Ty->isIntegerType()) { 142 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 143 << ValArg->getSourceRange(); 144 return true; 145 } 146 147 // Second argument should be a constant string. 148 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 149 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 150 if (!Literal || !Literal->isAscii()) { 151 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 152 << StrArg->getSourceRange(); 153 return true; 154 } 155 156 TheCall->setType(Ty); 157 return false; 158 } 159 160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 161 // We need at least one argument. 162 if (TheCall->getNumArgs() < 1) { 163 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 164 << 0 << 1 << TheCall->getNumArgs() 165 << TheCall->getCallee()->getSourceRange(); 166 return true; 167 } 168 169 // All arguments should be wide string literals. 170 for (Expr *Arg : TheCall->arguments()) { 171 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 172 if (!Literal || !Literal->isWide()) { 173 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 174 << Arg->getSourceRange(); 175 return true; 176 } 177 } 178 179 return false; 180 } 181 182 /// Check that the argument to __builtin_addressof is a glvalue, and set the 183 /// result type to the corresponding pointer type. 184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 185 if (checkArgCount(S, TheCall, 1)) 186 return true; 187 188 ExprResult Arg(TheCall->getArg(0)); 189 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 190 if (ResultType.isNull()) 191 return true; 192 193 TheCall->setArg(0, Arg.get()); 194 TheCall->setType(ResultType); 195 return false; 196 } 197 198 /// Check the number of arguments and set the result type to 199 /// the argument type. 200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 201 if (checkArgCount(S, TheCall, 1)) 202 return true; 203 204 TheCall->setType(TheCall->getArg(0)->getType()); 205 return false; 206 } 207 208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 210 /// type (but not a function pointer) and that the alignment is a power-of-two. 211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 212 if (checkArgCount(S, TheCall, 2)) 213 return true; 214 215 clang::Expr *Source = TheCall->getArg(0); 216 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 217 218 auto IsValidIntegerType = [](QualType Ty) { 219 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 220 }; 221 QualType SrcTy = Source->getType(); 222 // We should also be able to use it with arrays (but not functions!). 223 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 224 SrcTy = S.Context.getDecayedType(SrcTy); 225 } 226 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 227 SrcTy->isFunctionPointerType()) { 228 // FIXME: this is not quite the right error message since we don't allow 229 // floating point types, or member pointers. 230 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 231 << SrcTy; 232 return true; 233 } 234 235 clang::Expr *AlignOp = TheCall->getArg(1); 236 if (!IsValidIntegerType(AlignOp->getType())) { 237 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 238 << AlignOp->getType(); 239 return true; 240 } 241 Expr::EvalResult AlignResult; 242 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 243 // We can't check validity of alignment if it is value dependent. 244 if (!AlignOp->isValueDependent() && 245 AlignOp->EvaluateAsInt(AlignResult, S.Context, 246 Expr::SE_AllowSideEffects)) { 247 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 248 llvm::APSInt MaxValue( 249 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 250 if (AlignValue < 1) { 251 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 252 return true; 253 } 254 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 255 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 256 << toString(MaxValue, 10); 257 return true; 258 } 259 if (!AlignValue.isPowerOf2()) { 260 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 261 return true; 262 } 263 if (AlignValue == 1) { 264 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 265 << IsBooleanAlignBuiltin; 266 } 267 } 268 269 ExprResult SrcArg = S.PerformCopyInitialization( 270 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 271 SourceLocation(), Source); 272 if (SrcArg.isInvalid()) 273 return true; 274 TheCall->setArg(0, SrcArg.get()); 275 ExprResult AlignArg = 276 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 277 S.Context, AlignOp->getType(), false), 278 SourceLocation(), AlignOp); 279 if (AlignArg.isInvalid()) 280 return true; 281 TheCall->setArg(1, AlignArg.get()); 282 // For align_up/align_down, the return type is the same as the (potentially 283 // decayed) argument type including qualifiers. For is_aligned(), the result 284 // is always bool. 285 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 286 return false; 287 } 288 289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 290 unsigned BuiltinID) { 291 if (checkArgCount(S, TheCall, 3)) 292 return true; 293 294 // First two arguments should be integers. 295 for (unsigned I = 0; I < 2; ++I) { 296 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 297 if (Arg.isInvalid()) return true; 298 TheCall->setArg(I, Arg.get()); 299 300 QualType Ty = Arg.get()->getType(); 301 if (!Ty->isIntegerType()) { 302 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 303 << Ty << Arg.get()->getSourceRange(); 304 return true; 305 } 306 } 307 308 // Third argument should be a pointer to a non-const integer. 309 // IRGen correctly handles volatile, restrict, and address spaces, and 310 // the other qualifiers aren't possible. 311 { 312 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 313 if (Arg.isInvalid()) return true; 314 TheCall->setArg(2, Arg.get()); 315 316 QualType Ty = Arg.get()->getType(); 317 const auto *PtrTy = Ty->getAs<PointerType>(); 318 if (!PtrTy || 319 !PtrTy->getPointeeType()->isIntegerType() || 320 PtrTy->getPointeeType().isConstQualified()) { 321 S.Diag(Arg.get()->getBeginLoc(), 322 diag::err_overflow_builtin_must_be_ptr_int) 323 << Ty << Arg.get()->getSourceRange(); 324 return true; 325 } 326 } 327 328 // Disallow signed ExtIntType args larger than 128 bits to mul function until 329 // we improve backend support. 330 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 331 for (unsigned I = 0; I < 3; ++I) { 332 const auto Arg = TheCall->getArg(I); 333 // Third argument will be a pointer. 334 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 335 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 336 S.getASTContext().getIntWidth(Ty) > 128) 337 return S.Diag(Arg->getBeginLoc(), 338 diag::err_overflow_builtin_ext_int_max_size) 339 << 128; 340 } 341 } 342 343 return false; 344 } 345 346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 347 if (checkArgCount(S, BuiltinCall, 2)) 348 return true; 349 350 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 351 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 352 Expr *Call = BuiltinCall->getArg(0); 353 Expr *Chain = BuiltinCall->getArg(1); 354 355 if (Call->getStmtClass() != Stmt::CallExprClass) { 356 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 357 << Call->getSourceRange(); 358 return true; 359 } 360 361 auto CE = cast<CallExpr>(Call); 362 if (CE->getCallee()->getType()->isBlockPointerType()) { 363 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 364 << Call->getSourceRange(); 365 return true; 366 } 367 368 const Decl *TargetDecl = CE->getCalleeDecl(); 369 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 370 if (FD->getBuiltinID()) { 371 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 372 << Call->getSourceRange(); 373 return true; 374 } 375 376 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 377 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 378 << Call->getSourceRange(); 379 return true; 380 } 381 382 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 383 if (ChainResult.isInvalid()) 384 return true; 385 if (!ChainResult.get()->getType()->isPointerType()) { 386 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 387 << Chain->getSourceRange(); 388 return true; 389 } 390 391 QualType ReturnTy = CE->getCallReturnType(S.Context); 392 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 393 QualType BuiltinTy = S.Context.getFunctionType( 394 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 395 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 396 397 Builtin = 398 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 399 400 BuiltinCall->setType(CE->getType()); 401 BuiltinCall->setValueKind(CE->getValueKind()); 402 BuiltinCall->setObjectKind(CE->getObjectKind()); 403 BuiltinCall->setCallee(Builtin); 404 BuiltinCall->setArg(1, ChainResult.get()); 405 406 return false; 407 } 408 409 namespace { 410 411 class ScanfDiagnosticFormatHandler 412 : public analyze_format_string::FormatStringHandler { 413 // Accepts the argument index (relative to the first destination index) of the 414 // argument whose size we want. 415 using ComputeSizeFunction = 416 llvm::function_ref<Optional<llvm::APSInt>(unsigned)>; 417 418 // Accepts the argument index (relative to the first destination index), the 419 // destination size, and the source size). 420 using DiagnoseFunction = 421 llvm::function_ref<void(unsigned, unsigned, unsigned)>; 422 423 ComputeSizeFunction ComputeSizeArgument; 424 DiagnoseFunction Diagnose; 425 426 public: 427 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument, 428 DiagnoseFunction Diagnose) 429 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {} 430 431 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 432 const char *StartSpecifier, 433 unsigned specifierLen) override { 434 auto OptionalFW = FS.getFieldWidth(); 435 if (OptionalFW.getHowSpecified() != 436 analyze_format_string::OptionalAmount::HowSpecified::Constant) 437 return true; 438 439 // We have to write the data plus a NUL byte. 440 unsigned SourceSize = OptionalFW.getConstantAmount() + 1; 441 442 auto DestSizeAPS = ComputeSizeArgument(FS.getArgIndex()); 443 if (!DestSizeAPS) 444 return true; 445 446 unsigned DestSize = DestSizeAPS->getZExtValue(); 447 448 if (DestSize < SourceSize) 449 Diagnose(FS.getArgIndex(), DestSize, SourceSize); 450 451 return true; 452 } 453 }; 454 455 class EstimateSizeFormatHandler 456 : public analyze_format_string::FormatStringHandler { 457 size_t Size; 458 459 public: 460 EstimateSizeFormatHandler(StringRef Format) 461 : Size(std::min(Format.find(0), Format.size()) + 462 1 /* null byte always written by sprintf */) {} 463 464 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 465 const char *, unsigned SpecifierLen) override { 466 467 const size_t FieldWidth = computeFieldWidth(FS); 468 const size_t Precision = computePrecision(FS); 469 470 // The actual format. 471 switch (FS.getConversionSpecifier().getKind()) { 472 // Just a char. 473 case analyze_format_string::ConversionSpecifier::cArg: 474 case analyze_format_string::ConversionSpecifier::CArg: 475 Size += std::max(FieldWidth, (size_t)1); 476 break; 477 // Just an integer. 478 case analyze_format_string::ConversionSpecifier::dArg: 479 case analyze_format_string::ConversionSpecifier::DArg: 480 case analyze_format_string::ConversionSpecifier::iArg: 481 case analyze_format_string::ConversionSpecifier::oArg: 482 case analyze_format_string::ConversionSpecifier::OArg: 483 case analyze_format_string::ConversionSpecifier::uArg: 484 case analyze_format_string::ConversionSpecifier::UArg: 485 case analyze_format_string::ConversionSpecifier::xArg: 486 case analyze_format_string::ConversionSpecifier::XArg: 487 Size += std::max(FieldWidth, Precision); 488 break; 489 490 // %g style conversion switches between %f or %e style dynamically. 491 // %f always takes less space, so default to it. 492 case analyze_format_string::ConversionSpecifier::gArg: 493 case analyze_format_string::ConversionSpecifier::GArg: 494 495 // Floating point number in the form '[+]ddd.ddd'. 496 case analyze_format_string::ConversionSpecifier::fArg: 497 case analyze_format_string::ConversionSpecifier::FArg: 498 Size += std::max(FieldWidth, 1 /* integer part */ + 499 (Precision ? 1 + Precision 500 : 0) /* period + decimal */); 501 break; 502 503 // Floating point number in the form '[-]d.ddde[+-]dd'. 504 case analyze_format_string::ConversionSpecifier::eArg: 505 case analyze_format_string::ConversionSpecifier::EArg: 506 Size += 507 std::max(FieldWidth, 508 1 /* integer part */ + 509 (Precision ? 1 + Precision : 0) /* period + decimal */ + 510 1 /* e or E letter */ + 2 /* exponent */); 511 break; 512 513 // Floating point number in the form '[-]0xh.hhhhp±dd'. 514 case analyze_format_string::ConversionSpecifier::aArg: 515 case analyze_format_string::ConversionSpecifier::AArg: 516 Size += 517 std::max(FieldWidth, 518 2 /* 0x */ + 1 /* integer part */ + 519 (Precision ? 1 + Precision : 0) /* period + decimal */ + 520 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 521 break; 522 523 // Just a string. 524 case analyze_format_string::ConversionSpecifier::sArg: 525 case analyze_format_string::ConversionSpecifier::SArg: 526 Size += FieldWidth; 527 break; 528 529 // Just a pointer in the form '0xddd'. 530 case analyze_format_string::ConversionSpecifier::pArg: 531 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 532 break; 533 534 // A plain percent. 535 case analyze_format_string::ConversionSpecifier::PercentArg: 536 Size += 1; 537 break; 538 539 default: 540 break; 541 } 542 543 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 544 545 if (FS.hasAlternativeForm()) { 546 switch (FS.getConversionSpecifier().getKind()) { 547 default: 548 break; 549 // Force a leading '0'. 550 case analyze_format_string::ConversionSpecifier::oArg: 551 Size += 1; 552 break; 553 // Force a leading '0x'. 554 case analyze_format_string::ConversionSpecifier::xArg: 555 case analyze_format_string::ConversionSpecifier::XArg: 556 Size += 2; 557 break; 558 // Force a period '.' before decimal, even if precision is 0. 559 case analyze_format_string::ConversionSpecifier::aArg: 560 case analyze_format_string::ConversionSpecifier::AArg: 561 case analyze_format_string::ConversionSpecifier::eArg: 562 case analyze_format_string::ConversionSpecifier::EArg: 563 case analyze_format_string::ConversionSpecifier::fArg: 564 case analyze_format_string::ConversionSpecifier::FArg: 565 case analyze_format_string::ConversionSpecifier::gArg: 566 case analyze_format_string::ConversionSpecifier::GArg: 567 Size += (Precision ? 0 : 1); 568 break; 569 } 570 } 571 assert(SpecifierLen <= Size && "no underflow"); 572 Size -= SpecifierLen; 573 return true; 574 } 575 576 size_t getSizeLowerBound() const { return Size; } 577 578 private: 579 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 580 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 581 size_t FieldWidth = 0; 582 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 583 FieldWidth = FW.getConstantAmount(); 584 return FieldWidth; 585 } 586 587 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 588 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 589 size_t Precision = 0; 590 591 // See man 3 printf for default precision value based on the specifier. 592 switch (FW.getHowSpecified()) { 593 case analyze_format_string::OptionalAmount::NotSpecified: 594 switch (FS.getConversionSpecifier().getKind()) { 595 default: 596 break; 597 case analyze_format_string::ConversionSpecifier::dArg: // %d 598 case analyze_format_string::ConversionSpecifier::DArg: // %D 599 case analyze_format_string::ConversionSpecifier::iArg: // %i 600 Precision = 1; 601 break; 602 case analyze_format_string::ConversionSpecifier::oArg: // %d 603 case analyze_format_string::ConversionSpecifier::OArg: // %D 604 case analyze_format_string::ConversionSpecifier::uArg: // %d 605 case analyze_format_string::ConversionSpecifier::UArg: // %D 606 case analyze_format_string::ConversionSpecifier::xArg: // %d 607 case analyze_format_string::ConversionSpecifier::XArg: // %D 608 Precision = 1; 609 break; 610 case analyze_format_string::ConversionSpecifier::fArg: // %f 611 case analyze_format_string::ConversionSpecifier::FArg: // %F 612 case analyze_format_string::ConversionSpecifier::eArg: // %e 613 case analyze_format_string::ConversionSpecifier::EArg: // %E 614 case analyze_format_string::ConversionSpecifier::gArg: // %g 615 case analyze_format_string::ConversionSpecifier::GArg: // %G 616 Precision = 6; 617 break; 618 case analyze_format_string::ConversionSpecifier::pArg: // %d 619 Precision = 1; 620 break; 621 } 622 break; 623 case analyze_format_string::OptionalAmount::Constant: 624 Precision = FW.getConstantAmount(); 625 break; 626 default: 627 break; 628 } 629 return Precision; 630 } 631 }; 632 633 } // namespace 634 635 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 636 CallExpr *TheCall) { 637 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 638 isConstantEvaluated()) 639 return; 640 641 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 642 if (!BuiltinID) 643 return; 644 645 const TargetInfo &TI = getASTContext().getTargetInfo(); 646 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 647 648 auto ComputeExplicitObjectSizeArgument = 649 [&](unsigned Index) -> Optional<llvm::APSInt> { 650 Expr::EvalResult Result; 651 Expr *SizeArg = TheCall->getArg(Index); 652 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 653 return llvm::None; 654 return Result.Val.getInt(); 655 }; 656 657 auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 658 // If the parameter has a pass_object_size attribute, then we should use its 659 // (potentially) more strict checking mode. Otherwise, conservatively assume 660 // type 0. 661 int BOSType = 0; 662 // This check can fail for variadic functions. 663 if (Index < FD->getNumParams()) { 664 if (const auto *POS = 665 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>()) 666 BOSType = POS->getType(); 667 } 668 669 const Expr *ObjArg = TheCall->getArg(Index); 670 uint64_t Result; 671 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 672 return llvm::None; 673 674 // Get the object size in the target's size_t width. 675 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 676 }; 677 678 auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 679 Expr *ObjArg = TheCall->getArg(Index); 680 uint64_t Result; 681 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext())) 682 return llvm::None; 683 // Add 1 for null byte. 684 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth); 685 }; 686 687 Optional<llvm::APSInt> SourceSize; 688 Optional<llvm::APSInt> DestinationSize; 689 unsigned DiagID = 0; 690 bool IsChkVariant = false; 691 692 auto GetFunctionName = [&]() { 693 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 694 // Skim off the details of whichever builtin was called to produce a better 695 // diagnostic, as it's unlikely that the user wrote the __builtin 696 // explicitly. 697 if (IsChkVariant) { 698 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 699 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 700 } else if (FunctionName.startswith("__builtin_")) { 701 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 702 } 703 return FunctionName; 704 }; 705 706 switch (BuiltinID) { 707 default: 708 return; 709 case Builtin::BI__builtin_strcpy: 710 case Builtin::BIstrcpy: { 711 DiagID = diag::warn_fortify_strlen_overflow; 712 SourceSize = ComputeStrLenArgument(1); 713 DestinationSize = ComputeSizeArgument(0); 714 break; 715 } 716 717 case Builtin::BI__builtin___strcpy_chk: { 718 DiagID = diag::warn_fortify_strlen_overflow; 719 SourceSize = ComputeStrLenArgument(1); 720 DestinationSize = ComputeExplicitObjectSizeArgument(2); 721 IsChkVariant = true; 722 break; 723 } 724 725 case Builtin::BIscanf: 726 case Builtin::BIfscanf: 727 case Builtin::BIsscanf: { 728 unsigned FormatIndex = 1; 729 unsigned DataIndex = 2; 730 if (BuiltinID == Builtin::BIscanf) { 731 FormatIndex = 0; 732 DataIndex = 1; 733 } 734 735 const auto *FormatExpr = 736 TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 737 738 const auto *Format = dyn_cast<StringLiteral>(FormatExpr); 739 if (!Format) 740 return; 741 742 if (!Format->isAscii() && !Format->isUTF8()) 743 return; 744 745 auto Diagnose = [&](unsigned ArgIndex, unsigned DestSize, 746 unsigned SourceSize) { 747 DiagID = diag::warn_fortify_scanf_overflow; 748 StringRef FunctionName = GetFunctionName(); 749 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 750 PDiag(DiagID) 751 << FunctionName << (ArgIndex + DataIndex + 1) 752 << DestSize << SourceSize); 753 }; 754 755 StringRef FormatStrRef = Format->getString(); 756 auto ShiftedComputeSizeArgument = [&](unsigned Index) { 757 return ComputeSizeArgument(Index + DataIndex); 758 }; 759 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument, Diagnose); 760 const char *FormatBytes = FormatStrRef.data(); 761 const ConstantArrayType *T = 762 Context.getAsConstantArrayType(Format->getType()); 763 assert(T && "String literal not of constant array type!"); 764 size_t TypeSize = T->getSize().getZExtValue(); 765 766 // In case there's a null byte somewhere. 767 size_t StrLen = 768 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 769 770 analyze_format_string::ParseScanfString(H, FormatBytes, 771 FormatBytes + StrLen, getLangOpts(), 772 Context.getTargetInfo()); 773 774 // Unlike the other cases, in this one we have already issued the diagnostic 775 // here, so no need to continue (because unlike the other cases, here the 776 // diagnostic refers to the argument number). 777 return; 778 } 779 780 case Builtin::BIsprintf: 781 case Builtin::BI__builtin___sprintf_chk: { 782 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 783 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 784 785 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 786 787 if (!Format->isAscii() && !Format->isUTF8()) 788 return; 789 790 StringRef FormatStrRef = Format->getString(); 791 EstimateSizeFormatHandler H(FormatStrRef); 792 const char *FormatBytes = FormatStrRef.data(); 793 const ConstantArrayType *T = 794 Context.getAsConstantArrayType(Format->getType()); 795 assert(T && "String literal not of constant array type!"); 796 size_t TypeSize = T->getSize().getZExtValue(); 797 798 // In case there's a null byte somewhere. 799 size_t StrLen = 800 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 801 if (!analyze_format_string::ParsePrintfString( 802 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 803 Context.getTargetInfo(), false)) { 804 DiagID = diag::warn_fortify_source_format_overflow; 805 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 806 .extOrTrunc(SizeTypeWidth); 807 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 808 DestinationSize = ComputeExplicitObjectSizeArgument(2); 809 IsChkVariant = true; 810 } else { 811 DestinationSize = ComputeSizeArgument(0); 812 } 813 break; 814 } 815 } 816 return; 817 } 818 case Builtin::BI__builtin___memcpy_chk: 819 case Builtin::BI__builtin___memmove_chk: 820 case Builtin::BI__builtin___memset_chk: 821 case Builtin::BI__builtin___strlcat_chk: 822 case Builtin::BI__builtin___strlcpy_chk: 823 case Builtin::BI__builtin___strncat_chk: 824 case Builtin::BI__builtin___strncpy_chk: 825 case Builtin::BI__builtin___stpncpy_chk: 826 case Builtin::BI__builtin___memccpy_chk: 827 case Builtin::BI__builtin___mempcpy_chk: { 828 DiagID = diag::warn_builtin_chk_overflow; 829 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2); 830 DestinationSize = 831 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 832 IsChkVariant = true; 833 break; 834 } 835 836 case Builtin::BI__builtin___snprintf_chk: 837 case Builtin::BI__builtin___vsnprintf_chk: { 838 DiagID = diag::warn_builtin_chk_overflow; 839 SourceSize = ComputeExplicitObjectSizeArgument(1); 840 DestinationSize = ComputeExplicitObjectSizeArgument(3); 841 IsChkVariant = true; 842 break; 843 } 844 845 case Builtin::BIstrncat: 846 case Builtin::BI__builtin_strncat: 847 case Builtin::BIstrncpy: 848 case Builtin::BI__builtin_strncpy: 849 case Builtin::BIstpncpy: 850 case Builtin::BI__builtin_stpncpy: { 851 // Whether these functions overflow depends on the runtime strlen of the 852 // string, not just the buffer size, so emitting the "always overflow" 853 // diagnostic isn't quite right. We should still diagnose passing a buffer 854 // size larger than the destination buffer though; this is a runtime abort 855 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 856 DiagID = diag::warn_fortify_source_size_mismatch; 857 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 858 DestinationSize = ComputeSizeArgument(0); 859 break; 860 } 861 862 case Builtin::BImemcpy: 863 case Builtin::BI__builtin_memcpy: 864 case Builtin::BImemmove: 865 case Builtin::BI__builtin_memmove: 866 case Builtin::BImemset: 867 case Builtin::BI__builtin_memset: 868 case Builtin::BImempcpy: 869 case Builtin::BI__builtin_mempcpy: { 870 DiagID = diag::warn_fortify_source_overflow; 871 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 872 DestinationSize = ComputeSizeArgument(0); 873 break; 874 } 875 case Builtin::BIsnprintf: 876 case Builtin::BI__builtin_snprintf: 877 case Builtin::BIvsnprintf: 878 case Builtin::BI__builtin_vsnprintf: { 879 DiagID = diag::warn_fortify_source_size_mismatch; 880 SourceSize = ComputeExplicitObjectSizeArgument(1); 881 DestinationSize = ComputeSizeArgument(0); 882 break; 883 } 884 } 885 886 if (!SourceSize || !DestinationSize || 887 SourceSize.getValue().ule(DestinationSize.getValue())) 888 return; 889 890 StringRef FunctionName = GetFunctionName(); 891 892 SmallString<16> DestinationStr; 893 SmallString<16> SourceStr; 894 DestinationSize->toString(DestinationStr, /*Radix=*/10); 895 SourceSize->toString(SourceStr, /*Radix=*/10); 896 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 897 PDiag(DiagID) 898 << FunctionName << DestinationStr << SourceStr); 899 } 900 901 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 902 Scope::ScopeFlags NeededScopeFlags, 903 unsigned DiagID) { 904 // Scopes aren't available during instantiation. Fortunately, builtin 905 // functions cannot be template args so they cannot be formed through template 906 // instantiation. Therefore checking once during the parse is sufficient. 907 if (SemaRef.inTemplateInstantiation()) 908 return false; 909 910 Scope *S = SemaRef.getCurScope(); 911 while (S && !S->isSEHExceptScope()) 912 S = S->getParent(); 913 if (!S || !(S->getFlags() & NeededScopeFlags)) { 914 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 915 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 916 << DRE->getDecl()->getIdentifier(); 917 return true; 918 } 919 920 return false; 921 } 922 923 static inline bool isBlockPointer(Expr *Arg) { 924 return Arg->getType()->isBlockPointerType(); 925 } 926 927 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 928 /// void*, which is a requirement of device side enqueue. 929 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 930 const BlockPointerType *BPT = 931 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 932 ArrayRef<QualType> Params = 933 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 934 unsigned ArgCounter = 0; 935 bool IllegalParams = false; 936 // Iterate through the block parameters until either one is found that is not 937 // a local void*, or the block is valid. 938 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 939 I != E; ++I, ++ArgCounter) { 940 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 941 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 942 LangAS::opencl_local) { 943 // Get the location of the error. If a block literal has been passed 944 // (BlockExpr) then we can point straight to the offending argument, 945 // else we just point to the variable reference. 946 SourceLocation ErrorLoc; 947 if (isa<BlockExpr>(BlockArg)) { 948 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 949 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 950 } else if (isa<DeclRefExpr>(BlockArg)) { 951 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 952 } 953 S.Diag(ErrorLoc, 954 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 955 IllegalParams = true; 956 } 957 } 958 959 return IllegalParams; 960 } 961 962 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 963 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) { 964 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 965 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 966 return true; 967 } 968 return false; 969 } 970 971 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 972 if (checkArgCount(S, TheCall, 2)) 973 return true; 974 975 if (checkOpenCLSubgroupExt(S, TheCall)) 976 return true; 977 978 // First argument is an ndrange_t type. 979 Expr *NDRangeArg = TheCall->getArg(0); 980 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 981 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 982 << TheCall->getDirectCallee() << "'ndrange_t'"; 983 return true; 984 } 985 986 Expr *BlockArg = TheCall->getArg(1); 987 if (!isBlockPointer(BlockArg)) { 988 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 989 << TheCall->getDirectCallee() << "block"; 990 return true; 991 } 992 return checkOpenCLBlockArgs(S, BlockArg); 993 } 994 995 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 996 /// get_kernel_work_group_size 997 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 998 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 999 if (checkArgCount(S, TheCall, 1)) 1000 return true; 1001 1002 Expr *BlockArg = TheCall->getArg(0); 1003 if (!isBlockPointer(BlockArg)) { 1004 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1005 << TheCall->getDirectCallee() << "block"; 1006 return true; 1007 } 1008 return checkOpenCLBlockArgs(S, BlockArg); 1009 } 1010 1011 /// Diagnose integer type and any valid implicit conversion to it. 1012 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 1013 const QualType &IntType); 1014 1015 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 1016 unsigned Start, unsigned End) { 1017 bool IllegalParams = false; 1018 for (unsigned I = Start; I <= End; ++I) 1019 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 1020 S.Context.getSizeType()); 1021 return IllegalParams; 1022 } 1023 1024 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 1025 /// 'local void*' parameter of passed block. 1026 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 1027 Expr *BlockArg, 1028 unsigned NumNonVarArgs) { 1029 const BlockPointerType *BPT = 1030 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 1031 unsigned NumBlockParams = 1032 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 1033 unsigned TotalNumArgs = TheCall->getNumArgs(); 1034 1035 // For each argument passed to the block, a corresponding uint needs to 1036 // be passed to describe the size of the local memory. 1037 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 1038 S.Diag(TheCall->getBeginLoc(), 1039 diag::err_opencl_enqueue_kernel_local_size_args); 1040 return true; 1041 } 1042 1043 // Check that the sizes of the local memory are specified by integers. 1044 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 1045 TotalNumArgs - 1); 1046 } 1047 1048 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 1049 /// overload formats specified in Table 6.13.17.1. 1050 /// int enqueue_kernel(queue_t queue, 1051 /// kernel_enqueue_flags_t flags, 1052 /// const ndrange_t ndrange, 1053 /// void (^block)(void)) 1054 /// int enqueue_kernel(queue_t queue, 1055 /// kernel_enqueue_flags_t flags, 1056 /// const ndrange_t ndrange, 1057 /// uint num_events_in_wait_list, 1058 /// clk_event_t *event_wait_list, 1059 /// clk_event_t *event_ret, 1060 /// void (^block)(void)) 1061 /// int enqueue_kernel(queue_t queue, 1062 /// kernel_enqueue_flags_t flags, 1063 /// const ndrange_t ndrange, 1064 /// void (^block)(local void*, ...), 1065 /// uint size0, ...) 1066 /// int enqueue_kernel(queue_t queue, 1067 /// kernel_enqueue_flags_t flags, 1068 /// const ndrange_t ndrange, 1069 /// uint num_events_in_wait_list, 1070 /// clk_event_t *event_wait_list, 1071 /// clk_event_t *event_ret, 1072 /// void (^block)(local void*, ...), 1073 /// uint size0, ...) 1074 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 1075 unsigned NumArgs = TheCall->getNumArgs(); 1076 1077 if (NumArgs < 4) { 1078 S.Diag(TheCall->getBeginLoc(), 1079 diag::err_typecheck_call_too_few_args_at_least) 1080 << 0 << 4 << NumArgs; 1081 return true; 1082 } 1083 1084 Expr *Arg0 = TheCall->getArg(0); 1085 Expr *Arg1 = TheCall->getArg(1); 1086 Expr *Arg2 = TheCall->getArg(2); 1087 Expr *Arg3 = TheCall->getArg(3); 1088 1089 // First argument always needs to be a queue_t type. 1090 if (!Arg0->getType()->isQueueT()) { 1091 S.Diag(TheCall->getArg(0)->getBeginLoc(), 1092 diag::err_opencl_builtin_expected_type) 1093 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 1094 return true; 1095 } 1096 1097 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 1098 if (!Arg1->getType()->isIntegerType()) { 1099 S.Diag(TheCall->getArg(1)->getBeginLoc(), 1100 diag::err_opencl_builtin_expected_type) 1101 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 1102 return true; 1103 } 1104 1105 // Third argument is always an ndrange_t type. 1106 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 1107 S.Diag(TheCall->getArg(2)->getBeginLoc(), 1108 diag::err_opencl_builtin_expected_type) 1109 << TheCall->getDirectCallee() << "'ndrange_t'"; 1110 return true; 1111 } 1112 1113 // With four arguments, there is only one form that the function could be 1114 // called in: no events and no variable arguments. 1115 if (NumArgs == 4) { 1116 // check that the last argument is the right block type. 1117 if (!isBlockPointer(Arg3)) { 1118 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1119 << TheCall->getDirectCallee() << "block"; 1120 return true; 1121 } 1122 // we have a block type, check the prototype 1123 const BlockPointerType *BPT = 1124 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1125 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1126 S.Diag(Arg3->getBeginLoc(), 1127 diag::err_opencl_enqueue_kernel_blocks_no_args); 1128 return true; 1129 } 1130 return false; 1131 } 1132 // we can have block + varargs. 1133 if (isBlockPointer(Arg3)) 1134 return (checkOpenCLBlockArgs(S, Arg3) || 1135 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1136 // last two cases with either exactly 7 args or 7 args and varargs. 1137 if (NumArgs >= 7) { 1138 // check common block argument. 1139 Expr *Arg6 = TheCall->getArg(6); 1140 if (!isBlockPointer(Arg6)) { 1141 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1142 << TheCall->getDirectCallee() << "block"; 1143 return true; 1144 } 1145 if (checkOpenCLBlockArgs(S, Arg6)) 1146 return true; 1147 1148 // Forth argument has to be any integer type. 1149 if (!Arg3->getType()->isIntegerType()) { 1150 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1151 diag::err_opencl_builtin_expected_type) 1152 << TheCall->getDirectCallee() << "integer"; 1153 return true; 1154 } 1155 // check remaining common arguments. 1156 Expr *Arg4 = TheCall->getArg(4); 1157 Expr *Arg5 = TheCall->getArg(5); 1158 1159 // Fifth argument is always passed as a pointer to clk_event_t. 1160 if (!Arg4->isNullPointerConstant(S.Context, 1161 Expr::NPC_ValueDependentIsNotNull) && 1162 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1163 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1164 diag::err_opencl_builtin_expected_type) 1165 << TheCall->getDirectCallee() 1166 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1167 return true; 1168 } 1169 1170 // Sixth argument is always passed as a pointer to clk_event_t. 1171 if (!Arg5->isNullPointerConstant(S.Context, 1172 Expr::NPC_ValueDependentIsNotNull) && 1173 !(Arg5->getType()->isPointerType() && 1174 Arg5->getType()->getPointeeType()->isClkEventT())) { 1175 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1176 diag::err_opencl_builtin_expected_type) 1177 << TheCall->getDirectCallee() 1178 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1179 return true; 1180 } 1181 1182 if (NumArgs == 7) 1183 return false; 1184 1185 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1186 } 1187 1188 // None of the specific case has been detected, give generic error 1189 S.Diag(TheCall->getBeginLoc(), 1190 diag::err_opencl_enqueue_kernel_incorrect_args); 1191 return true; 1192 } 1193 1194 /// Returns OpenCL access qual. 1195 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1196 return D->getAttr<OpenCLAccessAttr>(); 1197 } 1198 1199 /// Returns true if pipe element type is different from the pointer. 1200 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1201 const Expr *Arg0 = Call->getArg(0); 1202 // First argument type should always be pipe. 1203 if (!Arg0->getType()->isPipeType()) { 1204 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1205 << Call->getDirectCallee() << Arg0->getSourceRange(); 1206 return true; 1207 } 1208 OpenCLAccessAttr *AccessQual = 1209 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1210 // Validates the access qualifier is compatible with the call. 1211 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1212 // read_only and write_only, and assumed to be read_only if no qualifier is 1213 // specified. 1214 switch (Call->getDirectCallee()->getBuiltinID()) { 1215 case Builtin::BIread_pipe: 1216 case Builtin::BIreserve_read_pipe: 1217 case Builtin::BIcommit_read_pipe: 1218 case Builtin::BIwork_group_reserve_read_pipe: 1219 case Builtin::BIsub_group_reserve_read_pipe: 1220 case Builtin::BIwork_group_commit_read_pipe: 1221 case Builtin::BIsub_group_commit_read_pipe: 1222 if (!(!AccessQual || AccessQual->isReadOnly())) { 1223 S.Diag(Arg0->getBeginLoc(), 1224 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1225 << "read_only" << Arg0->getSourceRange(); 1226 return true; 1227 } 1228 break; 1229 case Builtin::BIwrite_pipe: 1230 case Builtin::BIreserve_write_pipe: 1231 case Builtin::BIcommit_write_pipe: 1232 case Builtin::BIwork_group_reserve_write_pipe: 1233 case Builtin::BIsub_group_reserve_write_pipe: 1234 case Builtin::BIwork_group_commit_write_pipe: 1235 case Builtin::BIsub_group_commit_write_pipe: 1236 if (!(AccessQual && AccessQual->isWriteOnly())) { 1237 S.Diag(Arg0->getBeginLoc(), 1238 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1239 << "write_only" << Arg0->getSourceRange(); 1240 return true; 1241 } 1242 break; 1243 default: 1244 break; 1245 } 1246 return false; 1247 } 1248 1249 /// Returns true if pipe element type is different from the pointer. 1250 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1251 const Expr *Arg0 = Call->getArg(0); 1252 const Expr *ArgIdx = Call->getArg(Idx); 1253 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1254 const QualType EltTy = PipeTy->getElementType(); 1255 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1256 // The Idx argument should be a pointer and the type of the pointer and 1257 // the type of pipe element should also be the same. 1258 if (!ArgTy || 1259 !S.Context.hasSameType( 1260 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1261 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1262 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1263 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1264 return true; 1265 } 1266 return false; 1267 } 1268 1269 // Performs semantic analysis for the read/write_pipe call. 1270 // \param S Reference to the semantic analyzer. 1271 // \param Call A pointer to the builtin call. 1272 // \return True if a semantic error has been found, false otherwise. 1273 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1274 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1275 // functions have two forms. 1276 switch (Call->getNumArgs()) { 1277 case 2: 1278 if (checkOpenCLPipeArg(S, Call)) 1279 return true; 1280 // The call with 2 arguments should be 1281 // read/write_pipe(pipe T, T*). 1282 // Check packet type T. 1283 if (checkOpenCLPipePacketType(S, Call, 1)) 1284 return true; 1285 break; 1286 1287 case 4: { 1288 if (checkOpenCLPipeArg(S, Call)) 1289 return true; 1290 // The call with 4 arguments should be 1291 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1292 // Check reserve_id_t. 1293 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1294 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1295 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1296 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1297 return true; 1298 } 1299 1300 // Check the index. 1301 const Expr *Arg2 = Call->getArg(2); 1302 if (!Arg2->getType()->isIntegerType() && 1303 !Arg2->getType()->isUnsignedIntegerType()) { 1304 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1305 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1306 << Arg2->getType() << Arg2->getSourceRange(); 1307 return true; 1308 } 1309 1310 // Check packet type T. 1311 if (checkOpenCLPipePacketType(S, Call, 3)) 1312 return true; 1313 } break; 1314 default: 1315 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1316 << Call->getDirectCallee() << Call->getSourceRange(); 1317 return true; 1318 } 1319 1320 return false; 1321 } 1322 1323 // Performs a semantic analysis on the {work_group_/sub_group_ 1324 // /_}reserve_{read/write}_pipe 1325 // \param S Reference to the semantic analyzer. 1326 // \param Call The call to the builtin function to be analyzed. 1327 // \return True if a semantic error was found, false otherwise. 1328 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1329 if (checkArgCount(S, Call, 2)) 1330 return true; 1331 1332 if (checkOpenCLPipeArg(S, Call)) 1333 return true; 1334 1335 // Check the reserve size. 1336 if (!Call->getArg(1)->getType()->isIntegerType() && 1337 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1338 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1339 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1340 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1341 return true; 1342 } 1343 1344 // Since return type of reserve_read/write_pipe built-in function is 1345 // reserve_id_t, which is not defined in the builtin def file , we used int 1346 // as return type and need to override the return type of these functions. 1347 Call->setType(S.Context.OCLReserveIDTy); 1348 1349 return false; 1350 } 1351 1352 // Performs a semantic analysis on {work_group_/sub_group_ 1353 // /_}commit_{read/write}_pipe 1354 // \param S Reference to the semantic analyzer. 1355 // \param Call The call to the builtin function to be analyzed. 1356 // \return True if a semantic error was found, false otherwise. 1357 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1358 if (checkArgCount(S, Call, 2)) 1359 return true; 1360 1361 if (checkOpenCLPipeArg(S, Call)) 1362 return true; 1363 1364 // Check reserve_id_t. 1365 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1366 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1367 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1368 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1369 return true; 1370 } 1371 1372 return false; 1373 } 1374 1375 // Performs a semantic analysis on the call to built-in Pipe 1376 // Query Functions. 1377 // \param S Reference to the semantic analyzer. 1378 // \param Call The call to the builtin function to be analyzed. 1379 // \return True if a semantic error was found, false otherwise. 1380 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1381 if (checkArgCount(S, Call, 1)) 1382 return true; 1383 1384 if (!Call->getArg(0)->getType()->isPipeType()) { 1385 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1386 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1387 return true; 1388 } 1389 1390 return false; 1391 } 1392 1393 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1394 // Performs semantic analysis for the to_global/local/private call. 1395 // \param S Reference to the semantic analyzer. 1396 // \param BuiltinID ID of the builtin function. 1397 // \param Call A pointer to the builtin call. 1398 // \return True if a semantic error has been found, false otherwise. 1399 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1400 CallExpr *Call) { 1401 if (checkArgCount(S, Call, 1)) 1402 return true; 1403 1404 auto RT = Call->getArg(0)->getType(); 1405 if (!RT->isPointerType() || RT->getPointeeType() 1406 .getAddressSpace() == LangAS::opencl_constant) { 1407 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1408 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1409 return true; 1410 } 1411 1412 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1413 S.Diag(Call->getArg(0)->getBeginLoc(), 1414 diag::warn_opencl_generic_address_space_arg) 1415 << Call->getDirectCallee()->getNameInfo().getAsString() 1416 << Call->getArg(0)->getSourceRange(); 1417 } 1418 1419 RT = RT->getPointeeType(); 1420 auto Qual = RT.getQualifiers(); 1421 switch (BuiltinID) { 1422 case Builtin::BIto_global: 1423 Qual.setAddressSpace(LangAS::opencl_global); 1424 break; 1425 case Builtin::BIto_local: 1426 Qual.setAddressSpace(LangAS::opencl_local); 1427 break; 1428 case Builtin::BIto_private: 1429 Qual.setAddressSpace(LangAS::opencl_private); 1430 break; 1431 default: 1432 llvm_unreachable("Invalid builtin function"); 1433 } 1434 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1435 RT.getUnqualifiedType(), Qual))); 1436 1437 return false; 1438 } 1439 1440 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1441 if (checkArgCount(S, TheCall, 1)) 1442 return ExprError(); 1443 1444 // Compute __builtin_launder's parameter type from the argument. 1445 // The parameter type is: 1446 // * The type of the argument if it's not an array or function type, 1447 // Otherwise, 1448 // * The decayed argument type. 1449 QualType ParamTy = [&]() { 1450 QualType ArgTy = TheCall->getArg(0)->getType(); 1451 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1452 return S.Context.getPointerType(Ty->getElementType()); 1453 if (ArgTy->isFunctionType()) { 1454 return S.Context.getPointerType(ArgTy); 1455 } 1456 return ArgTy; 1457 }(); 1458 1459 TheCall->setType(ParamTy); 1460 1461 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1462 if (!ParamTy->isPointerType()) 1463 return 0; 1464 if (ParamTy->isFunctionPointerType()) 1465 return 1; 1466 if (ParamTy->isVoidPointerType()) 1467 return 2; 1468 return llvm::Optional<unsigned>{}; 1469 }(); 1470 if (DiagSelect.hasValue()) { 1471 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1472 << DiagSelect.getValue() << TheCall->getSourceRange(); 1473 return ExprError(); 1474 } 1475 1476 // We either have an incomplete class type, or we have a class template 1477 // whose instantiation has not been forced. Example: 1478 // 1479 // template <class T> struct Foo { T value; }; 1480 // Foo<int> *p = nullptr; 1481 // auto *d = __builtin_launder(p); 1482 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1483 diag::err_incomplete_type)) 1484 return ExprError(); 1485 1486 assert(ParamTy->getPointeeType()->isObjectType() && 1487 "Unhandled non-object pointer case"); 1488 1489 InitializedEntity Entity = 1490 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1491 ExprResult Arg = 1492 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1493 if (Arg.isInvalid()) 1494 return ExprError(); 1495 TheCall->setArg(0, Arg.get()); 1496 1497 return TheCall; 1498 } 1499 1500 // Emit an error and return true if the current architecture is not in the list 1501 // of supported architectures. 1502 static bool 1503 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1504 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1505 llvm::Triple::ArchType CurArch = 1506 S.getASTContext().getTargetInfo().getTriple().getArch(); 1507 if (llvm::is_contained(SupportedArchs, CurArch)) 1508 return false; 1509 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1510 << TheCall->getSourceRange(); 1511 return true; 1512 } 1513 1514 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1515 SourceLocation CallSiteLoc); 1516 1517 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1518 CallExpr *TheCall) { 1519 switch (TI.getTriple().getArch()) { 1520 default: 1521 // Some builtins don't require additional checking, so just consider these 1522 // acceptable. 1523 return false; 1524 case llvm::Triple::arm: 1525 case llvm::Triple::armeb: 1526 case llvm::Triple::thumb: 1527 case llvm::Triple::thumbeb: 1528 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1529 case llvm::Triple::aarch64: 1530 case llvm::Triple::aarch64_32: 1531 case llvm::Triple::aarch64_be: 1532 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1533 case llvm::Triple::bpfeb: 1534 case llvm::Triple::bpfel: 1535 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1536 case llvm::Triple::hexagon: 1537 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1538 case llvm::Triple::mips: 1539 case llvm::Triple::mipsel: 1540 case llvm::Triple::mips64: 1541 case llvm::Triple::mips64el: 1542 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1543 case llvm::Triple::systemz: 1544 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1545 case llvm::Triple::x86: 1546 case llvm::Triple::x86_64: 1547 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1548 case llvm::Triple::ppc: 1549 case llvm::Triple::ppcle: 1550 case llvm::Triple::ppc64: 1551 case llvm::Triple::ppc64le: 1552 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1553 case llvm::Triple::amdgcn: 1554 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1555 case llvm::Triple::riscv32: 1556 case llvm::Triple::riscv64: 1557 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1558 } 1559 } 1560 1561 ExprResult 1562 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1563 CallExpr *TheCall) { 1564 ExprResult TheCallResult(TheCall); 1565 1566 // Find out if any arguments are required to be integer constant expressions. 1567 unsigned ICEArguments = 0; 1568 ASTContext::GetBuiltinTypeError Error; 1569 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1570 if (Error != ASTContext::GE_None) 1571 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1572 1573 // If any arguments are required to be ICE's, check and diagnose. 1574 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1575 // Skip arguments not required to be ICE's. 1576 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1577 1578 llvm::APSInt Result; 1579 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1580 return true; 1581 ICEArguments &= ~(1 << ArgNo); 1582 } 1583 1584 switch (BuiltinID) { 1585 case Builtin::BI__builtin___CFStringMakeConstantString: 1586 assert(TheCall->getNumArgs() == 1 && 1587 "Wrong # arguments to builtin CFStringMakeConstantString"); 1588 if (CheckObjCString(TheCall->getArg(0))) 1589 return ExprError(); 1590 break; 1591 case Builtin::BI__builtin_ms_va_start: 1592 case Builtin::BI__builtin_stdarg_start: 1593 case Builtin::BI__builtin_va_start: 1594 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1595 return ExprError(); 1596 break; 1597 case Builtin::BI__va_start: { 1598 switch (Context.getTargetInfo().getTriple().getArch()) { 1599 case llvm::Triple::aarch64: 1600 case llvm::Triple::arm: 1601 case llvm::Triple::thumb: 1602 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1603 return ExprError(); 1604 break; 1605 default: 1606 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1607 return ExprError(); 1608 break; 1609 } 1610 break; 1611 } 1612 1613 // The acquire, release, and no fence variants are ARM and AArch64 only. 1614 case Builtin::BI_interlockedbittestandset_acq: 1615 case Builtin::BI_interlockedbittestandset_rel: 1616 case Builtin::BI_interlockedbittestandset_nf: 1617 case Builtin::BI_interlockedbittestandreset_acq: 1618 case Builtin::BI_interlockedbittestandreset_rel: 1619 case Builtin::BI_interlockedbittestandreset_nf: 1620 if (CheckBuiltinTargetSupport( 1621 *this, BuiltinID, TheCall, 1622 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1623 return ExprError(); 1624 break; 1625 1626 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1627 case Builtin::BI_bittest64: 1628 case Builtin::BI_bittestandcomplement64: 1629 case Builtin::BI_bittestandreset64: 1630 case Builtin::BI_bittestandset64: 1631 case Builtin::BI_interlockedbittestandreset64: 1632 case Builtin::BI_interlockedbittestandset64: 1633 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1634 {llvm::Triple::x86_64, llvm::Triple::arm, 1635 llvm::Triple::thumb, llvm::Triple::aarch64})) 1636 return ExprError(); 1637 break; 1638 1639 case Builtin::BI__builtin_isgreater: 1640 case Builtin::BI__builtin_isgreaterequal: 1641 case Builtin::BI__builtin_isless: 1642 case Builtin::BI__builtin_islessequal: 1643 case Builtin::BI__builtin_islessgreater: 1644 case Builtin::BI__builtin_isunordered: 1645 if (SemaBuiltinUnorderedCompare(TheCall)) 1646 return ExprError(); 1647 break; 1648 case Builtin::BI__builtin_fpclassify: 1649 if (SemaBuiltinFPClassification(TheCall, 6)) 1650 return ExprError(); 1651 break; 1652 case Builtin::BI__builtin_isfinite: 1653 case Builtin::BI__builtin_isinf: 1654 case Builtin::BI__builtin_isinf_sign: 1655 case Builtin::BI__builtin_isnan: 1656 case Builtin::BI__builtin_isnormal: 1657 case Builtin::BI__builtin_signbit: 1658 case Builtin::BI__builtin_signbitf: 1659 case Builtin::BI__builtin_signbitl: 1660 if (SemaBuiltinFPClassification(TheCall, 1)) 1661 return ExprError(); 1662 break; 1663 case Builtin::BI__builtin_shufflevector: 1664 return SemaBuiltinShuffleVector(TheCall); 1665 // TheCall will be freed by the smart pointer here, but that's fine, since 1666 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1667 case Builtin::BI__builtin_prefetch: 1668 if (SemaBuiltinPrefetch(TheCall)) 1669 return ExprError(); 1670 break; 1671 case Builtin::BI__builtin_alloca_with_align: 1672 if (SemaBuiltinAllocaWithAlign(TheCall)) 1673 return ExprError(); 1674 LLVM_FALLTHROUGH; 1675 case Builtin::BI__builtin_alloca: 1676 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1677 << TheCall->getDirectCallee(); 1678 break; 1679 case Builtin::BI__arithmetic_fence: 1680 if (SemaBuiltinArithmeticFence(TheCall)) 1681 return ExprError(); 1682 break; 1683 case Builtin::BI__assume: 1684 case Builtin::BI__builtin_assume: 1685 if (SemaBuiltinAssume(TheCall)) 1686 return ExprError(); 1687 break; 1688 case Builtin::BI__builtin_assume_aligned: 1689 if (SemaBuiltinAssumeAligned(TheCall)) 1690 return ExprError(); 1691 break; 1692 case Builtin::BI__builtin_dynamic_object_size: 1693 case Builtin::BI__builtin_object_size: 1694 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1695 return ExprError(); 1696 break; 1697 case Builtin::BI__builtin_longjmp: 1698 if (SemaBuiltinLongjmp(TheCall)) 1699 return ExprError(); 1700 break; 1701 case Builtin::BI__builtin_setjmp: 1702 if (SemaBuiltinSetjmp(TheCall)) 1703 return ExprError(); 1704 break; 1705 case Builtin::BI__builtin_classify_type: 1706 if (checkArgCount(*this, TheCall, 1)) return true; 1707 TheCall->setType(Context.IntTy); 1708 break; 1709 case Builtin::BI__builtin_complex: 1710 if (SemaBuiltinComplex(TheCall)) 1711 return ExprError(); 1712 break; 1713 case Builtin::BI__builtin_constant_p: { 1714 if (checkArgCount(*this, TheCall, 1)) return true; 1715 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1716 if (Arg.isInvalid()) return true; 1717 TheCall->setArg(0, Arg.get()); 1718 TheCall->setType(Context.IntTy); 1719 break; 1720 } 1721 case Builtin::BI__builtin_launder: 1722 return SemaBuiltinLaunder(*this, TheCall); 1723 case Builtin::BI__sync_fetch_and_add: 1724 case Builtin::BI__sync_fetch_and_add_1: 1725 case Builtin::BI__sync_fetch_and_add_2: 1726 case Builtin::BI__sync_fetch_and_add_4: 1727 case Builtin::BI__sync_fetch_and_add_8: 1728 case Builtin::BI__sync_fetch_and_add_16: 1729 case Builtin::BI__sync_fetch_and_sub: 1730 case Builtin::BI__sync_fetch_and_sub_1: 1731 case Builtin::BI__sync_fetch_and_sub_2: 1732 case Builtin::BI__sync_fetch_and_sub_4: 1733 case Builtin::BI__sync_fetch_and_sub_8: 1734 case Builtin::BI__sync_fetch_and_sub_16: 1735 case Builtin::BI__sync_fetch_and_or: 1736 case Builtin::BI__sync_fetch_and_or_1: 1737 case Builtin::BI__sync_fetch_and_or_2: 1738 case Builtin::BI__sync_fetch_and_or_4: 1739 case Builtin::BI__sync_fetch_and_or_8: 1740 case Builtin::BI__sync_fetch_and_or_16: 1741 case Builtin::BI__sync_fetch_and_and: 1742 case Builtin::BI__sync_fetch_and_and_1: 1743 case Builtin::BI__sync_fetch_and_and_2: 1744 case Builtin::BI__sync_fetch_and_and_4: 1745 case Builtin::BI__sync_fetch_and_and_8: 1746 case Builtin::BI__sync_fetch_and_and_16: 1747 case Builtin::BI__sync_fetch_and_xor: 1748 case Builtin::BI__sync_fetch_and_xor_1: 1749 case Builtin::BI__sync_fetch_and_xor_2: 1750 case Builtin::BI__sync_fetch_and_xor_4: 1751 case Builtin::BI__sync_fetch_and_xor_8: 1752 case Builtin::BI__sync_fetch_and_xor_16: 1753 case Builtin::BI__sync_fetch_and_nand: 1754 case Builtin::BI__sync_fetch_and_nand_1: 1755 case Builtin::BI__sync_fetch_and_nand_2: 1756 case Builtin::BI__sync_fetch_and_nand_4: 1757 case Builtin::BI__sync_fetch_and_nand_8: 1758 case Builtin::BI__sync_fetch_and_nand_16: 1759 case Builtin::BI__sync_add_and_fetch: 1760 case Builtin::BI__sync_add_and_fetch_1: 1761 case Builtin::BI__sync_add_and_fetch_2: 1762 case Builtin::BI__sync_add_and_fetch_4: 1763 case Builtin::BI__sync_add_and_fetch_8: 1764 case Builtin::BI__sync_add_and_fetch_16: 1765 case Builtin::BI__sync_sub_and_fetch: 1766 case Builtin::BI__sync_sub_and_fetch_1: 1767 case Builtin::BI__sync_sub_and_fetch_2: 1768 case Builtin::BI__sync_sub_and_fetch_4: 1769 case Builtin::BI__sync_sub_and_fetch_8: 1770 case Builtin::BI__sync_sub_and_fetch_16: 1771 case Builtin::BI__sync_and_and_fetch: 1772 case Builtin::BI__sync_and_and_fetch_1: 1773 case Builtin::BI__sync_and_and_fetch_2: 1774 case Builtin::BI__sync_and_and_fetch_4: 1775 case Builtin::BI__sync_and_and_fetch_8: 1776 case Builtin::BI__sync_and_and_fetch_16: 1777 case Builtin::BI__sync_or_and_fetch: 1778 case Builtin::BI__sync_or_and_fetch_1: 1779 case Builtin::BI__sync_or_and_fetch_2: 1780 case Builtin::BI__sync_or_and_fetch_4: 1781 case Builtin::BI__sync_or_and_fetch_8: 1782 case Builtin::BI__sync_or_and_fetch_16: 1783 case Builtin::BI__sync_xor_and_fetch: 1784 case Builtin::BI__sync_xor_and_fetch_1: 1785 case Builtin::BI__sync_xor_and_fetch_2: 1786 case Builtin::BI__sync_xor_and_fetch_4: 1787 case Builtin::BI__sync_xor_and_fetch_8: 1788 case Builtin::BI__sync_xor_and_fetch_16: 1789 case Builtin::BI__sync_nand_and_fetch: 1790 case Builtin::BI__sync_nand_and_fetch_1: 1791 case Builtin::BI__sync_nand_and_fetch_2: 1792 case Builtin::BI__sync_nand_and_fetch_4: 1793 case Builtin::BI__sync_nand_and_fetch_8: 1794 case Builtin::BI__sync_nand_and_fetch_16: 1795 case Builtin::BI__sync_val_compare_and_swap: 1796 case Builtin::BI__sync_val_compare_and_swap_1: 1797 case Builtin::BI__sync_val_compare_and_swap_2: 1798 case Builtin::BI__sync_val_compare_and_swap_4: 1799 case Builtin::BI__sync_val_compare_and_swap_8: 1800 case Builtin::BI__sync_val_compare_and_swap_16: 1801 case Builtin::BI__sync_bool_compare_and_swap: 1802 case Builtin::BI__sync_bool_compare_and_swap_1: 1803 case Builtin::BI__sync_bool_compare_and_swap_2: 1804 case Builtin::BI__sync_bool_compare_and_swap_4: 1805 case Builtin::BI__sync_bool_compare_and_swap_8: 1806 case Builtin::BI__sync_bool_compare_and_swap_16: 1807 case Builtin::BI__sync_lock_test_and_set: 1808 case Builtin::BI__sync_lock_test_and_set_1: 1809 case Builtin::BI__sync_lock_test_and_set_2: 1810 case Builtin::BI__sync_lock_test_and_set_4: 1811 case Builtin::BI__sync_lock_test_and_set_8: 1812 case Builtin::BI__sync_lock_test_and_set_16: 1813 case Builtin::BI__sync_lock_release: 1814 case Builtin::BI__sync_lock_release_1: 1815 case Builtin::BI__sync_lock_release_2: 1816 case Builtin::BI__sync_lock_release_4: 1817 case Builtin::BI__sync_lock_release_8: 1818 case Builtin::BI__sync_lock_release_16: 1819 case Builtin::BI__sync_swap: 1820 case Builtin::BI__sync_swap_1: 1821 case Builtin::BI__sync_swap_2: 1822 case Builtin::BI__sync_swap_4: 1823 case Builtin::BI__sync_swap_8: 1824 case Builtin::BI__sync_swap_16: 1825 return SemaBuiltinAtomicOverloaded(TheCallResult); 1826 case Builtin::BI__sync_synchronize: 1827 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1828 << TheCall->getCallee()->getSourceRange(); 1829 break; 1830 case Builtin::BI__builtin_nontemporal_load: 1831 case Builtin::BI__builtin_nontemporal_store: 1832 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1833 case Builtin::BI__builtin_memcpy_inline: { 1834 clang::Expr *SizeOp = TheCall->getArg(2); 1835 // We warn about copying to or from `nullptr` pointers when `size` is 1836 // greater than 0. When `size` is value dependent we cannot evaluate its 1837 // value so we bail out. 1838 if (SizeOp->isValueDependent()) 1839 break; 1840 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) { 1841 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1842 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1843 } 1844 break; 1845 } 1846 #define BUILTIN(ID, TYPE, ATTRS) 1847 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1848 case Builtin::BI##ID: \ 1849 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1850 #include "clang/Basic/Builtins.def" 1851 case Builtin::BI__annotation: 1852 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1853 return ExprError(); 1854 break; 1855 case Builtin::BI__builtin_annotation: 1856 if (SemaBuiltinAnnotation(*this, TheCall)) 1857 return ExprError(); 1858 break; 1859 case Builtin::BI__builtin_addressof: 1860 if (SemaBuiltinAddressof(*this, TheCall)) 1861 return ExprError(); 1862 break; 1863 case Builtin::BI__builtin_is_aligned: 1864 case Builtin::BI__builtin_align_up: 1865 case Builtin::BI__builtin_align_down: 1866 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1867 return ExprError(); 1868 break; 1869 case Builtin::BI__builtin_add_overflow: 1870 case Builtin::BI__builtin_sub_overflow: 1871 case Builtin::BI__builtin_mul_overflow: 1872 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1873 return ExprError(); 1874 break; 1875 case Builtin::BI__builtin_operator_new: 1876 case Builtin::BI__builtin_operator_delete: { 1877 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1878 ExprResult Res = 1879 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1880 if (Res.isInvalid()) 1881 CorrectDelayedTyposInExpr(TheCallResult.get()); 1882 return Res; 1883 } 1884 case Builtin::BI__builtin_dump_struct: { 1885 // We first want to ensure we are called with 2 arguments 1886 if (checkArgCount(*this, TheCall, 2)) 1887 return ExprError(); 1888 // Ensure that the first argument is of type 'struct XX *' 1889 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1890 const QualType PtrArgType = PtrArg->getType(); 1891 if (!PtrArgType->isPointerType() || 1892 !PtrArgType->getPointeeType()->isRecordType()) { 1893 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1894 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1895 << "structure pointer"; 1896 return ExprError(); 1897 } 1898 1899 // Ensure that the second argument is of type 'FunctionType' 1900 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1901 const QualType FnPtrArgType = FnPtrArg->getType(); 1902 if (!FnPtrArgType->isPointerType()) { 1903 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1904 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1905 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1906 return ExprError(); 1907 } 1908 1909 const auto *FuncType = 1910 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1911 1912 if (!FuncType) { 1913 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1914 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1915 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1916 return ExprError(); 1917 } 1918 1919 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1920 if (!FT->getNumParams()) { 1921 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1922 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1923 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1924 return ExprError(); 1925 } 1926 QualType PT = FT->getParamType(0); 1927 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1928 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1929 !PT->getPointeeType().isConstQualified()) { 1930 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1931 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1932 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1933 return ExprError(); 1934 } 1935 } 1936 1937 TheCall->setType(Context.IntTy); 1938 break; 1939 } 1940 case Builtin::BI__builtin_expect_with_probability: { 1941 // We first want to ensure we are called with 3 arguments 1942 if (checkArgCount(*this, TheCall, 3)) 1943 return ExprError(); 1944 // then check probability is constant float in range [0.0, 1.0] 1945 const Expr *ProbArg = TheCall->getArg(2); 1946 SmallVector<PartialDiagnosticAt, 8> Notes; 1947 Expr::EvalResult Eval; 1948 Eval.Diag = &Notes; 1949 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1950 !Eval.Val.isFloat()) { 1951 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1952 << ProbArg->getSourceRange(); 1953 for (const PartialDiagnosticAt &PDiag : Notes) 1954 Diag(PDiag.first, PDiag.second); 1955 return ExprError(); 1956 } 1957 llvm::APFloat Probability = Eval.Val.getFloat(); 1958 bool LoseInfo = false; 1959 Probability.convert(llvm::APFloat::IEEEdouble(), 1960 llvm::RoundingMode::Dynamic, &LoseInfo); 1961 if (!(Probability >= llvm::APFloat(0.0) && 1962 Probability <= llvm::APFloat(1.0))) { 1963 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1964 << ProbArg->getSourceRange(); 1965 return ExprError(); 1966 } 1967 break; 1968 } 1969 case Builtin::BI__builtin_preserve_access_index: 1970 if (SemaBuiltinPreserveAI(*this, TheCall)) 1971 return ExprError(); 1972 break; 1973 case Builtin::BI__builtin_call_with_static_chain: 1974 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1975 return ExprError(); 1976 break; 1977 case Builtin::BI__exception_code: 1978 case Builtin::BI_exception_code: 1979 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1980 diag::err_seh___except_block)) 1981 return ExprError(); 1982 break; 1983 case Builtin::BI__exception_info: 1984 case Builtin::BI_exception_info: 1985 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1986 diag::err_seh___except_filter)) 1987 return ExprError(); 1988 break; 1989 case Builtin::BI__GetExceptionInfo: 1990 if (checkArgCount(*this, TheCall, 1)) 1991 return ExprError(); 1992 1993 if (CheckCXXThrowOperand( 1994 TheCall->getBeginLoc(), 1995 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1996 TheCall)) 1997 return ExprError(); 1998 1999 TheCall->setType(Context.VoidPtrTy); 2000 break; 2001 // OpenCL v2.0, s6.13.16 - Pipe functions 2002 case Builtin::BIread_pipe: 2003 case Builtin::BIwrite_pipe: 2004 // Since those two functions are declared with var args, we need a semantic 2005 // check for the argument. 2006 if (SemaBuiltinRWPipe(*this, TheCall)) 2007 return ExprError(); 2008 break; 2009 case Builtin::BIreserve_read_pipe: 2010 case Builtin::BIreserve_write_pipe: 2011 case Builtin::BIwork_group_reserve_read_pipe: 2012 case Builtin::BIwork_group_reserve_write_pipe: 2013 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 2014 return ExprError(); 2015 break; 2016 case Builtin::BIsub_group_reserve_read_pipe: 2017 case Builtin::BIsub_group_reserve_write_pipe: 2018 if (checkOpenCLSubgroupExt(*this, TheCall) || 2019 SemaBuiltinReserveRWPipe(*this, TheCall)) 2020 return ExprError(); 2021 break; 2022 case Builtin::BIcommit_read_pipe: 2023 case Builtin::BIcommit_write_pipe: 2024 case Builtin::BIwork_group_commit_read_pipe: 2025 case Builtin::BIwork_group_commit_write_pipe: 2026 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 2027 return ExprError(); 2028 break; 2029 case Builtin::BIsub_group_commit_read_pipe: 2030 case Builtin::BIsub_group_commit_write_pipe: 2031 if (checkOpenCLSubgroupExt(*this, TheCall) || 2032 SemaBuiltinCommitRWPipe(*this, TheCall)) 2033 return ExprError(); 2034 break; 2035 case Builtin::BIget_pipe_num_packets: 2036 case Builtin::BIget_pipe_max_packets: 2037 if (SemaBuiltinPipePackets(*this, TheCall)) 2038 return ExprError(); 2039 break; 2040 case Builtin::BIto_global: 2041 case Builtin::BIto_local: 2042 case Builtin::BIto_private: 2043 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 2044 return ExprError(); 2045 break; 2046 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 2047 case Builtin::BIenqueue_kernel: 2048 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 2049 return ExprError(); 2050 break; 2051 case Builtin::BIget_kernel_work_group_size: 2052 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 2053 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 2054 return ExprError(); 2055 break; 2056 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 2057 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 2058 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 2059 return ExprError(); 2060 break; 2061 case Builtin::BI__builtin_os_log_format: 2062 Cleanup.setExprNeedsCleanups(true); 2063 LLVM_FALLTHROUGH; 2064 case Builtin::BI__builtin_os_log_format_buffer_size: 2065 if (SemaBuiltinOSLogFormat(TheCall)) 2066 return ExprError(); 2067 break; 2068 case Builtin::BI__builtin_frame_address: 2069 case Builtin::BI__builtin_return_address: { 2070 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 2071 return ExprError(); 2072 2073 // -Wframe-address warning if non-zero passed to builtin 2074 // return/frame address. 2075 Expr::EvalResult Result; 2076 if (!TheCall->getArg(0)->isValueDependent() && 2077 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 2078 Result.Val.getInt() != 0) 2079 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 2080 << ((BuiltinID == Builtin::BI__builtin_return_address) 2081 ? "__builtin_return_address" 2082 : "__builtin_frame_address") 2083 << TheCall->getSourceRange(); 2084 break; 2085 } 2086 2087 case Builtin::BI__builtin_elementwise_abs: 2088 if (SemaBuiltinElementwiseMathOneArg(TheCall)) 2089 return ExprError(); 2090 break; 2091 case Builtin::BI__builtin_elementwise_min: 2092 case Builtin::BI__builtin_elementwise_max: 2093 if (SemaBuiltinElementwiseMath(TheCall)) 2094 return ExprError(); 2095 break; 2096 case Builtin::BI__builtin_matrix_transpose: 2097 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 2098 2099 case Builtin::BI__builtin_matrix_column_major_load: 2100 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 2101 2102 case Builtin::BI__builtin_matrix_column_major_store: 2103 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 2104 2105 case Builtin::BI__builtin_get_device_side_mangled_name: { 2106 auto Check = [](CallExpr *TheCall) { 2107 if (TheCall->getNumArgs() != 1) 2108 return false; 2109 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 2110 if (!DRE) 2111 return false; 2112 auto *D = DRE->getDecl(); 2113 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 2114 return false; 2115 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 2116 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 2117 }; 2118 if (!Check(TheCall)) { 2119 Diag(TheCall->getBeginLoc(), 2120 diag::err_hip_invalid_args_builtin_mangled_name); 2121 return ExprError(); 2122 } 2123 } 2124 } 2125 2126 // Since the target specific builtins for each arch overlap, only check those 2127 // of the arch we are compiling for. 2128 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 2129 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 2130 assert(Context.getAuxTargetInfo() && 2131 "Aux Target Builtin, but not an aux target?"); 2132 2133 if (CheckTSBuiltinFunctionCall( 2134 *Context.getAuxTargetInfo(), 2135 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2136 return ExprError(); 2137 } else { 2138 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2139 TheCall)) 2140 return ExprError(); 2141 } 2142 } 2143 2144 return TheCallResult; 2145 } 2146 2147 // Get the valid immediate range for the specified NEON type code. 2148 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2149 NeonTypeFlags Type(t); 2150 int IsQuad = ForceQuad ? true : Type.isQuad(); 2151 switch (Type.getEltType()) { 2152 case NeonTypeFlags::Int8: 2153 case NeonTypeFlags::Poly8: 2154 return shift ? 7 : (8 << IsQuad) - 1; 2155 case NeonTypeFlags::Int16: 2156 case NeonTypeFlags::Poly16: 2157 return shift ? 15 : (4 << IsQuad) - 1; 2158 case NeonTypeFlags::Int32: 2159 return shift ? 31 : (2 << IsQuad) - 1; 2160 case NeonTypeFlags::Int64: 2161 case NeonTypeFlags::Poly64: 2162 return shift ? 63 : (1 << IsQuad) - 1; 2163 case NeonTypeFlags::Poly128: 2164 return shift ? 127 : (1 << IsQuad) - 1; 2165 case NeonTypeFlags::Float16: 2166 assert(!shift && "cannot shift float types!"); 2167 return (4 << IsQuad) - 1; 2168 case NeonTypeFlags::Float32: 2169 assert(!shift && "cannot shift float types!"); 2170 return (2 << IsQuad) - 1; 2171 case NeonTypeFlags::Float64: 2172 assert(!shift && "cannot shift float types!"); 2173 return (1 << IsQuad) - 1; 2174 case NeonTypeFlags::BFloat16: 2175 assert(!shift && "cannot shift float types!"); 2176 return (4 << IsQuad) - 1; 2177 } 2178 llvm_unreachable("Invalid NeonTypeFlag!"); 2179 } 2180 2181 /// getNeonEltType - Return the QualType corresponding to the elements of 2182 /// the vector type specified by the NeonTypeFlags. This is used to check 2183 /// the pointer arguments for Neon load/store intrinsics. 2184 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2185 bool IsPolyUnsigned, bool IsInt64Long) { 2186 switch (Flags.getEltType()) { 2187 case NeonTypeFlags::Int8: 2188 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2189 case NeonTypeFlags::Int16: 2190 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2191 case NeonTypeFlags::Int32: 2192 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2193 case NeonTypeFlags::Int64: 2194 if (IsInt64Long) 2195 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2196 else 2197 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2198 : Context.LongLongTy; 2199 case NeonTypeFlags::Poly8: 2200 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2201 case NeonTypeFlags::Poly16: 2202 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2203 case NeonTypeFlags::Poly64: 2204 if (IsInt64Long) 2205 return Context.UnsignedLongTy; 2206 else 2207 return Context.UnsignedLongLongTy; 2208 case NeonTypeFlags::Poly128: 2209 break; 2210 case NeonTypeFlags::Float16: 2211 return Context.HalfTy; 2212 case NeonTypeFlags::Float32: 2213 return Context.FloatTy; 2214 case NeonTypeFlags::Float64: 2215 return Context.DoubleTy; 2216 case NeonTypeFlags::BFloat16: 2217 return Context.BFloat16Ty; 2218 } 2219 llvm_unreachable("Invalid NeonTypeFlag!"); 2220 } 2221 2222 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2223 // Range check SVE intrinsics that take immediate values. 2224 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2225 2226 switch (BuiltinID) { 2227 default: 2228 return false; 2229 #define GET_SVE_IMMEDIATE_CHECK 2230 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2231 #undef GET_SVE_IMMEDIATE_CHECK 2232 } 2233 2234 // Perform all the immediate checks for this builtin call. 2235 bool HasError = false; 2236 for (auto &I : ImmChecks) { 2237 int ArgNum, CheckTy, ElementSizeInBits; 2238 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2239 2240 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2241 2242 // Function that checks whether the operand (ArgNum) is an immediate 2243 // that is one of the predefined values. 2244 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2245 int ErrDiag) -> bool { 2246 // We can't check the value of a dependent argument. 2247 Expr *Arg = TheCall->getArg(ArgNum); 2248 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2249 return false; 2250 2251 // Check constant-ness first. 2252 llvm::APSInt Imm; 2253 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2254 return true; 2255 2256 if (!CheckImm(Imm.getSExtValue())) 2257 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2258 return false; 2259 }; 2260 2261 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2262 case SVETypeFlags::ImmCheck0_31: 2263 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2264 HasError = true; 2265 break; 2266 case SVETypeFlags::ImmCheck0_13: 2267 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2268 HasError = true; 2269 break; 2270 case SVETypeFlags::ImmCheck1_16: 2271 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2272 HasError = true; 2273 break; 2274 case SVETypeFlags::ImmCheck0_7: 2275 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2276 HasError = true; 2277 break; 2278 case SVETypeFlags::ImmCheckExtract: 2279 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2280 (2048 / ElementSizeInBits) - 1)) 2281 HasError = true; 2282 break; 2283 case SVETypeFlags::ImmCheckShiftRight: 2284 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2285 HasError = true; 2286 break; 2287 case SVETypeFlags::ImmCheckShiftRightNarrow: 2288 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2289 ElementSizeInBits / 2)) 2290 HasError = true; 2291 break; 2292 case SVETypeFlags::ImmCheckShiftLeft: 2293 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2294 ElementSizeInBits - 1)) 2295 HasError = true; 2296 break; 2297 case SVETypeFlags::ImmCheckLaneIndex: 2298 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2299 (128 / (1 * ElementSizeInBits)) - 1)) 2300 HasError = true; 2301 break; 2302 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2303 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2304 (128 / (2 * ElementSizeInBits)) - 1)) 2305 HasError = true; 2306 break; 2307 case SVETypeFlags::ImmCheckLaneIndexDot: 2308 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2309 (128 / (4 * ElementSizeInBits)) - 1)) 2310 HasError = true; 2311 break; 2312 case SVETypeFlags::ImmCheckComplexRot90_270: 2313 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2314 diag::err_rotation_argument_to_cadd)) 2315 HasError = true; 2316 break; 2317 case SVETypeFlags::ImmCheckComplexRotAll90: 2318 if (CheckImmediateInSet( 2319 [](int64_t V) { 2320 return V == 0 || V == 90 || V == 180 || V == 270; 2321 }, 2322 diag::err_rotation_argument_to_cmla)) 2323 HasError = true; 2324 break; 2325 case SVETypeFlags::ImmCheck0_1: 2326 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2327 HasError = true; 2328 break; 2329 case SVETypeFlags::ImmCheck0_2: 2330 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2331 HasError = true; 2332 break; 2333 case SVETypeFlags::ImmCheck0_3: 2334 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2335 HasError = true; 2336 break; 2337 } 2338 } 2339 2340 return HasError; 2341 } 2342 2343 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2344 unsigned BuiltinID, CallExpr *TheCall) { 2345 llvm::APSInt Result; 2346 uint64_t mask = 0; 2347 unsigned TV = 0; 2348 int PtrArgNum = -1; 2349 bool HasConstPtr = false; 2350 switch (BuiltinID) { 2351 #define GET_NEON_OVERLOAD_CHECK 2352 #include "clang/Basic/arm_neon.inc" 2353 #include "clang/Basic/arm_fp16.inc" 2354 #undef GET_NEON_OVERLOAD_CHECK 2355 } 2356 2357 // For NEON intrinsics which are overloaded on vector element type, validate 2358 // the immediate which specifies which variant to emit. 2359 unsigned ImmArg = TheCall->getNumArgs()-1; 2360 if (mask) { 2361 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2362 return true; 2363 2364 TV = Result.getLimitedValue(64); 2365 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2366 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2367 << TheCall->getArg(ImmArg)->getSourceRange(); 2368 } 2369 2370 if (PtrArgNum >= 0) { 2371 // Check that pointer arguments have the specified type. 2372 Expr *Arg = TheCall->getArg(PtrArgNum); 2373 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2374 Arg = ICE->getSubExpr(); 2375 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2376 QualType RHSTy = RHS.get()->getType(); 2377 2378 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2379 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2380 Arch == llvm::Triple::aarch64_32 || 2381 Arch == llvm::Triple::aarch64_be; 2382 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2383 QualType EltTy = 2384 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2385 if (HasConstPtr) 2386 EltTy = EltTy.withConst(); 2387 QualType LHSTy = Context.getPointerType(EltTy); 2388 AssignConvertType ConvTy; 2389 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2390 if (RHS.isInvalid()) 2391 return true; 2392 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2393 RHS.get(), AA_Assigning)) 2394 return true; 2395 } 2396 2397 // For NEON intrinsics which take an immediate value as part of the 2398 // instruction, range check them here. 2399 unsigned i = 0, l = 0, u = 0; 2400 switch (BuiltinID) { 2401 default: 2402 return false; 2403 #define GET_NEON_IMMEDIATE_CHECK 2404 #include "clang/Basic/arm_neon.inc" 2405 #include "clang/Basic/arm_fp16.inc" 2406 #undef GET_NEON_IMMEDIATE_CHECK 2407 } 2408 2409 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2410 } 2411 2412 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2413 switch (BuiltinID) { 2414 default: 2415 return false; 2416 #include "clang/Basic/arm_mve_builtin_sema.inc" 2417 } 2418 } 2419 2420 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2421 CallExpr *TheCall) { 2422 bool Err = false; 2423 switch (BuiltinID) { 2424 default: 2425 return false; 2426 #include "clang/Basic/arm_cde_builtin_sema.inc" 2427 } 2428 2429 if (Err) 2430 return true; 2431 2432 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2433 } 2434 2435 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2436 const Expr *CoprocArg, bool WantCDE) { 2437 if (isConstantEvaluated()) 2438 return false; 2439 2440 // We can't check the value of a dependent argument. 2441 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2442 return false; 2443 2444 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2445 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2446 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2447 2448 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2449 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2450 2451 if (IsCDECoproc != WantCDE) 2452 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2453 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2454 2455 return false; 2456 } 2457 2458 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2459 unsigned MaxWidth) { 2460 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2461 BuiltinID == ARM::BI__builtin_arm_ldaex || 2462 BuiltinID == ARM::BI__builtin_arm_strex || 2463 BuiltinID == ARM::BI__builtin_arm_stlex || 2464 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2465 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2466 BuiltinID == AArch64::BI__builtin_arm_strex || 2467 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2468 "unexpected ARM builtin"); 2469 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2470 BuiltinID == ARM::BI__builtin_arm_ldaex || 2471 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2472 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2473 2474 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2475 2476 // Ensure that we have the proper number of arguments. 2477 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2478 return true; 2479 2480 // Inspect the pointer argument of the atomic builtin. This should always be 2481 // a pointer type, whose element is an integral scalar or pointer type. 2482 // Because it is a pointer type, we don't have to worry about any implicit 2483 // casts here. 2484 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2485 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2486 if (PointerArgRes.isInvalid()) 2487 return true; 2488 PointerArg = PointerArgRes.get(); 2489 2490 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2491 if (!pointerType) { 2492 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2493 << PointerArg->getType() << PointerArg->getSourceRange(); 2494 return true; 2495 } 2496 2497 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2498 // task is to insert the appropriate casts into the AST. First work out just 2499 // what the appropriate type is. 2500 QualType ValType = pointerType->getPointeeType(); 2501 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2502 if (IsLdrex) 2503 AddrType.addConst(); 2504 2505 // Issue a warning if the cast is dodgy. 2506 CastKind CastNeeded = CK_NoOp; 2507 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2508 CastNeeded = CK_BitCast; 2509 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2510 << PointerArg->getType() << Context.getPointerType(AddrType) 2511 << AA_Passing << PointerArg->getSourceRange(); 2512 } 2513 2514 // Finally, do the cast and replace the argument with the corrected version. 2515 AddrType = Context.getPointerType(AddrType); 2516 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2517 if (PointerArgRes.isInvalid()) 2518 return true; 2519 PointerArg = PointerArgRes.get(); 2520 2521 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2522 2523 // In general, we allow ints, floats and pointers to be loaded and stored. 2524 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2525 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2526 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2527 << PointerArg->getType() << PointerArg->getSourceRange(); 2528 return true; 2529 } 2530 2531 // But ARM doesn't have instructions to deal with 128-bit versions. 2532 if (Context.getTypeSize(ValType) > MaxWidth) { 2533 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2534 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2535 << PointerArg->getType() << PointerArg->getSourceRange(); 2536 return true; 2537 } 2538 2539 switch (ValType.getObjCLifetime()) { 2540 case Qualifiers::OCL_None: 2541 case Qualifiers::OCL_ExplicitNone: 2542 // okay 2543 break; 2544 2545 case Qualifiers::OCL_Weak: 2546 case Qualifiers::OCL_Strong: 2547 case Qualifiers::OCL_Autoreleasing: 2548 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2549 << ValType << PointerArg->getSourceRange(); 2550 return true; 2551 } 2552 2553 if (IsLdrex) { 2554 TheCall->setType(ValType); 2555 return false; 2556 } 2557 2558 // Initialize the argument to be stored. 2559 ExprResult ValArg = TheCall->getArg(0); 2560 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2561 Context, ValType, /*consume*/ false); 2562 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2563 if (ValArg.isInvalid()) 2564 return true; 2565 TheCall->setArg(0, ValArg.get()); 2566 2567 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2568 // but the custom checker bypasses all default analysis. 2569 TheCall->setType(Context.IntTy); 2570 return false; 2571 } 2572 2573 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2574 CallExpr *TheCall) { 2575 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2576 BuiltinID == ARM::BI__builtin_arm_ldaex || 2577 BuiltinID == ARM::BI__builtin_arm_strex || 2578 BuiltinID == ARM::BI__builtin_arm_stlex) { 2579 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2580 } 2581 2582 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2583 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2584 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2585 } 2586 2587 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2588 BuiltinID == ARM::BI__builtin_arm_wsr64) 2589 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2590 2591 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2592 BuiltinID == ARM::BI__builtin_arm_rsrp || 2593 BuiltinID == ARM::BI__builtin_arm_wsr || 2594 BuiltinID == ARM::BI__builtin_arm_wsrp) 2595 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2596 2597 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2598 return true; 2599 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2600 return true; 2601 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2602 return true; 2603 2604 // For intrinsics which take an immediate value as part of the instruction, 2605 // range check them here. 2606 // FIXME: VFP Intrinsics should error if VFP not present. 2607 switch (BuiltinID) { 2608 default: return false; 2609 case ARM::BI__builtin_arm_ssat: 2610 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2611 case ARM::BI__builtin_arm_usat: 2612 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2613 case ARM::BI__builtin_arm_ssat16: 2614 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2615 case ARM::BI__builtin_arm_usat16: 2616 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2617 case ARM::BI__builtin_arm_vcvtr_f: 2618 case ARM::BI__builtin_arm_vcvtr_d: 2619 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2620 case ARM::BI__builtin_arm_dmb: 2621 case ARM::BI__builtin_arm_dsb: 2622 case ARM::BI__builtin_arm_isb: 2623 case ARM::BI__builtin_arm_dbg: 2624 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2625 case ARM::BI__builtin_arm_cdp: 2626 case ARM::BI__builtin_arm_cdp2: 2627 case ARM::BI__builtin_arm_mcr: 2628 case ARM::BI__builtin_arm_mcr2: 2629 case ARM::BI__builtin_arm_mrc: 2630 case ARM::BI__builtin_arm_mrc2: 2631 case ARM::BI__builtin_arm_mcrr: 2632 case ARM::BI__builtin_arm_mcrr2: 2633 case ARM::BI__builtin_arm_mrrc: 2634 case ARM::BI__builtin_arm_mrrc2: 2635 case ARM::BI__builtin_arm_ldc: 2636 case ARM::BI__builtin_arm_ldcl: 2637 case ARM::BI__builtin_arm_ldc2: 2638 case ARM::BI__builtin_arm_ldc2l: 2639 case ARM::BI__builtin_arm_stc: 2640 case ARM::BI__builtin_arm_stcl: 2641 case ARM::BI__builtin_arm_stc2: 2642 case ARM::BI__builtin_arm_stc2l: 2643 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2644 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2645 /*WantCDE*/ false); 2646 } 2647 } 2648 2649 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2650 unsigned BuiltinID, 2651 CallExpr *TheCall) { 2652 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2653 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2654 BuiltinID == AArch64::BI__builtin_arm_strex || 2655 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2656 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2657 } 2658 2659 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2660 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2661 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2662 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2663 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2664 } 2665 2666 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2667 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2668 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2669 2670 // Memory Tagging Extensions (MTE) Intrinsics 2671 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2672 BuiltinID == AArch64::BI__builtin_arm_addg || 2673 BuiltinID == AArch64::BI__builtin_arm_gmi || 2674 BuiltinID == AArch64::BI__builtin_arm_ldg || 2675 BuiltinID == AArch64::BI__builtin_arm_stg || 2676 BuiltinID == AArch64::BI__builtin_arm_subp) { 2677 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2678 } 2679 2680 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2681 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2682 BuiltinID == AArch64::BI__builtin_arm_wsr || 2683 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2684 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2685 2686 // Only check the valid encoding range. Any constant in this range would be 2687 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2688 // an exception for incorrect registers. This matches MSVC behavior. 2689 if (BuiltinID == AArch64::BI_ReadStatusReg || 2690 BuiltinID == AArch64::BI_WriteStatusReg) 2691 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2692 2693 if (BuiltinID == AArch64::BI__getReg) 2694 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2695 2696 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2697 return true; 2698 2699 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2700 return true; 2701 2702 // For intrinsics which take an immediate value as part of the instruction, 2703 // range check them here. 2704 unsigned i = 0, l = 0, u = 0; 2705 switch (BuiltinID) { 2706 default: return false; 2707 case AArch64::BI__builtin_arm_dmb: 2708 case AArch64::BI__builtin_arm_dsb: 2709 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2710 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2711 } 2712 2713 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2714 } 2715 2716 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2717 if (Arg->getType()->getAsPlaceholderType()) 2718 return false; 2719 2720 // The first argument needs to be a record field access. 2721 // If it is an array element access, we delay decision 2722 // to BPF backend to check whether the access is a 2723 // field access or not. 2724 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2725 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2726 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2727 } 2728 2729 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2730 QualType VectorTy, QualType EltTy) { 2731 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2732 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2733 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2734 << Call->getSourceRange() << VectorEltTy << EltTy; 2735 return false; 2736 } 2737 return true; 2738 } 2739 2740 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2741 QualType ArgType = Arg->getType(); 2742 if (ArgType->getAsPlaceholderType()) 2743 return false; 2744 2745 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2746 // format: 2747 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2748 // 2. <type> var; 2749 // __builtin_preserve_type_info(var, flag); 2750 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2751 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2752 return false; 2753 2754 // Typedef type. 2755 if (ArgType->getAs<TypedefType>()) 2756 return true; 2757 2758 // Record type or Enum type. 2759 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2760 if (const auto *RT = Ty->getAs<RecordType>()) { 2761 if (!RT->getDecl()->getDeclName().isEmpty()) 2762 return true; 2763 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2764 if (!ET->getDecl()->getDeclName().isEmpty()) 2765 return true; 2766 } 2767 2768 return false; 2769 } 2770 2771 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2772 QualType ArgType = Arg->getType(); 2773 if (ArgType->getAsPlaceholderType()) 2774 return false; 2775 2776 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2777 // format: 2778 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2779 // flag); 2780 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2781 if (!UO) 2782 return false; 2783 2784 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2785 if (!CE) 2786 return false; 2787 if (CE->getCastKind() != CK_IntegralToPointer && 2788 CE->getCastKind() != CK_NullToPointer) 2789 return false; 2790 2791 // The integer must be from an EnumConstantDecl. 2792 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2793 if (!DR) 2794 return false; 2795 2796 const EnumConstantDecl *Enumerator = 2797 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2798 if (!Enumerator) 2799 return false; 2800 2801 // The type must be EnumType. 2802 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2803 const auto *ET = Ty->getAs<EnumType>(); 2804 if (!ET) 2805 return false; 2806 2807 // The enum value must be supported. 2808 return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator); 2809 } 2810 2811 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2812 CallExpr *TheCall) { 2813 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2814 BuiltinID == BPF::BI__builtin_btf_type_id || 2815 BuiltinID == BPF::BI__builtin_preserve_type_info || 2816 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2817 "unexpected BPF builtin"); 2818 2819 if (checkArgCount(*this, TheCall, 2)) 2820 return true; 2821 2822 // The second argument needs to be a constant int 2823 Expr *Arg = TheCall->getArg(1); 2824 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2825 diag::kind kind; 2826 if (!Value) { 2827 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2828 kind = diag::err_preserve_field_info_not_const; 2829 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2830 kind = diag::err_btf_type_id_not_const; 2831 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2832 kind = diag::err_preserve_type_info_not_const; 2833 else 2834 kind = diag::err_preserve_enum_value_not_const; 2835 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2836 return true; 2837 } 2838 2839 // The first argument 2840 Arg = TheCall->getArg(0); 2841 bool InvalidArg = false; 2842 bool ReturnUnsignedInt = true; 2843 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2844 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2845 InvalidArg = true; 2846 kind = diag::err_preserve_field_info_not_field; 2847 } 2848 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2849 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2850 InvalidArg = true; 2851 kind = diag::err_preserve_type_info_invalid; 2852 } 2853 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2854 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2855 InvalidArg = true; 2856 kind = diag::err_preserve_enum_value_invalid; 2857 } 2858 ReturnUnsignedInt = false; 2859 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2860 ReturnUnsignedInt = false; 2861 } 2862 2863 if (InvalidArg) { 2864 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2865 return true; 2866 } 2867 2868 if (ReturnUnsignedInt) 2869 TheCall->setType(Context.UnsignedIntTy); 2870 else 2871 TheCall->setType(Context.UnsignedLongTy); 2872 return false; 2873 } 2874 2875 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2876 struct ArgInfo { 2877 uint8_t OpNum; 2878 bool IsSigned; 2879 uint8_t BitWidth; 2880 uint8_t Align; 2881 }; 2882 struct BuiltinInfo { 2883 unsigned BuiltinID; 2884 ArgInfo Infos[2]; 2885 }; 2886 2887 static BuiltinInfo Infos[] = { 2888 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2889 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2890 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2891 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2892 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2893 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2894 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2895 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2896 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2897 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2898 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2899 2900 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2907 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2909 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2910 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2911 2912 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2914 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2919 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2921 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2922 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2924 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2927 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2928 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2930 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2931 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2934 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2939 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2940 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2941 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2942 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2943 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2944 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2945 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2946 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2947 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2948 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2949 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2950 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2951 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2952 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2953 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2954 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2955 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2956 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2957 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2958 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2959 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2960 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2961 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2962 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2963 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2964 {{ 1, false, 6, 0 }} }, 2965 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2966 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2967 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2968 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2969 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2970 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2971 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2972 {{ 1, false, 5, 0 }} }, 2973 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2974 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2975 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2976 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2977 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2978 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2979 { 2, false, 5, 0 }} }, 2980 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2981 { 2, false, 6, 0 }} }, 2982 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2983 { 3, false, 5, 0 }} }, 2984 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2985 { 3, false, 6, 0 }} }, 2986 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2987 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2988 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2989 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2990 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2991 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2992 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2993 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2994 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2995 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2996 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2997 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2998 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2999 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 3000 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 3001 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 3002 {{ 2, false, 4, 0 }, 3003 { 3, false, 5, 0 }} }, 3004 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 3005 {{ 2, false, 4, 0 }, 3006 { 3, false, 5, 0 }} }, 3007 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 3008 {{ 2, false, 4, 0 }, 3009 { 3, false, 5, 0 }} }, 3010 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 3011 {{ 2, false, 4, 0 }, 3012 { 3, false, 5, 0 }} }, 3013 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 3014 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 3015 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 3016 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 3017 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 3018 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 3019 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 3020 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 3021 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 3022 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 3023 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 3024 { 2, false, 5, 0 }} }, 3025 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 3026 { 2, false, 6, 0 }} }, 3027 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 3028 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 3029 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 3030 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 3031 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 3032 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 3033 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 3034 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 3035 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 3036 {{ 1, false, 4, 0 }} }, 3037 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 3038 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 3039 {{ 1, false, 4, 0 }} }, 3040 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 3041 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 3042 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 3043 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 3044 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 3045 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 3046 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 3047 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 3048 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 3049 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 3050 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 3051 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 3052 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 3053 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 3054 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 3055 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 3056 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 3057 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 3058 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 3059 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 3060 {{ 3, false, 1, 0 }} }, 3061 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 3062 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 3063 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 3064 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 3065 {{ 3, false, 1, 0 }} }, 3066 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 3067 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 3068 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 3069 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 3070 {{ 3, false, 1, 0 }} }, 3071 }; 3072 3073 // Use a dynamically initialized static to sort the table exactly once on 3074 // first run. 3075 static const bool SortOnce = 3076 (llvm::sort(Infos, 3077 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 3078 return LHS.BuiltinID < RHS.BuiltinID; 3079 }), 3080 true); 3081 (void)SortOnce; 3082 3083 const BuiltinInfo *F = llvm::partition_point( 3084 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 3085 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 3086 return false; 3087 3088 bool Error = false; 3089 3090 for (const ArgInfo &A : F->Infos) { 3091 // Ignore empty ArgInfo elements. 3092 if (A.BitWidth == 0) 3093 continue; 3094 3095 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 3096 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 3097 if (!A.Align) { 3098 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3099 } else { 3100 unsigned M = 1 << A.Align; 3101 Min *= M; 3102 Max *= M; 3103 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 3104 Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 3105 } 3106 } 3107 return Error; 3108 } 3109 3110 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 3111 CallExpr *TheCall) { 3112 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 3113 } 3114 3115 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 3116 unsigned BuiltinID, CallExpr *TheCall) { 3117 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 3118 CheckMipsBuiltinArgument(BuiltinID, TheCall); 3119 } 3120 3121 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 3122 CallExpr *TheCall) { 3123 3124 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 3125 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3126 if (!TI.hasFeature("dsp")) 3127 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3128 } 3129 3130 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3131 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3132 if (!TI.hasFeature("dspr2")) 3133 return Diag(TheCall->getBeginLoc(), 3134 diag::err_mips_builtin_requires_dspr2); 3135 } 3136 3137 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3138 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3139 if (!TI.hasFeature("msa")) 3140 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3141 } 3142 3143 return false; 3144 } 3145 3146 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3147 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3148 // ordering for DSP is unspecified. MSA is ordered by the data format used 3149 // by the underlying instruction i.e., df/m, df/n and then by size. 3150 // 3151 // FIXME: The size tests here should instead be tablegen'd along with the 3152 // definitions from include/clang/Basic/BuiltinsMips.def. 3153 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3154 // be too. 3155 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3156 unsigned i = 0, l = 0, u = 0, m = 0; 3157 switch (BuiltinID) { 3158 default: return false; 3159 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3160 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3161 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3162 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3163 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3164 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3165 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3166 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3167 // df/m field. 3168 // These intrinsics take an unsigned 3 bit immediate. 3169 case Mips::BI__builtin_msa_bclri_b: 3170 case Mips::BI__builtin_msa_bnegi_b: 3171 case Mips::BI__builtin_msa_bseti_b: 3172 case Mips::BI__builtin_msa_sat_s_b: 3173 case Mips::BI__builtin_msa_sat_u_b: 3174 case Mips::BI__builtin_msa_slli_b: 3175 case Mips::BI__builtin_msa_srai_b: 3176 case Mips::BI__builtin_msa_srari_b: 3177 case Mips::BI__builtin_msa_srli_b: 3178 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3179 case Mips::BI__builtin_msa_binsli_b: 3180 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3181 // These intrinsics take an unsigned 4 bit immediate. 3182 case Mips::BI__builtin_msa_bclri_h: 3183 case Mips::BI__builtin_msa_bnegi_h: 3184 case Mips::BI__builtin_msa_bseti_h: 3185 case Mips::BI__builtin_msa_sat_s_h: 3186 case Mips::BI__builtin_msa_sat_u_h: 3187 case Mips::BI__builtin_msa_slli_h: 3188 case Mips::BI__builtin_msa_srai_h: 3189 case Mips::BI__builtin_msa_srari_h: 3190 case Mips::BI__builtin_msa_srli_h: 3191 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3192 case Mips::BI__builtin_msa_binsli_h: 3193 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3194 // These intrinsics take an unsigned 5 bit immediate. 3195 // The first block of intrinsics actually have an unsigned 5 bit field, 3196 // not a df/n field. 3197 case Mips::BI__builtin_msa_cfcmsa: 3198 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3199 case Mips::BI__builtin_msa_clei_u_b: 3200 case Mips::BI__builtin_msa_clei_u_h: 3201 case Mips::BI__builtin_msa_clei_u_w: 3202 case Mips::BI__builtin_msa_clei_u_d: 3203 case Mips::BI__builtin_msa_clti_u_b: 3204 case Mips::BI__builtin_msa_clti_u_h: 3205 case Mips::BI__builtin_msa_clti_u_w: 3206 case Mips::BI__builtin_msa_clti_u_d: 3207 case Mips::BI__builtin_msa_maxi_u_b: 3208 case Mips::BI__builtin_msa_maxi_u_h: 3209 case Mips::BI__builtin_msa_maxi_u_w: 3210 case Mips::BI__builtin_msa_maxi_u_d: 3211 case Mips::BI__builtin_msa_mini_u_b: 3212 case Mips::BI__builtin_msa_mini_u_h: 3213 case Mips::BI__builtin_msa_mini_u_w: 3214 case Mips::BI__builtin_msa_mini_u_d: 3215 case Mips::BI__builtin_msa_addvi_b: 3216 case Mips::BI__builtin_msa_addvi_h: 3217 case Mips::BI__builtin_msa_addvi_w: 3218 case Mips::BI__builtin_msa_addvi_d: 3219 case Mips::BI__builtin_msa_bclri_w: 3220 case Mips::BI__builtin_msa_bnegi_w: 3221 case Mips::BI__builtin_msa_bseti_w: 3222 case Mips::BI__builtin_msa_sat_s_w: 3223 case Mips::BI__builtin_msa_sat_u_w: 3224 case Mips::BI__builtin_msa_slli_w: 3225 case Mips::BI__builtin_msa_srai_w: 3226 case Mips::BI__builtin_msa_srari_w: 3227 case Mips::BI__builtin_msa_srli_w: 3228 case Mips::BI__builtin_msa_srlri_w: 3229 case Mips::BI__builtin_msa_subvi_b: 3230 case Mips::BI__builtin_msa_subvi_h: 3231 case Mips::BI__builtin_msa_subvi_w: 3232 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3233 case Mips::BI__builtin_msa_binsli_w: 3234 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3235 // These intrinsics take an unsigned 6 bit immediate. 3236 case Mips::BI__builtin_msa_bclri_d: 3237 case Mips::BI__builtin_msa_bnegi_d: 3238 case Mips::BI__builtin_msa_bseti_d: 3239 case Mips::BI__builtin_msa_sat_s_d: 3240 case Mips::BI__builtin_msa_sat_u_d: 3241 case Mips::BI__builtin_msa_slli_d: 3242 case Mips::BI__builtin_msa_srai_d: 3243 case Mips::BI__builtin_msa_srari_d: 3244 case Mips::BI__builtin_msa_srli_d: 3245 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3246 case Mips::BI__builtin_msa_binsli_d: 3247 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3248 // These intrinsics take a signed 5 bit immediate. 3249 case Mips::BI__builtin_msa_ceqi_b: 3250 case Mips::BI__builtin_msa_ceqi_h: 3251 case Mips::BI__builtin_msa_ceqi_w: 3252 case Mips::BI__builtin_msa_ceqi_d: 3253 case Mips::BI__builtin_msa_clti_s_b: 3254 case Mips::BI__builtin_msa_clti_s_h: 3255 case Mips::BI__builtin_msa_clti_s_w: 3256 case Mips::BI__builtin_msa_clti_s_d: 3257 case Mips::BI__builtin_msa_clei_s_b: 3258 case Mips::BI__builtin_msa_clei_s_h: 3259 case Mips::BI__builtin_msa_clei_s_w: 3260 case Mips::BI__builtin_msa_clei_s_d: 3261 case Mips::BI__builtin_msa_maxi_s_b: 3262 case Mips::BI__builtin_msa_maxi_s_h: 3263 case Mips::BI__builtin_msa_maxi_s_w: 3264 case Mips::BI__builtin_msa_maxi_s_d: 3265 case Mips::BI__builtin_msa_mini_s_b: 3266 case Mips::BI__builtin_msa_mini_s_h: 3267 case Mips::BI__builtin_msa_mini_s_w: 3268 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3269 // These intrinsics take an unsigned 8 bit immediate. 3270 case Mips::BI__builtin_msa_andi_b: 3271 case Mips::BI__builtin_msa_nori_b: 3272 case Mips::BI__builtin_msa_ori_b: 3273 case Mips::BI__builtin_msa_shf_b: 3274 case Mips::BI__builtin_msa_shf_h: 3275 case Mips::BI__builtin_msa_shf_w: 3276 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3277 case Mips::BI__builtin_msa_bseli_b: 3278 case Mips::BI__builtin_msa_bmnzi_b: 3279 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3280 // df/n format 3281 // These intrinsics take an unsigned 4 bit immediate. 3282 case Mips::BI__builtin_msa_copy_s_b: 3283 case Mips::BI__builtin_msa_copy_u_b: 3284 case Mips::BI__builtin_msa_insve_b: 3285 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3286 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3287 // These intrinsics take an unsigned 3 bit immediate. 3288 case Mips::BI__builtin_msa_copy_s_h: 3289 case Mips::BI__builtin_msa_copy_u_h: 3290 case Mips::BI__builtin_msa_insve_h: 3291 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3292 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3293 // These intrinsics take an unsigned 2 bit immediate. 3294 case Mips::BI__builtin_msa_copy_s_w: 3295 case Mips::BI__builtin_msa_copy_u_w: 3296 case Mips::BI__builtin_msa_insve_w: 3297 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3298 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3299 // These intrinsics take an unsigned 1 bit immediate. 3300 case Mips::BI__builtin_msa_copy_s_d: 3301 case Mips::BI__builtin_msa_copy_u_d: 3302 case Mips::BI__builtin_msa_insve_d: 3303 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3304 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3305 // Memory offsets and immediate loads. 3306 // These intrinsics take a signed 10 bit immediate. 3307 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3308 case Mips::BI__builtin_msa_ldi_h: 3309 case Mips::BI__builtin_msa_ldi_w: 3310 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3311 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3312 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3313 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3314 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3315 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3316 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3317 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3318 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3319 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3320 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3321 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3322 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3323 } 3324 3325 if (!m) 3326 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3327 3328 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3329 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3330 } 3331 3332 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3333 /// advancing the pointer over the consumed characters. The decoded type is 3334 /// returned. If the decoded type represents a constant integer with a 3335 /// constraint on its value then Mask is set to that value. The type descriptors 3336 /// used in Str are specific to PPC MMA builtins and are documented in the file 3337 /// defining the PPC builtins. 3338 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3339 unsigned &Mask) { 3340 bool RequireICE = false; 3341 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3342 switch (*Str++) { 3343 case 'V': 3344 return Context.getVectorType(Context.UnsignedCharTy, 16, 3345 VectorType::VectorKind::AltiVecVector); 3346 case 'i': { 3347 char *End; 3348 unsigned size = strtoul(Str, &End, 10); 3349 assert(End != Str && "Missing constant parameter constraint"); 3350 Str = End; 3351 Mask = size; 3352 return Context.IntTy; 3353 } 3354 case 'W': { 3355 char *End; 3356 unsigned size = strtoul(Str, &End, 10); 3357 assert(End != Str && "Missing PowerPC MMA type size"); 3358 Str = End; 3359 QualType Type; 3360 switch (size) { 3361 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3362 case size: Type = Context.Id##Ty; break; 3363 #include "clang/Basic/PPCTypes.def" 3364 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3365 } 3366 bool CheckVectorArgs = false; 3367 while (!CheckVectorArgs) { 3368 switch (*Str++) { 3369 case '*': 3370 Type = Context.getPointerType(Type); 3371 break; 3372 case 'C': 3373 Type = Type.withConst(); 3374 break; 3375 default: 3376 CheckVectorArgs = true; 3377 --Str; 3378 break; 3379 } 3380 } 3381 return Type; 3382 } 3383 default: 3384 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3385 } 3386 } 3387 3388 static bool isPPC_64Builtin(unsigned BuiltinID) { 3389 // These builtins only work on PPC 64bit targets. 3390 switch (BuiltinID) { 3391 case PPC::BI__builtin_divde: 3392 case PPC::BI__builtin_divdeu: 3393 case PPC::BI__builtin_bpermd: 3394 case PPC::BI__builtin_ppc_ldarx: 3395 case PPC::BI__builtin_ppc_stdcx: 3396 case PPC::BI__builtin_ppc_tdw: 3397 case PPC::BI__builtin_ppc_trapd: 3398 case PPC::BI__builtin_ppc_cmpeqb: 3399 case PPC::BI__builtin_ppc_setb: 3400 case PPC::BI__builtin_ppc_mulhd: 3401 case PPC::BI__builtin_ppc_mulhdu: 3402 case PPC::BI__builtin_ppc_maddhd: 3403 case PPC::BI__builtin_ppc_maddhdu: 3404 case PPC::BI__builtin_ppc_maddld: 3405 case PPC::BI__builtin_ppc_load8r: 3406 case PPC::BI__builtin_ppc_store8r: 3407 case PPC::BI__builtin_ppc_insert_exp: 3408 case PPC::BI__builtin_ppc_extract_sig: 3409 case PPC::BI__builtin_ppc_addex: 3410 case PPC::BI__builtin_darn: 3411 case PPC::BI__builtin_darn_raw: 3412 case PPC::BI__builtin_ppc_compare_and_swaplp: 3413 case PPC::BI__builtin_ppc_fetch_and_addlp: 3414 case PPC::BI__builtin_ppc_fetch_and_andlp: 3415 case PPC::BI__builtin_ppc_fetch_and_orlp: 3416 case PPC::BI__builtin_ppc_fetch_and_swaplp: 3417 return true; 3418 } 3419 return false; 3420 } 3421 3422 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3423 StringRef FeatureToCheck, unsigned DiagID, 3424 StringRef DiagArg = "") { 3425 if (S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3426 return false; 3427 3428 if (DiagArg.empty()) 3429 S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3430 else 3431 S.Diag(TheCall->getBeginLoc(), DiagID) 3432 << DiagArg << TheCall->getSourceRange(); 3433 3434 return true; 3435 } 3436 3437 /// Returns true if the argument consists of one contiguous run of 1s with any 3438 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so 3439 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, 3440 /// since all 1s are not contiguous. 3441 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { 3442 llvm::APSInt Result; 3443 // We can't check the value of a dependent argument. 3444 Expr *Arg = TheCall->getArg(ArgNum); 3445 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3446 return false; 3447 3448 // Check constant-ness first. 3449 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3450 return true; 3451 3452 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. 3453 if (Result.isShiftedMask() || (~Result).isShiftedMask()) 3454 return false; 3455 3456 return Diag(TheCall->getBeginLoc(), 3457 diag::err_argument_not_contiguous_bit_field) 3458 << ArgNum << Arg->getSourceRange(); 3459 } 3460 3461 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3462 CallExpr *TheCall) { 3463 unsigned i = 0, l = 0, u = 0; 3464 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3465 llvm::APSInt Result; 3466 3467 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3468 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3469 << TheCall->getSourceRange(); 3470 3471 switch (BuiltinID) { 3472 default: return false; 3473 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3474 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3475 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3476 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3477 case PPC::BI__builtin_altivec_dss: 3478 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3479 case PPC::BI__builtin_tbegin: 3480 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3481 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3482 case PPC::BI__builtin_tabortwc: 3483 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3484 case PPC::BI__builtin_tabortwci: 3485 case PPC::BI__builtin_tabortdci: 3486 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3487 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3488 case PPC::BI__builtin_altivec_dst: 3489 case PPC::BI__builtin_altivec_dstt: 3490 case PPC::BI__builtin_altivec_dstst: 3491 case PPC::BI__builtin_altivec_dststt: 3492 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3493 case PPC::BI__builtin_vsx_xxpermdi: 3494 case PPC::BI__builtin_vsx_xxsldwi: 3495 return SemaBuiltinVSX(TheCall); 3496 case PPC::BI__builtin_divwe: 3497 case PPC::BI__builtin_divweu: 3498 case PPC::BI__builtin_divde: 3499 case PPC::BI__builtin_divdeu: 3500 return SemaFeatureCheck(*this, TheCall, "extdiv", 3501 diag::err_ppc_builtin_only_on_arch, "7"); 3502 case PPC::BI__builtin_bpermd: 3503 return SemaFeatureCheck(*this, TheCall, "bpermd", 3504 diag::err_ppc_builtin_only_on_arch, "7"); 3505 case PPC::BI__builtin_unpack_vector_int128: 3506 return SemaFeatureCheck(*this, TheCall, "vsx", 3507 diag::err_ppc_builtin_only_on_arch, "7") || 3508 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3509 case PPC::BI__builtin_pack_vector_int128: 3510 return SemaFeatureCheck(*this, TheCall, "vsx", 3511 diag::err_ppc_builtin_only_on_arch, "7"); 3512 case PPC::BI__builtin_altivec_vgnb: 3513 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3514 case PPC::BI__builtin_altivec_vec_replace_elt: 3515 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3516 QualType VecTy = TheCall->getArg(0)->getType(); 3517 QualType EltTy = TheCall->getArg(1)->getType(); 3518 unsigned Width = Context.getIntWidth(EltTy); 3519 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3520 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3521 } 3522 case PPC::BI__builtin_vsx_xxeval: 3523 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3524 case PPC::BI__builtin_altivec_vsldbi: 3525 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3526 case PPC::BI__builtin_altivec_vsrdbi: 3527 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3528 case PPC::BI__builtin_vsx_xxpermx: 3529 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3530 case PPC::BI__builtin_ppc_tw: 3531 case PPC::BI__builtin_ppc_tdw: 3532 return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31); 3533 case PPC::BI__builtin_ppc_cmpeqb: 3534 case PPC::BI__builtin_ppc_setb: 3535 case PPC::BI__builtin_ppc_maddhd: 3536 case PPC::BI__builtin_ppc_maddhdu: 3537 case PPC::BI__builtin_ppc_maddld: 3538 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3539 diag::err_ppc_builtin_only_on_arch, "9"); 3540 case PPC::BI__builtin_ppc_cmprb: 3541 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3542 diag::err_ppc_builtin_only_on_arch, "9") || 3543 SemaBuiltinConstantArgRange(TheCall, 0, 0, 1); 3544 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must 3545 // be a constant that represents a contiguous bit field. 3546 case PPC::BI__builtin_ppc_rlwnm: 3547 return SemaValueIsRunOfOnes(TheCall, 2); 3548 case PPC::BI__builtin_ppc_rlwimi: 3549 case PPC::BI__builtin_ppc_rldimi: 3550 return SemaBuiltinConstantArg(TheCall, 2, Result) || 3551 SemaValueIsRunOfOnes(TheCall, 3); 3552 case PPC::BI__builtin_ppc_extract_exp: 3553 case PPC::BI__builtin_ppc_extract_sig: 3554 case PPC::BI__builtin_ppc_insert_exp: 3555 return SemaFeatureCheck(*this, TheCall, "power9-vector", 3556 diag::err_ppc_builtin_only_on_arch, "9"); 3557 case PPC::BI__builtin_ppc_addex: { 3558 if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3559 diag::err_ppc_builtin_only_on_arch, "9") || 3560 SemaBuiltinConstantArgRange(TheCall, 2, 0, 3)) 3561 return true; 3562 // Output warning for reserved values 1 to 3. 3563 int ArgValue = 3564 TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue(); 3565 if (ArgValue != 0) 3566 Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour) 3567 << ArgValue; 3568 return false; 3569 } 3570 case PPC::BI__builtin_ppc_mtfsb0: 3571 case PPC::BI__builtin_ppc_mtfsb1: 3572 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 3573 case PPC::BI__builtin_ppc_mtfsf: 3574 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255); 3575 case PPC::BI__builtin_ppc_mtfsfi: 3576 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3577 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3578 case PPC::BI__builtin_ppc_alignx: 3579 return SemaBuiltinConstantArgPower2(TheCall, 0); 3580 case PPC::BI__builtin_ppc_rdlam: 3581 return SemaValueIsRunOfOnes(TheCall, 2); 3582 case PPC::BI__builtin_ppc_icbt: 3583 case PPC::BI__builtin_ppc_sthcx: 3584 case PPC::BI__builtin_ppc_stbcx: 3585 case PPC::BI__builtin_ppc_lharx: 3586 case PPC::BI__builtin_ppc_lbarx: 3587 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3588 diag::err_ppc_builtin_only_on_arch, "8"); 3589 case PPC::BI__builtin_vsx_ldrmb: 3590 case PPC::BI__builtin_vsx_strmb: 3591 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3592 diag::err_ppc_builtin_only_on_arch, "8") || 3593 SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 3594 case PPC::BI__builtin_altivec_vcntmbb: 3595 case PPC::BI__builtin_altivec_vcntmbh: 3596 case PPC::BI__builtin_altivec_vcntmbw: 3597 case PPC::BI__builtin_altivec_vcntmbd: 3598 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3599 case PPC::BI__builtin_darn: 3600 case PPC::BI__builtin_darn_raw: 3601 case PPC::BI__builtin_darn_32: 3602 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3603 diag::err_ppc_builtin_only_on_arch, "9"); 3604 case PPC::BI__builtin_vsx_xxgenpcvbm: 3605 case PPC::BI__builtin_vsx_xxgenpcvhm: 3606 case PPC::BI__builtin_vsx_xxgenpcvwm: 3607 case PPC::BI__builtin_vsx_xxgenpcvdm: 3608 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3609 case PPC::BI__builtin_ppc_compare_exp_uo: 3610 case PPC::BI__builtin_ppc_compare_exp_lt: 3611 case PPC::BI__builtin_ppc_compare_exp_gt: 3612 case PPC::BI__builtin_ppc_compare_exp_eq: 3613 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3614 diag::err_ppc_builtin_only_on_arch, "9") || 3615 SemaFeatureCheck(*this, TheCall, "vsx", 3616 diag::err_ppc_builtin_requires_vsx); 3617 case PPC::BI__builtin_ppc_test_data_class: { 3618 // Check if the first argument of the __builtin_ppc_test_data_class call is 3619 // valid. The argument must be either a 'float' or a 'double'. 3620 QualType ArgType = TheCall->getArg(0)->getType(); 3621 if (ArgType != QualType(Context.FloatTy) && 3622 ArgType != QualType(Context.DoubleTy)) 3623 return Diag(TheCall->getBeginLoc(), 3624 diag::err_ppc_invalid_test_data_class_type); 3625 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3626 diag::err_ppc_builtin_only_on_arch, "9") || 3627 SemaFeatureCheck(*this, TheCall, "vsx", 3628 diag::err_ppc_builtin_requires_vsx) || 3629 SemaBuiltinConstantArgRange(TheCall, 1, 0, 127); 3630 } 3631 case PPC::BI__builtin_ppc_load8r: 3632 case PPC::BI__builtin_ppc_store8r: 3633 return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions", 3634 diag::err_ppc_builtin_only_on_arch, "7"); 3635 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3636 case PPC::BI__builtin_##Name: \ 3637 return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types); 3638 #include "clang/Basic/BuiltinsPPC.def" 3639 } 3640 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3641 } 3642 3643 // Check if the given type is a non-pointer PPC MMA type. This function is used 3644 // in Sema to prevent invalid uses of restricted PPC MMA types. 3645 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3646 if (Type->isPointerType() || Type->isArrayType()) 3647 return false; 3648 3649 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3650 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3651 if (false 3652 #include "clang/Basic/PPCTypes.def" 3653 ) { 3654 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3655 return true; 3656 } 3657 return false; 3658 } 3659 3660 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3661 CallExpr *TheCall) { 3662 // position of memory order and scope arguments in the builtin 3663 unsigned OrderIndex, ScopeIndex; 3664 switch (BuiltinID) { 3665 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3666 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3667 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3668 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3669 OrderIndex = 2; 3670 ScopeIndex = 3; 3671 break; 3672 case AMDGPU::BI__builtin_amdgcn_fence: 3673 OrderIndex = 0; 3674 ScopeIndex = 1; 3675 break; 3676 default: 3677 return false; 3678 } 3679 3680 ExprResult Arg = TheCall->getArg(OrderIndex); 3681 auto ArgExpr = Arg.get(); 3682 Expr::EvalResult ArgResult; 3683 3684 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3685 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3686 << ArgExpr->getType(); 3687 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3688 3689 // Check validity of memory ordering as per C11 / C++11's memody model. 3690 // Only fence needs check. Atomic dec/inc allow all memory orders. 3691 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3692 return Diag(ArgExpr->getBeginLoc(), 3693 diag::warn_atomic_op_has_invalid_memory_order) 3694 << ArgExpr->getSourceRange(); 3695 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3696 case llvm::AtomicOrderingCABI::relaxed: 3697 case llvm::AtomicOrderingCABI::consume: 3698 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3699 return Diag(ArgExpr->getBeginLoc(), 3700 diag::warn_atomic_op_has_invalid_memory_order) 3701 << ArgExpr->getSourceRange(); 3702 break; 3703 case llvm::AtomicOrderingCABI::acquire: 3704 case llvm::AtomicOrderingCABI::release: 3705 case llvm::AtomicOrderingCABI::acq_rel: 3706 case llvm::AtomicOrderingCABI::seq_cst: 3707 break; 3708 } 3709 3710 Arg = TheCall->getArg(ScopeIndex); 3711 ArgExpr = Arg.get(); 3712 Expr::EvalResult ArgResult1; 3713 // Check that sync scope is a constant literal 3714 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3715 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3716 << ArgExpr->getType(); 3717 3718 return false; 3719 } 3720 3721 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 3722 llvm::APSInt Result; 3723 3724 // We can't check the value of a dependent argument. 3725 Expr *Arg = TheCall->getArg(ArgNum); 3726 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3727 return false; 3728 3729 // Check constant-ness first. 3730 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3731 return true; 3732 3733 int64_t Val = Result.getSExtValue(); 3734 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 3735 return false; 3736 3737 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 3738 << Arg->getSourceRange(); 3739 } 3740 3741 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3742 unsigned BuiltinID, 3743 CallExpr *TheCall) { 3744 // CodeGenFunction can also detect this, but this gives a better error 3745 // message. 3746 bool FeatureMissing = false; 3747 SmallVector<StringRef> ReqFeatures; 3748 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3749 Features.split(ReqFeatures, ','); 3750 3751 // Check if each required feature is included 3752 for (StringRef F : ReqFeatures) { 3753 if (TI.hasFeature(F)) 3754 continue; 3755 3756 // If the feature is 64bit, alter the string so it will print better in 3757 // the diagnostic. 3758 if (F == "64bit") 3759 F = "RV64"; 3760 3761 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 3762 F.consume_front("experimental-"); 3763 std::string FeatureStr = F.str(); 3764 FeatureStr[0] = std::toupper(FeatureStr[0]); 3765 3766 // Error message 3767 FeatureMissing = true; 3768 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 3769 << TheCall->getSourceRange() << StringRef(FeatureStr); 3770 } 3771 3772 if (FeatureMissing) 3773 return true; 3774 3775 switch (BuiltinID) { 3776 case RISCVVector::BI__builtin_rvv_vsetvli: 3777 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 3778 CheckRISCVLMUL(TheCall, 2); 3779 case RISCVVector::BI__builtin_rvv_vsetvlimax: 3780 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 3781 CheckRISCVLMUL(TheCall, 1); 3782 } 3783 3784 return false; 3785 } 3786 3787 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3788 CallExpr *TheCall) { 3789 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3790 Expr *Arg = TheCall->getArg(0); 3791 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3792 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3793 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3794 << Arg->getSourceRange(); 3795 } 3796 3797 // For intrinsics which take an immediate value as part of the instruction, 3798 // range check them here. 3799 unsigned i = 0, l = 0, u = 0; 3800 switch (BuiltinID) { 3801 default: return false; 3802 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3803 case SystemZ::BI__builtin_s390_verimb: 3804 case SystemZ::BI__builtin_s390_verimh: 3805 case SystemZ::BI__builtin_s390_verimf: 3806 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3807 case SystemZ::BI__builtin_s390_vfaeb: 3808 case SystemZ::BI__builtin_s390_vfaeh: 3809 case SystemZ::BI__builtin_s390_vfaef: 3810 case SystemZ::BI__builtin_s390_vfaebs: 3811 case SystemZ::BI__builtin_s390_vfaehs: 3812 case SystemZ::BI__builtin_s390_vfaefs: 3813 case SystemZ::BI__builtin_s390_vfaezb: 3814 case SystemZ::BI__builtin_s390_vfaezh: 3815 case SystemZ::BI__builtin_s390_vfaezf: 3816 case SystemZ::BI__builtin_s390_vfaezbs: 3817 case SystemZ::BI__builtin_s390_vfaezhs: 3818 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3819 case SystemZ::BI__builtin_s390_vfisb: 3820 case SystemZ::BI__builtin_s390_vfidb: 3821 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3822 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3823 case SystemZ::BI__builtin_s390_vftcisb: 3824 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3825 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3826 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3827 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3828 case SystemZ::BI__builtin_s390_vstrcb: 3829 case SystemZ::BI__builtin_s390_vstrch: 3830 case SystemZ::BI__builtin_s390_vstrcf: 3831 case SystemZ::BI__builtin_s390_vstrczb: 3832 case SystemZ::BI__builtin_s390_vstrczh: 3833 case SystemZ::BI__builtin_s390_vstrczf: 3834 case SystemZ::BI__builtin_s390_vstrcbs: 3835 case SystemZ::BI__builtin_s390_vstrchs: 3836 case SystemZ::BI__builtin_s390_vstrcfs: 3837 case SystemZ::BI__builtin_s390_vstrczbs: 3838 case SystemZ::BI__builtin_s390_vstrczhs: 3839 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3840 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3841 case SystemZ::BI__builtin_s390_vfminsb: 3842 case SystemZ::BI__builtin_s390_vfmaxsb: 3843 case SystemZ::BI__builtin_s390_vfmindb: 3844 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3845 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3846 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3847 case SystemZ::BI__builtin_s390_vclfnhs: 3848 case SystemZ::BI__builtin_s390_vclfnls: 3849 case SystemZ::BI__builtin_s390_vcfn: 3850 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break; 3851 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break; 3852 } 3853 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3854 } 3855 3856 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3857 /// This checks that the target supports __builtin_cpu_supports and 3858 /// that the string argument is constant and valid. 3859 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3860 CallExpr *TheCall) { 3861 Expr *Arg = TheCall->getArg(0); 3862 3863 // Check if the argument is a string literal. 3864 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3865 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3866 << Arg->getSourceRange(); 3867 3868 // Check the contents of the string. 3869 StringRef Feature = 3870 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3871 if (!TI.validateCpuSupports(Feature)) 3872 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3873 << Arg->getSourceRange(); 3874 return false; 3875 } 3876 3877 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3878 /// This checks that the target supports __builtin_cpu_is and 3879 /// that the string argument is constant and valid. 3880 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3881 Expr *Arg = TheCall->getArg(0); 3882 3883 // Check if the argument is a string literal. 3884 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3885 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3886 << Arg->getSourceRange(); 3887 3888 // Check the contents of the string. 3889 StringRef Feature = 3890 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3891 if (!TI.validateCpuIs(Feature)) 3892 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3893 << Arg->getSourceRange(); 3894 return false; 3895 } 3896 3897 // Check if the rounding mode is legal. 3898 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3899 // Indicates if this instruction has rounding control or just SAE. 3900 bool HasRC = false; 3901 3902 unsigned ArgNum = 0; 3903 switch (BuiltinID) { 3904 default: 3905 return false; 3906 case X86::BI__builtin_ia32_vcvttsd2si32: 3907 case X86::BI__builtin_ia32_vcvttsd2si64: 3908 case X86::BI__builtin_ia32_vcvttsd2usi32: 3909 case X86::BI__builtin_ia32_vcvttsd2usi64: 3910 case X86::BI__builtin_ia32_vcvttss2si32: 3911 case X86::BI__builtin_ia32_vcvttss2si64: 3912 case X86::BI__builtin_ia32_vcvttss2usi32: 3913 case X86::BI__builtin_ia32_vcvttss2usi64: 3914 case X86::BI__builtin_ia32_vcvttsh2si32: 3915 case X86::BI__builtin_ia32_vcvttsh2si64: 3916 case X86::BI__builtin_ia32_vcvttsh2usi32: 3917 case X86::BI__builtin_ia32_vcvttsh2usi64: 3918 ArgNum = 1; 3919 break; 3920 case X86::BI__builtin_ia32_maxpd512: 3921 case X86::BI__builtin_ia32_maxps512: 3922 case X86::BI__builtin_ia32_minpd512: 3923 case X86::BI__builtin_ia32_minps512: 3924 case X86::BI__builtin_ia32_maxph512: 3925 case X86::BI__builtin_ia32_minph512: 3926 ArgNum = 2; 3927 break; 3928 case X86::BI__builtin_ia32_vcvtph2pd512_mask: 3929 case X86::BI__builtin_ia32_vcvtph2psx512_mask: 3930 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3931 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3932 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3933 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3934 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3935 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3936 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3937 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3938 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3939 case X86::BI__builtin_ia32_vcvttph2w512_mask: 3940 case X86::BI__builtin_ia32_vcvttph2uw512_mask: 3941 case X86::BI__builtin_ia32_vcvttph2dq512_mask: 3942 case X86::BI__builtin_ia32_vcvttph2udq512_mask: 3943 case X86::BI__builtin_ia32_vcvttph2qq512_mask: 3944 case X86::BI__builtin_ia32_vcvttph2uqq512_mask: 3945 case X86::BI__builtin_ia32_exp2pd_mask: 3946 case X86::BI__builtin_ia32_exp2ps_mask: 3947 case X86::BI__builtin_ia32_getexppd512_mask: 3948 case X86::BI__builtin_ia32_getexpps512_mask: 3949 case X86::BI__builtin_ia32_getexpph512_mask: 3950 case X86::BI__builtin_ia32_rcp28pd_mask: 3951 case X86::BI__builtin_ia32_rcp28ps_mask: 3952 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3953 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3954 case X86::BI__builtin_ia32_vcomisd: 3955 case X86::BI__builtin_ia32_vcomiss: 3956 case X86::BI__builtin_ia32_vcomish: 3957 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3958 ArgNum = 3; 3959 break; 3960 case X86::BI__builtin_ia32_cmppd512_mask: 3961 case X86::BI__builtin_ia32_cmpps512_mask: 3962 case X86::BI__builtin_ia32_cmpsd_mask: 3963 case X86::BI__builtin_ia32_cmpss_mask: 3964 case X86::BI__builtin_ia32_cmpsh_mask: 3965 case X86::BI__builtin_ia32_vcvtsh2sd_round_mask: 3966 case X86::BI__builtin_ia32_vcvtsh2ss_round_mask: 3967 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3968 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3969 case X86::BI__builtin_ia32_getexpss128_round_mask: 3970 case X86::BI__builtin_ia32_getexpsh128_round_mask: 3971 case X86::BI__builtin_ia32_getmantpd512_mask: 3972 case X86::BI__builtin_ia32_getmantps512_mask: 3973 case X86::BI__builtin_ia32_getmantph512_mask: 3974 case X86::BI__builtin_ia32_maxsd_round_mask: 3975 case X86::BI__builtin_ia32_maxss_round_mask: 3976 case X86::BI__builtin_ia32_maxsh_round_mask: 3977 case X86::BI__builtin_ia32_minsd_round_mask: 3978 case X86::BI__builtin_ia32_minss_round_mask: 3979 case X86::BI__builtin_ia32_minsh_round_mask: 3980 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3981 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3982 case X86::BI__builtin_ia32_reducepd512_mask: 3983 case X86::BI__builtin_ia32_reduceps512_mask: 3984 case X86::BI__builtin_ia32_reduceph512_mask: 3985 case X86::BI__builtin_ia32_rndscalepd_mask: 3986 case X86::BI__builtin_ia32_rndscaleps_mask: 3987 case X86::BI__builtin_ia32_rndscaleph_mask: 3988 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3989 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3990 ArgNum = 4; 3991 break; 3992 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3993 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3994 case X86::BI__builtin_ia32_fixupimmps512_mask: 3995 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3996 case X86::BI__builtin_ia32_fixupimmsd_mask: 3997 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3998 case X86::BI__builtin_ia32_fixupimmss_mask: 3999 case X86::BI__builtin_ia32_fixupimmss_maskz: 4000 case X86::BI__builtin_ia32_getmantsd_round_mask: 4001 case X86::BI__builtin_ia32_getmantss_round_mask: 4002 case X86::BI__builtin_ia32_getmantsh_round_mask: 4003 case X86::BI__builtin_ia32_rangepd512_mask: 4004 case X86::BI__builtin_ia32_rangeps512_mask: 4005 case X86::BI__builtin_ia32_rangesd128_round_mask: 4006 case X86::BI__builtin_ia32_rangess128_round_mask: 4007 case X86::BI__builtin_ia32_reducesd_mask: 4008 case X86::BI__builtin_ia32_reducess_mask: 4009 case X86::BI__builtin_ia32_reducesh_mask: 4010 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4011 case X86::BI__builtin_ia32_rndscaless_round_mask: 4012 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4013 ArgNum = 5; 4014 break; 4015 case X86::BI__builtin_ia32_vcvtsd2si64: 4016 case X86::BI__builtin_ia32_vcvtsd2si32: 4017 case X86::BI__builtin_ia32_vcvtsd2usi32: 4018 case X86::BI__builtin_ia32_vcvtsd2usi64: 4019 case X86::BI__builtin_ia32_vcvtss2si32: 4020 case X86::BI__builtin_ia32_vcvtss2si64: 4021 case X86::BI__builtin_ia32_vcvtss2usi32: 4022 case X86::BI__builtin_ia32_vcvtss2usi64: 4023 case X86::BI__builtin_ia32_vcvtsh2si32: 4024 case X86::BI__builtin_ia32_vcvtsh2si64: 4025 case X86::BI__builtin_ia32_vcvtsh2usi32: 4026 case X86::BI__builtin_ia32_vcvtsh2usi64: 4027 case X86::BI__builtin_ia32_sqrtpd512: 4028 case X86::BI__builtin_ia32_sqrtps512: 4029 case X86::BI__builtin_ia32_sqrtph512: 4030 ArgNum = 1; 4031 HasRC = true; 4032 break; 4033 case X86::BI__builtin_ia32_addph512: 4034 case X86::BI__builtin_ia32_divph512: 4035 case X86::BI__builtin_ia32_mulph512: 4036 case X86::BI__builtin_ia32_subph512: 4037 case X86::BI__builtin_ia32_addpd512: 4038 case X86::BI__builtin_ia32_addps512: 4039 case X86::BI__builtin_ia32_divpd512: 4040 case X86::BI__builtin_ia32_divps512: 4041 case X86::BI__builtin_ia32_mulpd512: 4042 case X86::BI__builtin_ia32_mulps512: 4043 case X86::BI__builtin_ia32_subpd512: 4044 case X86::BI__builtin_ia32_subps512: 4045 case X86::BI__builtin_ia32_cvtsi2sd64: 4046 case X86::BI__builtin_ia32_cvtsi2ss32: 4047 case X86::BI__builtin_ia32_cvtsi2ss64: 4048 case X86::BI__builtin_ia32_cvtusi2sd64: 4049 case X86::BI__builtin_ia32_cvtusi2ss32: 4050 case X86::BI__builtin_ia32_cvtusi2ss64: 4051 case X86::BI__builtin_ia32_vcvtusi2sh: 4052 case X86::BI__builtin_ia32_vcvtusi642sh: 4053 case X86::BI__builtin_ia32_vcvtsi2sh: 4054 case X86::BI__builtin_ia32_vcvtsi642sh: 4055 ArgNum = 2; 4056 HasRC = true; 4057 break; 4058 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 4059 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 4060 case X86::BI__builtin_ia32_vcvtpd2ph512_mask: 4061 case X86::BI__builtin_ia32_vcvtps2phx512_mask: 4062 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 4063 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 4064 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 4065 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 4066 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 4067 case X86::BI__builtin_ia32_cvtps2dq512_mask: 4068 case X86::BI__builtin_ia32_cvtps2qq512_mask: 4069 case X86::BI__builtin_ia32_cvtps2udq512_mask: 4070 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 4071 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 4072 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 4073 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 4074 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 4075 case X86::BI__builtin_ia32_vcvtdq2ph512_mask: 4076 case X86::BI__builtin_ia32_vcvtudq2ph512_mask: 4077 case X86::BI__builtin_ia32_vcvtw2ph512_mask: 4078 case X86::BI__builtin_ia32_vcvtuw2ph512_mask: 4079 case X86::BI__builtin_ia32_vcvtph2w512_mask: 4080 case X86::BI__builtin_ia32_vcvtph2uw512_mask: 4081 case X86::BI__builtin_ia32_vcvtph2dq512_mask: 4082 case X86::BI__builtin_ia32_vcvtph2udq512_mask: 4083 case X86::BI__builtin_ia32_vcvtph2qq512_mask: 4084 case X86::BI__builtin_ia32_vcvtph2uqq512_mask: 4085 case X86::BI__builtin_ia32_vcvtqq2ph512_mask: 4086 case X86::BI__builtin_ia32_vcvtuqq2ph512_mask: 4087 ArgNum = 3; 4088 HasRC = true; 4089 break; 4090 case X86::BI__builtin_ia32_addsh_round_mask: 4091 case X86::BI__builtin_ia32_addss_round_mask: 4092 case X86::BI__builtin_ia32_addsd_round_mask: 4093 case X86::BI__builtin_ia32_divsh_round_mask: 4094 case X86::BI__builtin_ia32_divss_round_mask: 4095 case X86::BI__builtin_ia32_divsd_round_mask: 4096 case X86::BI__builtin_ia32_mulsh_round_mask: 4097 case X86::BI__builtin_ia32_mulss_round_mask: 4098 case X86::BI__builtin_ia32_mulsd_round_mask: 4099 case X86::BI__builtin_ia32_subsh_round_mask: 4100 case X86::BI__builtin_ia32_subss_round_mask: 4101 case X86::BI__builtin_ia32_subsd_round_mask: 4102 case X86::BI__builtin_ia32_scalefph512_mask: 4103 case X86::BI__builtin_ia32_scalefpd512_mask: 4104 case X86::BI__builtin_ia32_scalefps512_mask: 4105 case X86::BI__builtin_ia32_scalefsd_round_mask: 4106 case X86::BI__builtin_ia32_scalefss_round_mask: 4107 case X86::BI__builtin_ia32_scalefsh_round_mask: 4108 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 4109 case X86::BI__builtin_ia32_vcvtss2sh_round_mask: 4110 case X86::BI__builtin_ia32_vcvtsd2sh_round_mask: 4111 case X86::BI__builtin_ia32_sqrtsd_round_mask: 4112 case X86::BI__builtin_ia32_sqrtss_round_mask: 4113 case X86::BI__builtin_ia32_sqrtsh_round_mask: 4114 case X86::BI__builtin_ia32_vfmaddsd3_mask: 4115 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 4116 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 4117 case X86::BI__builtin_ia32_vfmaddss3_mask: 4118 case X86::BI__builtin_ia32_vfmaddss3_maskz: 4119 case X86::BI__builtin_ia32_vfmaddss3_mask3: 4120 case X86::BI__builtin_ia32_vfmaddsh3_mask: 4121 case X86::BI__builtin_ia32_vfmaddsh3_maskz: 4122 case X86::BI__builtin_ia32_vfmaddsh3_mask3: 4123 case X86::BI__builtin_ia32_vfmaddpd512_mask: 4124 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 4125 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 4126 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 4127 case X86::BI__builtin_ia32_vfmaddps512_mask: 4128 case X86::BI__builtin_ia32_vfmaddps512_maskz: 4129 case X86::BI__builtin_ia32_vfmaddps512_mask3: 4130 case X86::BI__builtin_ia32_vfmsubps512_mask3: 4131 case X86::BI__builtin_ia32_vfmaddph512_mask: 4132 case X86::BI__builtin_ia32_vfmaddph512_maskz: 4133 case X86::BI__builtin_ia32_vfmaddph512_mask3: 4134 case X86::BI__builtin_ia32_vfmsubph512_mask3: 4135 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 4136 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 4137 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 4138 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 4139 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 4140 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 4141 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 4142 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 4143 case X86::BI__builtin_ia32_vfmaddsubph512_mask: 4144 case X86::BI__builtin_ia32_vfmaddsubph512_maskz: 4145 case X86::BI__builtin_ia32_vfmaddsubph512_mask3: 4146 case X86::BI__builtin_ia32_vfmsubaddph512_mask3: 4147 case X86::BI__builtin_ia32_vfmaddcsh_mask: 4148 case X86::BI__builtin_ia32_vfmaddcsh_round_mask: 4149 case X86::BI__builtin_ia32_vfmaddcsh_round_mask3: 4150 case X86::BI__builtin_ia32_vfmaddcph512_mask: 4151 case X86::BI__builtin_ia32_vfmaddcph512_maskz: 4152 case X86::BI__builtin_ia32_vfmaddcph512_mask3: 4153 case X86::BI__builtin_ia32_vfcmaddcsh_mask: 4154 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask: 4155 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3: 4156 case X86::BI__builtin_ia32_vfcmaddcph512_mask: 4157 case X86::BI__builtin_ia32_vfcmaddcph512_maskz: 4158 case X86::BI__builtin_ia32_vfcmaddcph512_mask3: 4159 case X86::BI__builtin_ia32_vfmulcsh_mask: 4160 case X86::BI__builtin_ia32_vfmulcph512_mask: 4161 case X86::BI__builtin_ia32_vfcmulcsh_mask: 4162 case X86::BI__builtin_ia32_vfcmulcph512_mask: 4163 ArgNum = 4; 4164 HasRC = true; 4165 break; 4166 } 4167 4168 llvm::APSInt Result; 4169 4170 // We can't check the value of a dependent argument. 4171 Expr *Arg = TheCall->getArg(ArgNum); 4172 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4173 return false; 4174 4175 // Check constant-ness first. 4176 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4177 return true; 4178 4179 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 4180 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 4181 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 4182 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 4183 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 4184 Result == 8/*ROUND_NO_EXC*/ || 4185 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 4186 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 4187 return false; 4188 4189 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 4190 << Arg->getSourceRange(); 4191 } 4192 4193 // Check if the gather/scatter scale is legal. 4194 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 4195 CallExpr *TheCall) { 4196 unsigned ArgNum = 0; 4197 switch (BuiltinID) { 4198 default: 4199 return false; 4200 case X86::BI__builtin_ia32_gatherpfdpd: 4201 case X86::BI__builtin_ia32_gatherpfdps: 4202 case X86::BI__builtin_ia32_gatherpfqpd: 4203 case X86::BI__builtin_ia32_gatherpfqps: 4204 case X86::BI__builtin_ia32_scatterpfdpd: 4205 case X86::BI__builtin_ia32_scatterpfdps: 4206 case X86::BI__builtin_ia32_scatterpfqpd: 4207 case X86::BI__builtin_ia32_scatterpfqps: 4208 ArgNum = 3; 4209 break; 4210 case X86::BI__builtin_ia32_gatherd_pd: 4211 case X86::BI__builtin_ia32_gatherd_pd256: 4212 case X86::BI__builtin_ia32_gatherq_pd: 4213 case X86::BI__builtin_ia32_gatherq_pd256: 4214 case X86::BI__builtin_ia32_gatherd_ps: 4215 case X86::BI__builtin_ia32_gatherd_ps256: 4216 case X86::BI__builtin_ia32_gatherq_ps: 4217 case X86::BI__builtin_ia32_gatherq_ps256: 4218 case X86::BI__builtin_ia32_gatherd_q: 4219 case X86::BI__builtin_ia32_gatherd_q256: 4220 case X86::BI__builtin_ia32_gatherq_q: 4221 case X86::BI__builtin_ia32_gatherq_q256: 4222 case X86::BI__builtin_ia32_gatherd_d: 4223 case X86::BI__builtin_ia32_gatherd_d256: 4224 case X86::BI__builtin_ia32_gatherq_d: 4225 case X86::BI__builtin_ia32_gatherq_d256: 4226 case X86::BI__builtin_ia32_gather3div2df: 4227 case X86::BI__builtin_ia32_gather3div2di: 4228 case X86::BI__builtin_ia32_gather3div4df: 4229 case X86::BI__builtin_ia32_gather3div4di: 4230 case X86::BI__builtin_ia32_gather3div4sf: 4231 case X86::BI__builtin_ia32_gather3div4si: 4232 case X86::BI__builtin_ia32_gather3div8sf: 4233 case X86::BI__builtin_ia32_gather3div8si: 4234 case X86::BI__builtin_ia32_gather3siv2df: 4235 case X86::BI__builtin_ia32_gather3siv2di: 4236 case X86::BI__builtin_ia32_gather3siv4df: 4237 case X86::BI__builtin_ia32_gather3siv4di: 4238 case X86::BI__builtin_ia32_gather3siv4sf: 4239 case X86::BI__builtin_ia32_gather3siv4si: 4240 case X86::BI__builtin_ia32_gather3siv8sf: 4241 case X86::BI__builtin_ia32_gather3siv8si: 4242 case X86::BI__builtin_ia32_gathersiv8df: 4243 case X86::BI__builtin_ia32_gathersiv16sf: 4244 case X86::BI__builtin_ia32_gatherdiv8df: 4245 case X86::BI__builtin_ia32_gatherdiv16sf: 4246 case X86::BI__builtin_ia32_gathersiv8di: 4247 case X86::BI__builtin_ia32_gathersiv16si: 4248 case X86::BI__builtin_ia32_gatherdiv8di: 4249 case X86::BI__builtin_ia32_gatherdiv16si: 4250 case X86::BI__builtin_ia32_scatterdiv2df: 4251 case X86::BI__builtin_ia32_scatterdiv2di: 4252 case X86::BI__builtin_ia32_scatterdiv4df: 4253 case X86::BI__builtin_ia32_scatterdiv4di: 4254 case X86::BI__builtin_ia32_scatterdiv4sf: 4255 case X86::BI__builtin_ia32_scatterdiv4si: 4256 case X86::BI__builtin_ia32_scatterdiv8sf: 4257 case X86::BI__builtin_ia32_scatterdiv8si: 4258 case X86::BI__builtin_ia32_scattersiv2df: 4259 case X86::BI__builtin_ia32_scattersiv2di: 4260 case X86::BI__builtin_ia32_scattersiv4df: 4261 case X86::BI__builtin_ia32_scattersiv4di: 4262 case X86::BI__builtin_ia32_scattersiv4sf: 4263 case X86::BI__builtin_ia32_scattersiv4si: 4264 case X86::BI__builtin_ia32_scattersiv8sf: 4265 case X86::BI__builtin_ia32_scattersiv8si: 4266 case X86::BI__builtin_ia32_scattersiv8df: 4267 case X86::BI__builtin_ia32_scattersiv16sf: 4268 case X86::BI__builtin_ia32_scatterdiv8df: 4269 case X86::BI__builtin_ia32_scatterdiv16sf: 4270 case X86::BI__builtin_ia32_scattersiv8di: 4271 case X86::BI__builtin_ia32_scattersiv16si: 4272 case X86::BI__builtin_ia32_scatterdiv8di: 4273 case X86::BI__builtin_ia32_scatterdiv16si: 4274 ArgNum = 4; 4275 break; 4276 } 4277 4278 llvm::APSInt Result; 4279 4280 // We can't check the value of a dependent argument. 4281 Expr *Arg = TheCall->getArg(ArgNum); 4282 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4283 return false; 4284 4285 // Check constant-ness first. 4286 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4287 return true; 4288 4289 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4290 return false; 4291 4292 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4293 << Arg->getSourceRange(); 4294 } 4295 4296 enum { TileRegLow = 0, TileRegHigh = 7 }; 4297 4298 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4299 ArrayRef<int> ArgNums) { 4300 for (int ArgNum : ArgNums) { 4301 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4302 return true; 4303 } 4304 return false; 4305 } 4306 4307 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4308 ArrayRef<int> ArgNums) { 4309 // Because the max number of tile register is TileRegHigh + 1, so here we use 4310 // each bit to represent the usage of them in bitset. 4311 std::bitset<TileRegHigh + 1> ArgValues; 4312 for (int ArgNum : ArgNums) { 4313 Expr *Arg = TheCall->getArg(ArgNum); 4314 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4315 continue; 4316 4317 llvm::APSInt Result; 4318 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4319 return true; 4320 int ArgExtValue = Result.getExtValue(); 4321 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4322 "Incorrect tile register num."); 4323 if (ArgValues.test(ArgExtValue)) 4324 return Diag(TheCall->getBeginLoc(), 4325 diag::err_x86_builtin_tile_arg_duplicate) 4326 << TheCall->getArg(ArgNum)->getSourceRange(); 4327 ArgValues.set(ArgExtValue); 4328 } 4329 return false; 4330 } 4331 4332 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 4333 ArrayRef<int> ArgNums) { 4334 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 4335 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 4336 } 4337 4338 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 4339 switch (BuiltinID) { 4340 default: 4341 return false; 4342 case X86::BI__builtin_ia32_tileloadd64: 4343 case X86::BI__builtin_ia32_tileloaddt164: 4344 case X86::BI__builtin_ia32_tilestored64: 4345 case X86::BI__builtin_ia32_tilezero: 4346 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 4347 case X86::BI__builtin_ia32_tdpbssd: 4348 case X86::BI__builtin_ia32_tdpbsud: 4349 case X86::BI__builtin_ia32_tdpbusd: 4350 case X86::BI__builtin_ia32_tdpbuud: 4351 case X86::BI__builtin_ia32_tdpbf16ps: 4352 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 4353 } 4354 } 4355 static bool isX86_32Builtin(unsigned BuiltinID) { 4356 // These builtins only work on x86-32 targets. 4357 switch (BuiltinID) { 4358 case X86::BI__builtin_ia32_readeflags_u32: 4359 case X86::BI__builtin_ia32_writeeflags_u32: 4360 return true; 4361 } 4362 4363 return false; 4364 } 4365 4366 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 4367 CallExpr *TheCall) { 4368 if (BuiltinID == X86::BI__builtin_cpu_supports) 4369 return SemaBuiltinCpuSupports(*this, TI, TheCall); 4370 4371 if (BuiltinID == X86::BI__builtin_cpu_is) 4372 return SemaBuiltinCpuIs(*this, TI, TheCall); 4373 4374 // Check for 32-bit only builtins on a 64-bit target. 4375 const llvm::Triple &TT = TI.getTriple(); 4376 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 4377 return Diag(TheCall->getCallee()->getBeginLoc(), 4378 diag::err_32_bit_builtin_64_bit_tgt); 4379 4380 // If the intrinsic has rounding or SAE make sure its valid. 4381 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 4382 return true; 4383 4384 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 4385 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 4386 return true; 4387 4388 // If the intrinsic has a tile arguments, make sure they are valid. 4389 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4390 return true; 4391 4392 // For intrinsics which take an immediate value as part of the instruction, 4393 // range check them here. 4394 int i = 0, l = 0, u = 0; 4395 switch (BuiltinID) { 4396 default: 4397 return false; 4398 case X86::BI__builtin_ia32_vec_ext_v2si: 4399 case X86::BI__builtin_ia32_vec_ext_v2di: 4400 case X86::BI__builtin_ia32_vextractf128_pd256: 4401 case X86::BI__builtin_ia32_vextractf128_ps256: 4402 case X86::BI__builtin_ia32_vextractf128_si256: 4403 case X86::BI__builtin_ia32_extract128i256: 4404 case X86::BI__builtin_ia32_extractf64x4_mask: 4405 case X86::BI__builtin_ia32_extracti64x4_mask: 4406 case X86::BI__builtin_ia32_extractf32x8_mask: 4407 case X86::BI__builtin_ia32_extracti32x8_mask: 4408 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4409 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4410 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4411 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4412 i = 1; l = 0; u = 1; 4413 break; 4414 case X86::BI__builtin_ia32_vec_set_v2di: 4415 case X86::BI__builtin_ia32_vinsertf128_pd256: 4416 case X86::BI__builtin_ia32_vinsertf128_ps256: 4417 case X86::BI__builtin_ia32_vinsertf128_si256: 4418 case X86::BI__builtin_ia32_insert128i256: 4419 case X86::BI__builtin_ia32_insertf32x8: 4420 case X86::BI__builtin_ia32_inserti32x8: 4421 case X86::BI__builtin_ia32_insertf64x4: 4422 case X86::BI__builtin_ia32_inserti64x4: 4423 case X86::BI__builtin_ia32_insertf64x2_256: 4424 case X86::BI__builtin_ia32_inserti64x2_256: 4425 case X86::BI__builtin_ia32_insertf32x4_256: 4426 case X86::BI__builtin_ia32_inserti32x4_256: 4427 i = 2; l = 0; u = 1; 4428 break; 4429 case X86::BI__builtin_ia32_vpermilpd: 4430 case X86::BI__builtin_ia32_vec_ext_v4hi: 4431 case X86::BI__builtin_ia32_vec_ext_v4si: 4432 case X86::BI__builtin_ia32_vec_ext_v4sf: 4433 case X86::BI__builtin_ia32_vec_ext_v4di: 4434 case X86::BI__builtin_ia32_extractf32x4_mask: 4435 case X86::BI__builtin_ia32_extracti32x4_mask: 4436 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4437 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4438 i = 1; l = 0; u = 3; 4439 break; 4440 case X86::BI_mm_prefetch: 4441 case X86::BI__builtin_ia32_vec_ext_v8hi: 4442 case X86::BI__builtin_ia32_vec_ext_v8si: 4443 i = 1; l = 0; u = 7; 4444 break; 4445 case X86::BI__builtin_ia32_sha1rnds4: 4446 case X86::BI__builtin_ia32_blendpd: 4447 case X86::BI__builtin_ia32_shufpd: 4448 case X86::BI__builtin_ia32_vec_set_v4hi: 4449 case X86::BI__builtin_ia32_vec_set_v4si: 4450 case X86::BI__builtin_ia32_vec_set_v4di: 4451 case X86::BI__builtin_ia32_shuf_f32x4_256: 4452 case X86::BI__builtin_ia32_shuf_f64x2_256: 4453 case X86::BI__builtin_ia32_shuf_i32x4_256: 4454 case X86::BI__builtin_ia32_shuf_i64x2_256: 4455 case X86::BI__builtin_ia32_insertf64x2_512: 4456 case X86::BI__builtin_ia32_inserti64x2_512: 4457 case X86::BI__builtin_ia32_insertf32x4: 4458 case X86::BI__builtin_ia32_inserti32x4: 4459 i = 2; l = 0; u = 3; 4460 break; 4461 case X86::BI__builtin_ia32_vpermil2pd: 4462 case X86::BI__builtin_ia32_vpermil2pd256: 4463 case X86::BI__builtin_ia32_vpermil2ps: 4464 case X86::BI__builtin_ia32_vpermil2ps256: 4465 i = 3; l = 0; u = 3; 4466 break; 4467 case X86::BI__builtin_ia32_cmpb128_mask: 4468 case X86::BI__builtin_ia32_cmpw128_mask: 4469 case X86::BI__builtin_ia32_cmpd128_mask: 4470 case X86::BI__builtin_ia32_cmpq128_mask: 4471 case X86::BI__builtin_ia32_cmpb256_mask: 4472 case X86::BI__builtin_ia32_cmpw256_mask: 4473 case X86::BI__builtin_ia32_cmpd256_mask: 4474 case X86::BI__builtin_ia32_cmpq256_mask: 4475 case X86::BI__builtin_ia32_cmpb512_mask: 4476 case X86::BI__builtin_ia32_cmpw512_mask: 4477 case X86::BI__builtin_ia32_cmpd512_mask: 4478 case X86::BI__builtin_ia32_cmpq512_mask: 4479 case X86::BI__builtin_ia32_ucmpb128_mask: 4480 case X86::BI__builtin_ia32_ucmpw128_mask: 4481 case X86::BI__builtin_ia32_ucmpd128_mask: 4482 case X86::BI__builtin_ia32_ucmpq128_mask: 4483 case X86::BI__builtin_ia32_ucmpb256_mask: 4484 case X86::BI__builtin_ia32_ucmpw256_mask: 4485 case X86::BI__builtin_ia32_ucmpd256_mask: 4486 case X86::BI__builtin_ia32_ucmpq256_mask: 4487 case X86::BI__builtin_ia32_ucmpb512_mask: 4488 case X86::BI__builtin_ia32_ucmpw512_mask: 4489 case X86::BI__builtin_ia32_ucmpd512_mask: 4490 case X86::BI__builtin_ia32_ucmpq512_mask: 4491 case X86::BI__builtin_ia32_vpcomub: 4492 case X86::BI__builtin_ia32_vpcomuw: 4493 case X86::BI__builtin_ia32_vpcomud: 4494 case X86::BI__builtin_ia32_vpcomuq: 4495 case X86::BI__builtin_ia32_vpcomb: 4496 case X86::BI__builtin_ia32_vpcomw: 4497 case X86::BI__builtin_ia32_vpcomd: 4498 case X86::BI__builtin_ia32_vpcomq: 4499 case X86::BI__builtin_ia32_vec_set_v8hi: 4500 case X86::BI__builtin_ia32_vec_set_v8si: 4501 i = 2; l = 0; u = 7; 4502 break; 4503 case X86::BI__builtin_ia32_vpermilpd256: 4504 case X86::BI__builtin_ia32_roundps: 4505 case X86::BI__builtin_ia32_roundpd: 4506 case X86::BI__builtin_ia32_roundps256: 4507 case X86::BI__builtin_ia32_roundpd256: 4508 case X86::BI__builtin_ia32_getmantpd128_mask: 4509 case X86::BI__builtin_ia32_getmantpd256_mask: 4510 case X86::BI__builtin_ia32_getmantps128_mask: 4511 case X86::BI__builtin_ia32_getmantps256_mask: 4512 case X86::BI__builtin_ia32_getmantpd512_mask: 4513 case X86::BI__builtin_ia32_getmantps512_mask: 4514 case X86::BI__builtin_ia32_getmantph128_mask: 4515 case X86::BI__builtin_ia32_getmantph256_mask: 4516 case X86::BI__builtin_ia32_getmantph512_mask: 4517 case X86::BI__builtin_ia32_vec_ext_v16qi: 4518 case X86::BI__builtin_ia32_vec_ext_v16hi: 4519 i = 1; l = 0; u = 15; 4520 break; 4521 case X86::BI__builtin_ia32_pblendd128: 4522 case X86::BI__builtin_ia32_blendps: 4523 case X86::BI__builtin_ia32_blendpd256: 4524 case X86::BI__builtin_ia32_shufpd256: 4525 case X86::BI__builtin_ia32_roundss: 4526 case X86::BI__builtin_ia32_roundsd: 4527 case X86::BI__builtin_ia32_rangepd128_mask: 4528 case X86::BI__builtin_ia32_rangepd256_mask: 4529 case X86::BI__builtin_ia32_rangepd512_mask: 4530 case X86::BI__builtin_ia32_rangeps128_mask: 4531 case X86::BI__builtin_ia32_rangeps256_mask: 4532 case X86::BI__builtin_ia32_rangeps512_mask: 4533 case X86::BI__builtin_ia32_getmantsd_round_mask: 4534 case X86::BI__builtin_ia32_getmantss_round_mask: 4535 case X86::BI__builtin_ia32_getmantsh_round_mask: 4536 case X86::BI__builtin_ia32_vec_set_v16qi: 4537 case X86::BI__builtin_ia32_vec_set_v16hi: 4538 i = 2; l = 0; u = 15; 4539 break; 4540 case X86::BI__builtin_ia32_vec_ext_v32qi: 4541 i = 1; l = 0; u = 31; 4542 break; 4543 case X86::BI__builtin_ia32_cmpps: 4544 case X86::BI__builtin_ia32_cmpss: 4545 case X86::BI__builtin_ia32_cmppd: 4546 case X86::BI__builtin_ia32_cmpsd: 4547 case X86::BI__builtin_ia32_cmpps256: 4548 case X86::BI__builtin_ia32_cmppd256: 4549 case X86::BI__builtin_ia32_cmpps128_mask: 4550 case X86::BI__builtin_ia32_cmppd128_mask: 4551 case X86::BI__builtin_ia32_cmpps256_mask: 4552 case X86::BI__builtin_ia32_cmppd256_mask: 4553 case X86::BI__builtin_ia32_cmpps512_mask: 4554 case X86::BI__builtin_ia32_cmppd512_mask: 4555 case X86::BI__builtin_ia32_cmpsd_mask: 4556 case X86::BI__builtin_ia32_cmpss_mask: 4557 case X86::BI__builtin_ia32_vec_set_v32qi: 4558 i = 2; l = 0; u = 31; 4559 break; 4560 case X86::BI__builtin_ia32_permdf256: 4561 case X86::BI__builtin_ia32_permdi256: 4562 case X86::BI__builtin_ia32_permdf512: 4563 case X86::BI__builtin_ia32_permdi512: 4564 case X86::BI__builtin_ia32_vpermilps: 4565 case X86::BI__builtin_ia32_vpermilps256: 4566 case X86::BI__builtin_ia32_vpermilpd512: 4567 case X86::BI__builtin_ia32_vpermilps512: 4568 case X86::BI__builtin_ia32_pshufd: 4569 case X86::BI__builtin_ia32_pshufd256: 4570 case X86::BI__builtin_ia32_pshufd512: 4571 case X86::BI__builtin_ia32_pshufhw: 4572 case X86::BI__builtin_ia32_pshufhw256: 4573 case X86::BI__builtin_ia32_pshufhw512: 4574 case X86::BI__builtin_ia32_pshuflw: 4575 case X86::BI__builtin_ia32_pshuflw256: 4576 case X86::BI__builtin_ia32_pshuflw512: 4577 case X86::BI__builtin_ia32_vcvtps2ph: 4578 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4579 case X86::BI__builtin_ia32_vcvtps2ph256: 4580 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4581 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4582 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4583 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4584 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4585 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4586 case X86::BI__builtin_ia32_rndscaleps_mask: 4587 case X86::BI__builtin_ia32_rndscalepd_mask: 4588 case X86::BI__builtin_ia32_rndscaleph_mask: 4589 case X86::BI__builtin_ia32_reducepd128_mask: 4590 case X86::BI__builtin_ia32_reducepd256_mask: 4591 case X86::BI__builtin_ia32_reducepd512_mask: 4592 case X86::BI__builtin_ia32_reduceps128_mask: 4593 case X86::BI__builtin_ia32_reduceps256_mask: 4594 case X86::BI__builtin_ia32_reduceps512_mask: 4595 case X86::BI__builtin_ia32_reduceph128_mask: 4596 case X86::BI__builtin_ia32_reduceph256_mask: 4597 case X86::BI__builtin_ia32_reduceph512_mask: 4598 case X86::BI__builtin_ia32_prold512: 4599 case X86::BI__builtin_ia32_prolq512: 4600 case X86::BI__builtin_ia32_prold128: 4601 case X86::BI__builtin_ia32_prold256: 4602 case X86::BI__builtin_ia32_prolq128: 4603 case X86::BI__builtin_ia32_prolq256: 4604 case X86::BI__builtin_ia32_prord512: 4605 case X86::BI__builtin_ia32_prorq512: 4606 case X86::BI__builtin_ia32_prord128: 4607 case X86::BI__builtin_ia32_prord256: 4608 case X86::BI__builtin_ia32_prorq128: 4609 case X86::BI__builtin_ia32_prorq256: 4610 case X86::BI__builtin_ia32_fpclasspd128_mask: 4611 case X86::BI__builtin_ia32_fpclasspd256_mask: 4612 case X86::BI__builtin_ia32_fpclassps128_mask: 4613 case X86::BI__builtin_ia32_fpclassps256_mask: 4614 case X86::BI__builtin_ia32_fpclassps512_mask: 4615 case X86::BI__builtin_ia32_fpclasspd512_mask: 4616 case X86::BI__builtin_ia32_fpclassph128_mask: 4617 case X86::BI__builtin_ia32_fpclassph256_mask: 4618 case X86::BI__builtin_ia32_fpclassph512_mask: 4619 case X86::BI__builtin_ia32_fpclasssd_mask: 4620 case X86::BI__builtin_ia32_fpclassss_mask: 4621 case X86::BI__builtin_ia32_fpclasssh_mask: 4622 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4623 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4624 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4625 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4626 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4627 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4628 case X86::BI__builtin_ia32_kshiftliqi: 4629 case X86::BI__builtin_ia32_kshiftlihi: 4630 case X86::BI__builtin_ia32_kshiftlisi: 4631 case X86::BI__builtin_ia32_kshiftlidi: 4632 case X86::BI__builtin_ia32_kshiftriqi: 4633 case X86::BI__builtin_ia32_kshiftrihi: 4634 case X86::BI__builtin_ia32_kshiftrisi: 4635 case X86::BI__builtin_ia32_kshiftridi: 4636 i = 1; l = 0; u = 255; 4637 break; 4638 case X86::BI__builtin_ia32_vperm2f128_pd256: 4639 case X86::BI__builtin_ia32_vperm2f128_ps256: 4640 case X86::BI__builtin_ia32_vperm2f128_si256: 4641 case X86::BI__builtin_ia32_permti256: 4642 case X86::BI__builtin_ia32_pblendw128: 4643 case X86::BI__builtin_ia32_pblendw256: 4644 case X86::BI__builtin_ia32_blendps256: 4645 case X86::BI__builtin_ia32_pblendd256: 4646 case X86::BI__builtin_ia32_palignr128: 4647 case X86::BI__builtin_ia32_palignr256: 4648 case X86::BI__builtin_ia32_palignr512: 4649 case X86::BI__builtin_ia32_alignq512: 4650 case X86::BI__builtin_ia32_alignd512: 4651 case X86::BI__builtin_ia32_alignd128: 4652 case X86::BI__builtin_ia32_alignd256: 4653 case X86::BI__builtin_ia32_alignq128: 4654 case X86::BI__builtin_ia32_alignq256: 4655 case X86::BI__builtin_ia32_vcomisd: 4656 case X86::BI__builtin_ia32_vcomiss: 4657 case X86::BI__builtin_ia32_shuf_f32x4: 4658 case X86::BI__builtin_ia32_shuf_f64x2: 4659 case X86::BI__builtin_ia32_shuf_i32x4: 4660 case X86::BI__builtin_ia32_shuf_i64x2: 4661 case X86::BI__builtin_ia32_shufpd512: 4662 case X86::BI__builtin_ia32_shufps: 4663 case X86::BI__builtin_ia32_shufps256: 4664 case X86::BI__builtin_ia32_shufps512: 4665 case X86::BI__builtin_ia32_dbpsadbw128: 4666 case X86::BI__builtin_ia32_dbpsadbw256: 4667 case X86::BI__builtin_ia32_dbpsadbw512: 4668 case X86::BI__builtin_ia32_vpshldd128: 4669 case X86::BI__builtin_ia32_vpshldd256: 4670 case X86::BI__builtin_ia32_vpshldd512: 4671 case X86::BI__builtin_ia32_vpshldq128: 4672 case X86::BI__builtin_ia32_vpshldq256: 4673 case X86::BI__builtin_ia32_vpshldq512: 4674 case X86::BI__builtin_ia32_vpshldw128: 4675 case X86::BI__builtin_ia32_vpshldw256: 4676 case X86::BI__builtin_ia32_vpshldw512: 4677 case X86::BI__builtin_ia32_vpshrdd128: 4678 case X86::BI__builtin_ia32_vpshrdd256: 4679 case X86::BI__builtin_ia32_vpshrdd512: 4680 case X86::BI__builtin_ia32_vpshrdq128: 4681 case X86::BI__builtin_ia32_vpshrdq256: 4682 case X86::BI__builtin_ia32_vpshrdq512: 4683 case X86::BI__builtin_ia32_vpshrdw128: 4684 case X86::BI__builtin_ia32_vpshrdw256: 4685 case X86::BI__builtin_ia32_vpshrdw512: 4686 i = 2; l = 0; u = 255; 4687 break; 4688 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4689 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4690 case X86::BI__builtin_ia32_fixupimmps512_mask: 4691 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4692 case X86::BI__builtin_ia32_fixupimmsd_mask: 4693 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4694 case X86::BI__builtin_ia32_fixupimmss_mask: 4695 case X86::BI__builtin_ia32_fixupimmss_maskz: 4696 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4697 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4698 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4699 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4700 case X86::BI__builtin_ia32_fixupimmps128_mask: 4701 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4702 case X86::BI__builtin_ia32_fixupimmps256_mask: 4703 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4704 case X86::BI__builtin_ia32_pternlogd512_mask: 4705 case X86::BI__builtin_ia32_pternlogd512_maskz: 4706 case X86::BI__builtin_ia32_pternlogq512_mask: 4707 case X86::BI__builtin_ia32_pternlogq512_maskz: 4708 case X86::BI__builtin_ia32_pternlogd128_mask: 4709 case X86::BI__builtin_ia32_pternlogd128_maskz: 4710 case X86::BI__builtin_ia32_pternlogd256_mask: 4711 case X86::BI__builtin_ia32_pternlogd256_maskz: 4712 case X86::BI__builtin_ia32_pternlogq128_mask: 4713 case X86::BI__builtin_ia32_pternlogq128_maskz: 4714 case X86::BI__builtin_ia32_pternlogq256_mask: 4715 case X86::BI__builtin_ia32_pternlogq256_maskz: 4716 i = 3; l = 0; u = 255; 4717 break; 4718 case X86::BI__builtin_ia32_gatherpfdpd: 4719 case X86::BI__builtin_ia32_gatherpfdps: 4720 case X86::BI__builtin_ia32_gatherpfqpd: 4721 case X86::BI__builtin_ia32_gatherpfqps: 4722 case X86::BI__builtin_ia32_scatterpfdpd: 4723 case X86::BI__builtin_ia32_scatterpfdps: 4724 case X86::BI__builtin_ia32_scatterpfqpd: 4725 case X86::BI__builtin_ia32_scatterpfqps: 4726 i = 4; l = 2; u = 3; 4727 break; 4728 case X86::BI__builtin_ia32_reducesd_mask: 4729 case X86::BI__builtin_ia32_reducess_mask: 4730 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4731 case X86::BI__builtin_ia32_rndscaless_round_mask: 4732 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4733 case X86::BI__builtin_ia32_reducesh_mask: 4734 i = 4; l = 0; u = 255; 4735 break; 4736 } 4737 4738 // Note that we don't force a hard error on the range check here, allowing 4739 // template-generated or macro-generated dead code to potentially have out-of- 4740 // range values. These need to code generate, but don't need to necessarily 4741 // make any sense. We use a warning that defaults to an error. 4742 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4743 } 4744 4745 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4746 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4747 /// Returns true when the format fits the function and the FormatStringInfo has 4748 /// been populated. 4749 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4750 FormatStringInfo *FSI) { 4751 FSI->HasVAListArg = Format->getFirstArg() == 0; 4752 FSI->FormatIdx = Format->getFormatIdx() - 1; 4753 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4754 4755 // The way the format attribute works in GCC, the implicit this argument 4756 // of member functions is counted. However, it doesn't appear in our own 4757 // lists, so decrement format_idx in that case. 4758 if (IsCXXMember) { 4759 if(FSI->FormatIdx == 0) 4760 return false; 4761 --FSI->FormatIdx; 4762 if (FSI->FirstDataArg != 0) 4763 --FSI->FirstDataArg; 4764 } 4765 return true; 4766 } 4767 4768 /// Checks if a the given expression evaluates to null. 4769 /// 4770 /// Returns true if the value evaluates to null. 4771 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4772 // If the expression has non-null type, it doesn't evaluate to null. 4773 if (auto nullability 4774 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4775 if (*nullability == NullabilityKind::NonNull) 4776 return false; 4777 } 4778 4779 // As a special case, transparent unions initialized with zero are 4780 // considered null for the purposes of the nonnull attribute. 4781 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4782 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4783 if (const CompoundLiteralExpr *CLE = 4784 dyn_cast<CompoundLiteralExpr>(Expr)) 4785 if (const InitListExpr *ILE = 4786 dyn_cast<InitListExpr>(CLE->getInitializer())) 4787 Expr = ILE->getInit(0); 4788 } 4789 4790 bool Result; 4791 return (!Expr->isValueDependent() && 4792 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4793 !Result); 4794 } 4795 4796 static void CheckNonNullArgument(Sema &S, 4797 const Expr *ArgExpr, 4798 SourceLocation CallSiteLoc) { 4799 if (CheckNonNullExpr(S, ArgExpr)) 4800 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4801 S.PDiag(diag::warn_null_arg) 4802 << ArgExpr->getSourceRange()); 4803 } 4804 4805 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4806 FormatStringInfo FSI; 4807 if ((GetFormatStringType(Format) == FST_NSString) && 4808 getFormatStringInfo(Format, false, &FSI)) { 4809 Idx = FSI.FormatIdx; 4810 return true; 4811 } 4812 return false; 4813 } 4814 4815 /// Diagnose use of %s directive in an NSString which is being passed 4816 /// as formatting string to formatting method. 4817 static void 4818 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4819 const NamedDecl *FDecl, 4820 Expr **Args, 4821 unsigned NumArgs) { 4822 unsigned Idx = 0; 4823 bool Format = false; 4824 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4825 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4826 Idx = 2; 4827 Format = true; 4828 } 4829 else 4830 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4831 if (S.GetFormatNSStringIdx(I, Idx)) { 4832 Format = true; 4833 break; 4834 } 4835 } 4836 if (!Format || NumArgs <= Idx) 4837 return; 4838 const Expr *FormatExpr = Args[Idx]; 4839 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4840 FormatExpr = CSCE->getSubExpr(); 4841 const StringLiteral *FormatString; 4842 if (const ObjCStringLiteral *OSL = 4843 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4844 FormatString = OSL->getString(); 4845 else 4846 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4847 if (!FormatString) 4848 return; 4849 if (S.FormatStringHasSArg(FormatString)) { 4850 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4851 << "%s" << 1 << 1; 4852 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4853 << FDecl->getDeclName(); 4854 } 4855 } 4856 4857 /// Determine whether the given type has a non-null nullability annotation. 4858 static bool isNonNullType(ASTContext &ctx, QualType type) { 4859 if (auto nullability = type->getNullability(ctx)) 4860 return *nullability == NullabilityKind::NonNull; 4861 4862 return false; 4863 } 4864 4865 static void CheckNonNullArguments(Sema &S, 4866 const NamedDecl *FDecl, 4867 const FunctionProtoType *Proto, 4868 ArrayRef<const Expr *> Args, 4869 SourceLocation CallSiteLoc) { 4870 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4871 4872 // Already checked by by constant evaluator. 4873 if (S.isConstantEvaluated()) 4874 return; 4875 // Check the attributes attached to the method/function itself. 4876 llvm::SmallBitVector NonNullArgs; 4877 if (FDecl) { 4878 // Handle the nonnull attribute on the function/method declaration itself. 4879 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4880 if (!NonNull->args_size()) { 4881 // Easy case: all pointer arguments are nonnull. 4882 for (const auto *Arg : Args) 4883 if (S.isValidPointerAttrType(Arg->getType())) 4884 CheckNonNullArgument(S, Arg, CallSiteLoc); 4885 return; 4886 } 4887 4888 for (const ParamIdx &Idx : NonNull->args()) { 4889 unsigned IdxAST = Idx.getASTIndex(); 4890 if (IdxAST >= Args.size()) 4891 continue; 4892 if (NonNullArgs.empty()) 4893 NonNullArgs.resize(Args.size()); 4894 NonNullArgs.set(IdxAST); 4895 } 4896 } 4897 } 4898 4899 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4900 // Handle the nonnull attribute on the parameters of the 4901 // function/method. 4902 ArrayRef<ParmVarDecl*> parms; 4903 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4904 parms = FD->parameters(); 4905 else 4906 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4907 4908 unsigned ParamIndex = 0; 4909 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4910 I != E; ++I, ++ParamIndex) { 4911 const ParmVarDecl *PVD = *I; 4912 if (PVD->hasAttr<NonNullAttr>() || 4913 isNonNullType(S.Context, PVD->getType())) { 4914 if (NonNullArgs.empty()) 4915 NonNullArgs.resize(Args.size()); 4916 4917 NonNullArgs.set(ParamIndex); 4918 } 4919 } 4920 } else { 4921 // If we have a non-function, non-method declaration but no 4922 // function prototype, try to dig out the function prototype. 4923 if (!Proto) { 4924 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4925 QualType type = VD->getType().getNonReferenceType(); 4926 if (auto pointerType = type->getAs<PointerType>()) 4927 type = pointerType->getPointeeType(); 4928 else if (auto blockType = type->getAs<BlockPointerType>()) 4929 type = blockType->getPointeeType(); 4930 // FIXME: data member pointers? 4931 4932 // Dig out the function prototype, if there is one. 4933 Proto = type->getAs<FunctionProtoType>(); 4934 } 4935 } 4936 4937 // Fill in non-null argument information from the nullability 4938 // information on the parameter types (if we have them). 4939 if (Proto) { 4940 unsigned Index = 0; 4941 for (auto paramType : Proto->getParamTypes()) { 4942 if (isNonNullType(S.Context, paramType)) { 4943 if (NonNullArgs.empty()) 4944 NonNullArgs.resize(Args.size()); 4945 4946 NonNullArgs.set(Index); 4947 } 4948 4949 ++Index; 4950 } 4951 } 4952 } 4953 4954 // Check for non-null arguments. 4955 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4956 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4957 if (NonNullArgs[ArgIndex]) 4958 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4959 } 4960 } 4961 4962 /// Warn if a pointer or reference argument passed to a function points to an 4963 /// object that is less aligned than the parameter. This can happen when 4964 /// creating a typedef with a lower alignment than the original type and then 4965 /// calling functions defined in terms of the original type. 4966 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 4967 StringRef ParamName, QualType ArgTy, 4968 QualType ParamTy) { 4969 4970 // If a function accepts a pointer or reference type 4971 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 4972 return; 4973 4974 // If the parameter is a pointer type, get the pointee type for the 4975 // argument too. If the parameter is a reference type, don't try to get 4976 // the pointee type for the argument. 4977 if (ParamTy->isPointerType()) 4978 ArgTy = ArgTy->getPointeeType(); 4979 4980 // Remove reference or pointer 4981 ParamTy = ParamTy->getPointeeType(); 4982 4983 // Find expected alignment, and the actual alignment of the passed object. 4984 // getTypeAlignInChars requires complete types 4985 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 4986 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 4987 ArgTy->isUndeducedType()) 4988 return; 4989 4990 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 4991 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 4992 4993 // If the argument is less aligned than the parameter, there is a 4994 // potential alignment issue. 4995 if (ArgAlign < ParamAlign) 4996 Diag(Loc, diag::warn_param_mismatched_alignment) 4997 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 4998 << ParamName << FDecl; 4999 } 5000 5001 /// Handles the checks for format strings, non-POD arguments to vararg 5002 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 5003 /// attributes. 5004 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 5005 const Expr *ThisArg, ArrayRef<const Expr *> Args, 5006 bool IsMemberFunction, SourceLocation Loc, 5007 SourceRange Range, VariadicCallType CallType) { 5008 // FIXME: We should check as much as we can in the template definition. 5009 if (CurContext->isDependentContext()) 5010 return; 5011 5012 // Printf and scanf checking. 5013 llvm::SmallBitVector CheckedVarArgs; 5014 if (FDecl) { 5015 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 5016 // Only create vector if there are format attributes. 5017 CheckedVarArgs.resize(Args.size()); 5018 5019 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 5020 CheckedVarArgs); 5021 } 5022 } 5023 5024 // Refuse POD arguments that weren't caught by the format string 5025 // checks above. 5026 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 5027 if (CallType != VariadicDoesNotApply && 5028 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 5029 unsigned NumParams = Proto ? Proto->getNumParams() 5030 : FDecl && isa<FunctionDecl>(FDecl) 5031 ? cast<FunctionDecl>(FDecl)->getNumParams() 5032 : FDecl && isa<ObjCMethodDecl>(FDecl) 5033 ? cast<ObjCMethodDecl>(FDecl)->param_size() 5034 : 0; 5035 5036 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 5037 // Args[ArgIdx] can be null in malformed code. 5038 if (const Expr *Arg = Args[ArgIdx]) { 5039 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 5040 checkVariadicArgument(Arg, CallType); 5041 } 5042 } 5043 } 5044 5045 if (FDecl || Proto) { 5046 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 5047 5048 // Type safety checking. 5049 if (FDecl) { 5050 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 5051 CheckArgumentWithTypeTag(I, Args, Loc); 5052 } 5053 } 5054 5055 // Check that passed arguments match the alignment of original arguments. 5056 // Try to get the missing prototype from the declaration. 5057 if (!Proto && FDecl) { 5058 const auto *FT = FDecl->getFunctionType(); 5059 if (isa_and_nonnull<FunctionProtoType>(FT)) 5060 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 5061 } 5062 if (Proto) { 5063 // For variadic functions, we may have more args than parameters. 5064 // For some K&R functions, we may have less args than parameters. 5065 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 5066 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 5067 // Args[ArgIdx] can be null in malformed code. 5068 if (const Expr *Arg = Args[ArgIdx]) { 5069 if (Arg->containsErrors()) 5070 continue; 5071 5072 QualType ParamTy = Proto->getParamType(ArgIdx); 5073 QualType ArgTy = Arg->getType(); 5074 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 5075 ArgTy, ParamTy); 5076 } 5077 } 5078 } 5079 5080 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 5081 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 5082 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 5083 if (!Arg->isValueDependent()) { 5084 Expr::EvalResult Align; 5085 if (Arg->EvaluateAsInt(Align, Context)) { 5086 const llvm::APSInt &I = Align.Val.getInt(); 5087 if (!I.isPowerOf2()) 5088 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 5089 << Arg->getSourceRange(); 5090 5091 if (I > Sema::MaximumAlignment) 5092 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 5093 << Arg->getSourceRange() << Sema::MaximumAlignment; 5094 } 5095 } 5096 } 5097 5098 if (FD) 5099 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 5100 } 5101 5102 /// CheckConstructorCall - Check a constructor call for correctness and safety 5103 /// properties not enforced by the C type system. 5104 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 5105 ArrayRef<const Expr *> Args, 5106 const FunctionProtoType *Proto, 5107 SourceLocation Loc) { 5108 VariadicCallType CallType = 5109 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 5110 5111 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 5112 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 5113 Context.getPointerType(Ctor->getThisObjectType())); 5114 5115 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 5116 Loc, SourceRange(), CallType); 5117 } 5118 5119 /// CheckFunctionCall - Check a direct function call for various correctness 5120 /// and safety properties not strictly enforced by the C type system. 5121 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 5122 const FunctionProtoType *Proto) { 5123 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 5124 isa<CXXMethodDecl>(FDecl); 5125 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 5126 IsMemberOperatorCall; 5127 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 5128 TheCall->getCallee()); 5129 Expr** Args = TheCall->getArgs(); 5130 unsigned NumArgs = TheCall->getNumArgs(); 5131 5132 Expr *ImplicitThis = nullptr; 5133 if (IsMemberOperatorCall) { 5134 // If this is a call to a member operator, hide the first argument 5135 // from checkCall. 5136 // FIXME: Our choice of AST representation here is less than ideal. 5137 ImplicitThis = Args[0]; 5138 ++Args; 5139 --NumArgs; 5140 } else if (IsMemberFunction) 5141 ImplicitThis = 5142 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 5143 5144 if (ImplicitThis) { 5145 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 5146 // used. 5147 QualType ThisType = ImplicitThis->getType(); 5148 if (!ThisType->isPointerType()) { 5149 assert(!ThisType->isReferenceType()); 5150 ThisType = Context.getPointerType(ThisType); 5151 } 5152 5153 QualType ThisTypeFromDecl = 5154 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 5155 5156 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 5157 ThisTypeFromDecl); 5158 } 5159 5160 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 5161 IsMemberFunction, TheCall->getRParenLoc(), 5162 TheCall->getCallee()->getSourceRange(), CallType); 5163 5164 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5165 // None of the checks below are needed for functions that don't have 5166 // simple names (e.g., C++ conversion functions). 5167 if (!FnInfo) 5168 return false; 5169 5170 CheckTCBEnforcement(TheCall, FDecl); 5171 5172 CheckAbsoluteValueFunction(TheCall, FDecl); 5173 CheckMaxUnsignedZero(TheCall, FDecl); 5174 5175 if (getLangOpts().ObjC) 5176 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 5177 5178 unsigned CMId = FDecl->getMemoryFunctionKind(); 5179 5180 // Handle memory setting and copying functions. 5181 switch (CMId) { 5182 case 0: 5183 return false; 5184 case Builtin::BIstrlcpy: // fallthrough 5185 case Builtin::BIstrlcat: 5186 CheckStrlcpycatArguments(TheCall, FnInfo); 5187 break; 5188 case Builtin::BIstrncat: 5189 CheckStrncatArguments(TheCall, FnInfo); 5190 break; 5191 case Builtin::BIfree: 5192 CheckFreeArguments(TheCall); 5193 break; 5194 default: 5195 CheckMemaccessArguments(TheCall, CMId, FnInfo); 5196 } 5197 5198 return false; 5199 } 5200 5201 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 5202 ArrayRef<const Expr *> Args) { 5203 VariadicCallType CallType = 5204 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 5205 5206 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 5207 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 5208 CallType); 5209 5210 return false; 5211 } 5212 5213 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 5214 const FunctionProtoType *Proto) { 5215 QualType Ty; 5216 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 5217 Ty = V->getType().getNonReferenceType(); 5218 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 5219 Ty = F->getType().getNonReferenceType(); 5220 else 5221 return false; 5222 5223 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 5224 !Ty->isFunctionProtoType()) 5225 return false; 5226 5227 VariadicCallType CallType; 5228 if (!Proto || !Proto->isVariadic()) { 5229 CallType = VariadicDoesNotApply; 5230 } else if (Ty->isBlockPointerType()) { 5231 CallType = VariadicBlock; 5232 } else { // Ty->isFunctionPointerType() 5233 CallType = VariadicFunction; 5234 } 5235 5236 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 5237 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5238 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5239 TheCall->getCallee()->getSourceRange(), CallType); 5240 5241 return false; 5242 } 5243 5244 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 5245 /// such as function pointers returned from functions. 5246 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 5247 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 5248 TheCall->getCallee()); 5249 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 5250 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5251 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5252 TheCall->getCallee()->getSourceRange(), CallType); 5253 5254 return false; 5255 } 5256 5257 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 5258 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 5259 return false; 5260 5261 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 5262 switch (Op) { 5263 case AtomicExpr::AO__c11_atomic_init: 5264 case AtomicExpr::AO__opencl_atomic_init: 5265 llvm_unreachable("There is no ordering argument for an init"); 5266 5267 case AtomicExpr::AO__c11_atomic_load: 5268 case AtomicExpr::AO__opencl_atomic_load: 5269 case AtomicExpr::AO__atomic_load_n: 5270 case AtomicExpr::AO__atomic_load: 5271 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5272 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5273 5274 case AtomicExpr::AO__c11_atomic_store: 5275 case AtomicExpr::AO__opencl_atomic_store: 5276 case AtomicExpr::AO__atomic_store: 5277 case AtomicExpr::AO__atomic_store_n: 5278 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5279 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5280 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5281 5282 default: 5283 return true; 5284 } 5285 } 5286 5287 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5288 AtomicExpr::AtomicOp Op) { 5289 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5290 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5291 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5292 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5293 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5294 Op); 5295 } 5296 5297 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5298 SourceLocation RParenLoc, MultiExprArg Args, 5299 AtomicExpr::AtomicOp Op, 5300 AtomicArgumentOrder ArgOrder) { 5301 // All the non-OpenCL operations take one of the following forms. 5302 // The OpenCL operations take the __c11 forms with one extra argument for 5303 // synchronization scope. 5304 enum { 5305 // C __c11_atomic_init(A *, C) 5306 Init, 5307 5308 // C __c11_atomic_load(A *, int) 5309 Load, 5310 5311 // void __atomic_load(A *, CP, int) 5312 LoadCopy, 5313 5314 // void __atomic_store(A *, CP, int) 5315 Copy, 5316 5317 // C __c11_atomic_add(A *, M, int) 5318 Arithmetic, 5319 5320 // C __atomic_exchange_n(A *, CP, int) 5321 Xchg, 5322 5323 // void __atomic_exchange(A *, C *, CP, int) 5324 GNUXchg, 5325 5326 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 5327 C11CmpXchg, 5328 5329 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 5330 GNUCmpXchg 5331 } Form = Init; 5332 5333 const unsigned NumForm = GNUCmpXchg + 1; 5334 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 5335 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 5336 // where: 5337 // C is an appropriate type, 5338 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 5339 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 5340 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 5341 // the int parameters are for orderings. 5342 5343 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 5344 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 5345 "need to update code for modified forms"); 5346 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 5347 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 5348 AtomicExpr::AO__atomic_load, 5349 "need to update code for modified C11 atomics"); 5350 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 5351 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 5352 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 5353 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 5354 IsOpenCL; 5355 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 5356 Op == AtomicExpr::AO__atomic_store_n || 5357 Op == AtomicExpr::AO__atomic_exchange_n || 5358 Op == AtomicExpr::AO__atomic_compare_exchange_n; 5359 bool IsAddSub = false; 5360 5361 switch (Op) { 5362 case AtomicExpr::AO__c11_atomic_init: 5363 case AtomicExpr::AO__opencl_atomic_init: 5364 Form = Init; 5365 break; 5366 5367 case AtomicExpr::AO__c11_atomic_load: 5368 case AtomicExpr::AO__opencl_atomic_load: 5369 case AtomicExpr::AO__atomic_load_n: 5370 Form = Load; 5371 break; 5372 5373 case AtomicExpr::AO__atomic_load: 5374 Form = LoadCopy; 5375 break; 5376 5377 case AtomicExpr::AO__c11_atomic_store: 5378 case AtomicExpr::AO__opencl_atomic_store: 5379 case AtomicExpr::AO__atomic_store: 5380 case AtomicExpr::AO__atomic_store_n: 5381 Form = Copy; 5382 break; 5383 5384 case AtomicExpr::AO__c11_atomic_fetch_add: 5385 case AtomicExpr::AO__c11_atomic_fetch_sub: 5386 case AtomicExpr::AO__opencl_atomic_fetch_add: 5387 case AtomicExpr::AO__opencl_atomic_fetch_sub: 5388 case AtomicExpr::AO__atomic_fetch_add: 5389 case AtomicExpr::AO__atomic_fetch_sub: 5390 case AtomicExpr::AO__atomic_add_fetch: 5391 case AtomicExpr::AO__atomic_sub_fetch: 5392 IsAddSub = true; 5393 Form = Arithmetic; 5394 break; 5395 case AtomicExpr::AO__c11_atomic_fetch_and: 5396 case AtomicExpr::AO__c11_atomic_fetch_or: 5397 case AtomicExpr::AO__c11_atomic_fetch_xor: 5398 case AtomicExpr::AO__c11_atomic_fetch_nand: 5399 case AtomicExpr::AO__opencl_atomic_fetch_and: 5400 case AtomicExpr::AO__opencl_atomic_fetch_or: 5401 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5402 case AtomicExpr::AO__atomic_fetch_and: 5403 case AtomicExpr::AO__atomic_fetch_or: 5404 case AtomicExpr::AO__atomic_fetch_xor: 5405 case AtomicExpr::AO__atomic_fetch_nand: 5406 case AtomicExpr::AO__atomic_and_fetch: 5407 case AtomicExpr::AO__atomic_or_fetch: 5408 case AtomicExpr::AO__atomic_xor_fetch: 5409 case AtomicExpr::AO__atomic_nand_fetch: 5410 Form = Arithmetic; 5411 break; 5412 case AtomicExpr::AO__c11_atomic_fetch_min: 5413 case AtomicExpr::AO__c11_atomic_fetch_max: 5414 case AtomicExpr::AO__opencl_atomic_fetch_min: 5415 case AtomicExpr::AO__opencl_atomic_fetch_max: 5416 case AtomicExpr::AO__atomic_min_fetch: 5417 case AtomicExpr::AO__atomic_max_fetch: 5418 case AtomicExpr::AO__atomic_fetch_min: 5419 case AtomicExpr::AO__atomic_fetch_max: 5420 Form = Arithmetic; 5421 break; 5422 5423 case AtomicExpr::AO__c11_atomic_exchange: 5424 case AtomicExpr::AO__opencl_atomic_exchange: 5425 case AtomicExpr::AO__atomic_exchange_n: 5426 Form = Xchg; 5427 break; 5428 5429 case AtomicExpr::AO__atomic_exchange: 5430 Form = GNUXchg; 5431 break; 5432 5433 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5434 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5435 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5436 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5437 Form = C11CmpXchg; 5438 break; 5439 5440 case AtomicExpr::AO__atomic_compare_exchange: 5441 case AtomicExpr::AO__atomic_compare_exchange_n: 5442 Form = GNUCmpXchg; 5443 break; 5444 } 5445 5446 unsigned AdjustedNumArgs = NumArgs[Form]; 5447 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 5448 ++AdjustedNumArgs; 5449 // Check we have the right number of arguments. 5450 if (Args.size() < AdjustedNumArgs) { 5451 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5452 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5453 << ExprRange; 5454 return ExprError(); 5455 } else if (Args.size() > AdjustedNumArgs) { 5456 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5457 diag::err_typecheck_call_too_many_args) 5458 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5459 << ExprRange; 5460 return ExprError(); 5461 } 5462 5463 // Inspect the first argument of the atomic operation. 5464 Expr *Ptr = Args[0]; 5465 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5466 if (ConvertedPtr.isInvalid()) 5467 return ExprError(); 5468 5469 Ptr = ConvertedPtr.get(); 5470 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5471 if (!pointerType) { 5472 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5473 << Ptr->getType() << Ptr->getSourceRange(); 5474 return ExprError(); 5475 } 5476 5477 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5478 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5479 QualType ValType = AtomTy; // 'C' 5480 if (IsC11) { 5481 if (!AtomTy->isAtomicType()) { 5482 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5483 << Ptr->getType() << Ptr->getSourceRange(); 5484 return ExprError(); 5485 } 5486 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5487 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5488 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5489 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5490 << Ptr->getSourceRange(); 5491 return ExprError(); 5492 } 5493 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5494 } else if (Form != Load && Form != LoadCopy) { 5495 if (ValType.isConstQualified()) { 5496 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5497 << Ptr->getType() << Ptr->getSourceRange(); 5498 return ExprError(); 5499 } 5500 } 5501 5502 // For an arithmetic operation, the implied arithmetic must be well-formed. 5503 if (Form == Arithmetic) { 5504 // gcc does not enforce these rules for GNU atomics, but we do so for 5505 // sanity. 5506 auto IsAllowedValueType = [&](QualType ValType) { 5507 if (ValType->isIntegerType()) 5508 return true; 5509 if (ValType->isPointerType()) 5510 return true; 5511 if (!ValType->isFloatingType()) 5512 return false; 5513 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5514 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5515 &Context.getTargetInfo().getLongDoubleFormat() == 5516 &llvm::APFloat::x87DoubleExtended()) 5517 return false; 5518 return true; 5519 }; 5520 if (IsAddSub && !IsAllowedValueType(ValType)) { 5521 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5522 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5523 return ExprError(); 5524 } 5525 if (!IsAddSub && !ValType->isIntegerType()) { 5526 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5527 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5528 return ExprError(); 5529 } 5530 if (IsC11 && ValType->isPointerType() && 5531 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5532 diag::err_incomplete_type)) { 5533 return ExprError(); 5534 } 5535 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5536 // For __atomic_*_n operations, the value type must be a scalar integral or 5537 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5538 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5539 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5540 return ExprError(); 5541 } 5542 5543 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5544 !AtomTy->isScalarType()) { 5545 // For GNU atomics, require a trivially-copyable type. This is not part of 5546 // the GNU atomics specification, but we enforce it for sanity. 5547 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5548 << Ptr->getType() << Ptr->getSourceRange(); 5549 return ExprError(); 5550 } 5551 5552 switch (ValType.getObjCLifetime()) { 5553 case Qualifiers::OCL_None: 5554 case Qualifiers::OCL_ExplicitNone: 5555 // okay 5556 break; 5557 5558 case Qualifiers::OCL_Weak: 5559 case Qualifiers::OCL_Strong: 5560 case Qualifiers::OCL_Autoreleasing: 5561 // FIXME: Can this happen? By this point, ValType should be known 5562 // to be trivially copyable. 5563 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5564 << ValType << Ptr->getSourceRange(); 5565 return ExprError(); 5566 } 5567 5568 // All atomic operations have an overload which takes a pointer to a volatile 5569 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5570 // into the result or the other operands. Similarly atomic_load takes a 5571 // pointer to a const 'A'. 5572 ValType.removeLocalVolatile(); 5573 ValType.removeLocalConst(); 5574 QualType ResultType = ValType; 5575 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5576 Form == Init) 5577 ResultType = Context.VoidTy; 5578 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5579 ResultType = Context.BoolTy; 5580 5581 // The type of a parameter passed 'by value'. In the GNU atomics, such 5582 // arguments are actually passed as pointers. 5583 QualType ByValType = ValType; // 'CP' 5584 bool IsPassedByAddress = false; 5585 if (!IsC11 && !IsN) { 5586 ByValType = Ptr->getType(); 5587 IsPassedByAddress = true; 5588 } 5589 5590 SmallVector<Expr *, 5> APIOrderedArgs; 5591 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5592 APIOrderedArgs.push_back(Args[0]); 5593 switch (Form) { 5594 case Init: 5595 case Load: 5596 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5597 break; 5598 case LoadCopy: 5599 case Copy: 5600 case Arithmetic: 5601 case Xchg: 5602 APIOrderedArgs.push_back(Args[2]); // Val1 5603 APIOrderedArgs.push_back(Args[1]); // Order 5604 break; 5605 case GNUXchg: 5606 APIOrderedArgs.push_back(Args[2]); // Val1 5607 APIOrderedArgs.push_back(Args[3]); // Val2 5608 APIOrderedArgs.push_back(Args[1]); // Order 5609 break; 5610 case C11CmpXchg: 5611 APIOrderedArgs.push_back(Args[2]); // Val1 5612 APIOrderedArgs.push_back(Args[4]); // Val2 5613 APIOrderedArgs.push_back(Args[1]); // Order 5614 APIOrderedArgs.push_back(Args[3]); // OrderFail 5615 break; 5616 case GNUCmpXchg: 5617 APIOrderedArgs.push_back(Args[2]); // Val1 5618 APIOrderedArgs.push_back(Args[4]); // Val2 5619 APIOrderedArgs.push_back(Args[5]); // Weak 5620 APIOrderedArgs.push_back(Args[1]); // Order 5621 APIOrderedArgs.push_back(Args[3]); // OrderFail 5622 break; 5623 } 5624 } else 5625 APIOrderedArgs.append(Args.begin(), Args.end()); 5626 5627 // The first argument's non-CV pointer type is used to deduce the type of 5628 // subsequent arguments, except for: 5629 // - weak flag (always converted to bool) 5630 // - memory order (always converted to int) 5631 // - scope (always converted to int) 5632 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5633 QualType Ty; 5634 if (i < NumVals[Form] + 1) { 5635 switch (i) { 5636 case 0: 5637 // The first argument is always a pointer. It has a fixed type. 5638 // It is always dereferenced, a nullptr is undefined. 5639 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5640 // Nothing else to do: we already know all we want about this pointer. 5641 continue; 5642 case 1: 5643 // The second argument is the non-atomic operand. For arithmetic, this 5644 // is always passed by value, and for a compare_exchange it is always 5645 // passed by address. For the rest, GNU uses by-address and C11 uses 5646 // by-value. 5647 assert(Form != Load); 5648 if (Form == Arithmetic && ValType->isPointerType()) 5649 Ty = Context.getPointerDiffType(); 5650 else if (Form == Init || Form == Arithmetic) 5651 Ty = ValType; 5652 else if (Form == Copy || Form == Xchg) { 5653 if (IsPassedByAddress) { 5654 // The value pointer is always dereferenced, a nullptr is undefined. 5655 CheckNonNullArgument(*this, APIOrderedArgs[i], 5656 ExprRange.getBegin()); 5657 } 5658 Ty = ByValType; 5659 } else { 5660 Expr *ValArg = APIOrderedArgs[i]; 5661 // The value pointer is always dereferenced, a nullptr is undefined. 5662 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5663 LangAS AS = LangAS::Default; 5664 // Keep address space of non-atomic pointer type. 5665 if (const PointerType *PtrTy = 5666 ValArg->getType()->getAs<PointerType>()) { 5667 AS = PtrTy->getPointeeType().getAddressSpace(); 5668 } 5669 Ty = Context.getPointerType( 5670 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5671 } 5672 break; 5673 case 2: 5674 // The third argument to compare_exchange / GNU exchange is the desired 5675 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5676 if (IsPassedByAddress) 5677 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5678 Ty = ByValType; 5679 break; 5680 case 3: 5681 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5682 Ty = Context.BoolTy; 5683 break; 5684 } 5685 } else { 5686 // The order(s) and scope are always converted to int. 5687 Ty = Context.IntTy; 5688 } 5689 5690 InitializedEntity Entity = 5691 InitializedEntity::InitializeParameter(Context, Ty, false); 5692 ExprResult Arg = APIOrderedArgs[i]; 5693 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5694 if (Arg.isInvalid()) 5695 return true; 5696 APIOrderedArgs[i] = Arg.get(); 5697 } 5698 5699 // Permute the arguments into a 'consistent' order. 5700 SmallVector<Expr*, 5> SubExprs; 5701 SubExprs.push_back(Ptr); 5702 switch (Form) { 5703 case Init: 5704 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5705 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5706 break; 5707 case Load: 5708 SubExprs.push_back(APIOrderedArgs[1]); // Order 5709 break; 5710 case LoadCopy: 5711 case Copy: 5712 case Arithmetic: 5713 case Xchg: 5714 SubExprs.push_back(APIOrderedArgs[2]); // Order 5715 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5716 break; 5717 case GNUXchg: 5718 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5719 SubExprs.push_back(APIOrderedArgs[3]); // Order 5720 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5721 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5722 break; 5723 case C11CmpXchg: 5724 SubExprs.push_back(APIOrderedArgs[3]); // Order 5725 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5726 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5727 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5728 break; 5729 case GNUCmpXchg: 5730 SubExprs.push_back(APIOrderedArgs[4]); // Order 5731 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5732 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5733 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5734 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5735 break; 5736 } 5737 5738 if (SubExprs.size() >= 2 && Form != Init) { 5739 if (Optional<llvm::APSInt> Result = 5740 SubExprs[1]->getIntegerConstantExpr(Context)) 5741 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5742 Diag(SubExprs[1]->getBeginLoc(), 5743 diag::warn_atomic_op_has_invalid_memory_order) 5744 << SubExprs[1]->getSourceRange(); 5745 } 5746 5747 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5748 auto *Scope = Args[Args.size() - 1]; 5749 if (Optional<llvm::APSInt> Result = 5750 Scope->getIntegerConstantExpr(Context)) { 5751 if (!ScopeModel->isValid(Result->getZExtValue())) 5752 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5753 << Scope->getSourceRange(); 5754 } 5755 SubExprs.push_back(Scope); 5756 } 5757 5758 AtomicExpr *AE = new (Context) 5759 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5760 5761 if ((Op == AtomicExpr::AO__c11_atomic_load || 5762 Op == AtomicExpr::AO__c11_atomic_store || 5763 Op == AtomicExpr::AO__opencl_atomic_load || 5764 Op == AtomicExpr::AO__opencl_atomic_store ) && 5765 Context.AtomicUsesUnsupportedLibcall(AE)) 5766 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5767 << ((Op == AtomicExpr::AO__c11_atomic_load || 5768 Op == AtomicExpr::AO__opencl_atomic_load) 5769 ? 0 5770 : 1); 5771 5772 if (ValType->isExtIntType()) { 5773 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5774 return ExprError(); 5775 } 5776 5777 return AE; 5778 } 5779 5780 /// checkBuiltinArgument - Given a call to a builtin function, perform 5781 /// normal type-checking on the given argument, updating the call in 5782 /// place. This is useful when a builtin function requires custom 5783 /// type-checking for some of its arguments but not necessarily all of 5784 /// them. 5785 /// 5786 /// Returns true on error. 5787 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5788 FunctionDecl *Fn = E->getDirectCallee(); 5789 assert(Fn && "builtin call without direct callee!"); 5790 5791 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5792 InitializedEntity Entity = 5793 InitializedEntity::InitializeParameter(S.Context, Param); 5794 5795 ExprResult Arg = E->getArg(0); 5796 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5797 if (Arg.isInvalid()) 5798 return true; 5799 5800 E->setArg(ArgIndex, Arg.get()); 5801 return false; 5802 } 5803 5804 /// We have a call to a function like __sync_fetch_and_add, which is an 5805 /// overloaded function based on the pointer type of its first argument. 5806 /// The main BuildCallExpr routines have already promoted the types of 5807 /// arguments because all of these calls are prototyped as void(...). 5808 /// 5809 /// This function goes through and does final semantic checking for these 5810 /// builtins, as well as generating any warnings. 5811 ExprResult 5812 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5813 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5814 Expr *Callee = TheCall->getCallee(); 5815 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5816 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5817 5818 // Ensure that we have at least one argument to do type inference from. 5819 if (TheCall->getNumArgs() < 1) { 5820 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5821 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5822 return ExprError(); 5823 } 5824 5825 // Inspect the first argument of the atomic builtin. This should always be 5826 // a pointer type, whose element is an integral scalar or pointer type. 5827 // Because it is a pointer type, we don't have to worry about any implicit 5828 // casts here. 5829 // FIXME: We don't allow floating point scalars as input. 5830 Expr *FirstArg = TheCall->getArg(0); 5831 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5832 if (FirstArgResult.isInvalid()) 5833 return ExprError(); 5834 FirstArg = FirstArgResult.get(); 5835 TheCall->setArg(0, FirstArg); 5836 5837 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5838 if (!pointerType) { 5839 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5840 << FirstArg->getType() << FirstArg->getSourceRange(); 5841 return ExprError(); 5842 } 5843 5844 QualType ValType = pointerType->getPointeeType(); 5845 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5846 !ValType->isBlockPointerType()) { 5847 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5848 << FirstArg->getType() << FirstArg->getSourceRange(); 5849 return ExprError(); 5850 } 5851 5852 if (ValType.isConstQualified()) { 5853 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5854 << FirstArg->getType() << FirstArg->getSourceRange(); 5855 return ExprError(); 5856 } 5857 5858 switch (ValType.getObjCLifetime()) { 5859 case Qualifiers::OCL_None: 5860 case Qualifiers::OCL_ExplicitNone: 5861 // okay 5862 break; 5863 5864 case Qualifiers::OCL_Weak: 5865 case Qualifiers::OCL_Strong: 5866 case Qualifiers::OCL_Autoreleasing: 5867 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5868 << ValType << FirstArg->getSourceRange(); 5869 return ExprError(); 5870 } 5871 5872 // Strip any qualifiers off ValType. 5873 ValType = ValType.getUnqualifiedType(); 5874 5875 // The majority of builtins return a value, but a few have special return 5876 // types, so allow them to override appropriately below. 5877 QualType ResultType = ValType; 5878 5879 // We need to figure out which concrete builtin this maps onto. For example, 5880 // __sync_fetch_and_add with a 2 byte object turns into 5881 // __sync_fetch_and_add_2. 5882 #define BUILTIN_ROW(x) \ 5883 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5884 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5885 5886 static const unsigned BuiltinIndices[][5] = { 5887 BUILTIN_ROW(__sync_fetch_and_add), 5888 BUILTIN_ROW(__sync_fetch_and_sub), 5889 BUILTIN_ROW(__sync_fetch_and_or), 5890 BUILTIN_ROW(__sync_fetch_and_and), 5891 BUILTIN_ROW(__sync_fetch_and_xor), 5892 BUILTIN_ROW(__sync_fetch_and_nand), 5893 5894 BUILTIN_ROW(__sync_add_and_fetch), 5895 BUILTIN_ROW(__sync_sub_and_fetch), 5896 BUILTIN_ROW(__sync_and_and_fetch), 5897 BUILTIN_ROW(__sync_or_and_fetch), 5898 BUILTIN_ROW(__sync_xor_and_fetch), 5899 BUILTIN_ROW(__sync_nand_and_fetch), 5900 5901 BUILTIN_ROW(__sync_val_compare_and_swap), 5902 BUILTIN_ROW(__sync_bool_compare_and_swap), 5903 BUILTIN_ROW(__sync_lock_test_and_set), 5904 BUILTIN_ROW(__sync_lock_release), 5905 BUILTIN_ROW(__sync_swap) 5906 }; 5907 #undef BUILTIN_ROW 5908 5909 // Determine the index of the size. 5910 unsigned SizeIndex; 5911 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5912 case 1: SizeIndex = 0; break; 5913 case 2: SizeIndex = 1; break; 5914 case 4: SizeIndex = 2; break; 5915 case 8: SizeIndex = 3; break; 5916 case 16: SizeIndex = 4; break; 5917 default: 5918 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5919 << FirstArg->getType() << FirstArg->getSourceRange(); 5920 return ExprError(); 5921 } 5922 5923 // Each of these builtins has one pointer argument, followed by some number of 5924 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5925 // that we ignore. Find out which row of BuiltinIndices to read from as well 5926 // as the number of fixed args. 5927 unsigned BuiltinID = FDecl->getBuiltinID(); 5928 unsigned BuiltinIndex, NumFixed = 1; 5929 bool WarnAboutSemanticsChange = false; 5930 switch (BuiltinID) { 5931 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5932 case Builtin::BI__sync_fetch_and_add: 5933 case Builtin::BI__sync_fetch_and_add_1: 5934 case Builtin::BI__sync_fetch_and_add_2: 5935 case Builtin::BI__sync_fetch_and_add_4: 5936 case Builtin::BI__sync_fetch_and_add_8: 5937 case Builtin::BI__sync_fetch_and_add_16: 5938 BuiltinIndex = 0; 5939 break; 5940 5941 case Builtin::BI__sync_fetch_and_sub: 5942 case Builtin::BI__sync_fetch_and_sub_1: 5943 case Builtin::BI__sync_fetch_and_sub_2: 5944 case Builtin::BI__sync_fetch_and_sub_4: 5945 case Builtin::BI__sync_fetch_and_sub_8: 5946 case Builtin::BI__sync_fetch_and_sub_16: 5947 BuiltinIndex = 1; 5948 break; 5949 5950 case Builtin::BI__sync_fetch_and_or: 5951 case Builtin::BI__sync_fetch_and_or_1: 5952 case Builtin::BI__sync_fetch_and_or_2: 5953 case Builtin::BI__sync_fetch_and_or_4: 5954 case Builtin::BI__sync_fetch_and_or_8: 5955 case Builtin::BI__sync_fetch_and_or_16: 5956 BuiltinIndex = 2; 5957 break; 5958 5959 case Builtin::BI__sync_fetch_and_and: 5960 case Builtin::BI__sync_fetch_and_and_1: 5961 case Builtin::BI__sync_fetch_and_and_2: 5962 case Builtin::BI__sync_fetch_and_and_4: 5963 case Builtin::BI__sync_fetch_and_and_8: 5964 case Builtin::BI__sync_fetch_and_and_16: 5965 BuiltinIndex = 3; 5966 break; 5967 5968 case Builtin::BI__sync_fetch_and_xor: 5969 case Builtin::BI__sync_fetch_and_xor_1: 5970 case Builtin::BI__sync_fetch_and_xor_2: 5971 case Builtin::BI__sync_fetch_and_xor_4: 5972 case Builtin::BI__sync_fetch_and_xor_8: 5973 case Builtin::BI__sync_fetch_and_xor_16: 5974 BuiltinIndex = 4; 5975 break; 5976 5977 case Builtin::BI__sync_fetch_and_nand: 5978 case Builtin::BI__sync_fetch_and_nand_1: 5979 case Builtin::BI__sync_fetch_and_nand_2: 5980 case Builtin::BI__sync_fetch_and_nand_4: 5981 case Builtin::BI__sync_fetch_and_nand_8: 5982 case Builtin::BI__sync_fetch_and_nand_16: 5983 BuiltinIndex = 5; 5984 WarnAboutSemanticsChange = true; 5985 break; 5986 5987 case Builtin::BI__sync_add_and_fetch: 5988 case Builtin::BI__sync_add_and_fetch_1: 5989 case Builtin::BI__sync_add_and_fetch_2: 5990 case Builtin::BI__sync_add_and_fetch_4: 5991 case Builtin::BI__sync_add_and_fetch_8: 5992 case Builtin::BI__sync_add_and_fetch_16: 5993 BuiltinIndex = 6; 5994 break; 5995 5996 case Builtin::BI__sync_sub_and_fetch: 5997 case Builtin::BI__sync_sub_and_fetch_1: 5998 case Builtin::BI__sync_sub_and_fetch_2: 5999 case Builtin::BI__sync_sub_and_fetch_4: 6000 case Builtin::BI__sync_sub_and_fetch_8: 6001 case Builtin::BI__sync_sub_and_fetch_16: 6002 BuiltinIndex = 7; 6003 break; 6004 6005 case Builtin::BI__sync_and_and_fetch: 6006 case Builtin::BI__sync_and_and_fetch_1: 6007 case Builtin::BI__sync_and_and_fetch_2: 6008 case Builtin::BI__sync_and_and_fetch_4: 6009 case Builtin::BI__sync_and_and_fetch_8: 6010 case Builtin::BI__sync_and_and_fetch_16: 6011 BuiltinIndex = 8; 6012 break; 6013 6014 case Builtin::BI__sync_or_and_fetch: 6015 case Builtin::BI__sync_or_and_fetch_1: 6016 case Builtin::BI__sync_or_and_fetch_2: 6017 case Builtin::BI__sync_or_and_fetch_4: 6018 case Builtin::BI__sync_or_and_fetch_8: 6019 case Builtin::BI__sync_or_and_fetch_16: 6020 BuiltinIndex = 9; 6021 break; 6022 6023 case Builtin::BI__sync_xor_and_fetch: 6024 case Builtin::BI__sync_xor_and_fetch_1: 6025 case Builtin::BI__sync_xor_and_fetch_2: 6026 case Builtin::BI__sync_xor_and_fetch_4: 6027 case Builtin::BI__sync_xor_and_fetch_8: 6028 case Builtin::BI__sync_xor_and_fetch_16: 6029 BuiltinIndex = 10; 6030 break; 6031 6032 case Builtin::BI__sync_nand_and_fetch: 6033 case Builtin::BI__sync_nand_and_fetch_1: 6034 case Builtin::BI__sync_nand_and_fetch_2: 6035 case Builtin::BI__sync_nand_and_fetch_4: 6036 case Builtin::BI__sync_nand_and_fetch_8: 6037 case Builtin::BI__sync_nand_and_fetch_16: 6038 BuiltinIndex = 11; 6039 WarnAboutSemanticsChange = true; 6040 break; 6041 6042 case Builtin::BI__sync_val_compare_and_swap: 6043 case Builtin::BI__sync_val_compare_and_swap_1: 6044 case Builtin::BI__sync_val_compare_and_swap_2: 6045 case Builtin::BI__sync_val_compare_and_swap_4: 6046 case Builtin::BI__sync_val_compare_and_swap_8: 6047 case Builtin::BI__sync_val_compare_and_swap_16: 6048 BuiltinIndex = 12; 6049 NumFixed = 2; 6050 break; 6051 6052 case Builtin::BI__sync_bool_compare_and_swap: 6053 case Builtin::BI__sync_bool_compare_and_swap_1: 6054 case Builtin::BI__sync_bool_compare_and_swap_2: 6055 case Builtin::BI__sync_bool_compare_and_swap_4: 6056 case Builtin::BI__sync_bool_compare_and_swap_8: 6057 case Builtin::BI__sync_bool_compare_and_swap_16: 6058 BuiltinIndex = 13; 6059 NumFixed = 2; 6060 ResultType = Context.BoolTy; 6061 break; 6062 6063 case Builtin::BI__sync_lock_test_and_set: 6064 case Builtin::BI__sync_lock_test_and_set_1: 6065 case Builtin::BI__sync_lock_test_and_set_2: 6066 case Builtin::BI__sync_lock_test_and_set_4: 6067 case Builtin::BI__sync_lock_test_and_set_8: 6068 case Builtin::BI__sync_lock_test_and_set_16: 6069 BuiltinIndex = 14; 6070 break; 6071 6072 case Builtin::BI__sync_lock_release: 6073 case Builtin::BI__sync_lock_release_1: 6074 case Builtin::BI__sync_lock_release_2: 6075 case Builtin::BI__sync_lock_release_4: 6076 case Builtin::BI__sync_lock_release_8: 6077 case Builtin::BI__sync_lock_release_16: 6078 BuiltinIndex = 15; 6079 NumFixed = 0; 6080 ResultType = Context.VoidTy; 6081 break; 6082 6083 case Builtin::BI__sync_swap: 6084 case Builtin::BI__sync_swap_1: 6085 case Builtin::BI__sync_swap_2: 6086 case Builtin::BI__sync_swap_4: 6087 case Builtin::BI__sync_swap_8: 6088 case Builtin::BI__sync_swap_16: 6089 BuiltinIndex = 16; 6090 break; 6091 } 6092 6093 // Now that we know how many fixed arguments we expect, first check that we 6094 // have at least that many. 6095 if (TheCall->getNumArgs() < 1+NumFixed) { 6096 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6097 << 0 << 1 + NumFixed << TheCall->getNumArgs() 6098 << Callee->getSourceRange(); 6099 return ExprError(); 6100 } 6101 6102 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 6103 << Callee->getSourceRange(); 6104 6105 if (WarnAboutSemanticsChange) { 6106 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 6107 << Callee->getSourceRange(); 6108 } 6109 6110 // Get the decl for the concrete builtin from this, we can tell what the 6111 // concrete integer type we should convert to is. 6112 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 6113 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 6114 FunctionDecl *NewBuiltinDecl; 6115 if (NewBuiltinID == BuiltinID) 6116 NewBuiltinDecl = FDecl; 6117 else { 6118 // Perform builtin lookup to avoid redeclaring it. 6119 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 6120 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 6121 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 6122 assert(Res.getFoundDecl()); 6123 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 6124 if (!NewBuiltinDecl) 6125 return ExprError(); 6126 } 6127 6128 // The first argument --- the pointer --- has a fixed type; we 6129 // deduce the types of the rest of the arguments accordingly. Walk 6130 // the remaining arguments, converting them to the deduced value type. 6131 for (unsigned i = 0; i != NumFixed; ++i) { 6132 ExprResult Arg = TheCall->getArg(i+1); 6133 6134 // GCC does an implicit conversion to the pointer or integer ValType. This 6135 // can fail in some cases (1i -> int**), check for this error case now. 6136 // Initialize the argument. 6137 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6138 ValType, /*consume*/ false); 6139 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6140 if (Arg.isInvalid()) 6141 return ExprError(); 6142 6143 // Okay, we have something that *can* be converted to the right type. Check 6144 // to see if there is a potentially weird extension going on here. This can 6145 // happen when you do an atomic operation on something like an char* and 6146 // pass in 42. The 42 gets converted to char. This is even more strange 6147 // for things like 45.123 -> char, etc. 6148 // FIXME: Do this check. 6149 TheCall->setArg(i+1, Arg.get()); 6150 } 6151 6152 // Create a new DeclRefExpr to refer to the new decl. 6153 DeclRefExpr *NewDRE = DeclRefExpr::Create( 6154 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 6155 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 6156 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 6157 6158 // Set the callee in the CallExpr. 6159 // FIXME: This loses syntactic information. 6160 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 6161 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 6162 CK_BuiltinFnToFnPtr); 6163 TheCall->setCallee(PromotedCall.get()); 6164 6165 // Change the result type of the call to match the original value type. This 6166 // is arbitrary, but the codegen for these builtins ins design to handle it 6167 // gracefully. 6168 TheCall->setType(ResultType); 6169 6170 // Prohibit use of _ExtInt with atomic builtins. 6171 // The arguments would have already been converted to the first argument's 6172 // type, so only need to check the first argument. 6173 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 6174 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 6175 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 6176 return ExprError(); 6177 } 6178 6179 return TheCallResult; 6180 } 6181 6182 /// SemaBuiltinNontemporalOverloaded - We have a call to 6183 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 6184 /// overloaded function based on the pointer type of its last argument. 6185 /// 6186 /// This function goes through and does final semantic checking for these 6187 /// builtins. 6188 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 6189 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 6190 DeclRefExpr *DRE = 6191 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6192 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6193 unsigned BuiltinID = FDecl->getBuiltinID(); 6194 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 6195 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 6196 "Unexpected nontemporal load/store builtin!"); 6197 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 6198 unsigned numArgs = isStore ? 2 : 1; 6199 6200 // Ensure that we have the proper number of arguments. 6201 if (checkArgCount(*this, TheCall, numArgs)) 6202 return ExprError(); 6203 6204 // Inspect the last argument of the nontemporal builtin. This should always 6205 // be a pointer type, from which we imply the type of the memory access. 6206 // Because it is a pointer type, we don't have to worry about any implicit 6207 // casts here. 6208 Expr *PointerArg = TheCall->getArg(numArgs - 1); 6209 ExprResult PointerArgResult = 6210 DefaultFunctionArrayLvalueConversion(PointerArg); 6211 6212 if (PointerArgResult.isInvalid()) 6213 return ExprError(); 6214 PointerArg = PointerArgResult.get(); 6215 TheCall->setArg(numArgs - 1, PointerArg); 6216 6217 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 6218 if (!pointerType) { 6219 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 6220 << PointerArg->getType() << PointerArg->getSourceRange(); 6221 return ExprError(); 6222 } 6223 6224 QualType ValType = pointerType->getPointeeType(); 6225 6226 // Strip any qualifiers off ValType. 6227 ValType = ValType.getUnqualifiedType(); 6228 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6229 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 6230 !ValType->isVectorType()) { 6231 Diag(DRE->getBeginLoc(), 6232 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 6233 << PointerArg->getType() << PointerArg->getSourceRange(); 6234 return ExprError(); 6235 } 6236 6237 if (!isStore) { 6238 TheCall->setType(ValType); 6239 return TheCallResult; 6240 } 6241 6242 ExprResult ValArg = TheCall->getArg(0); 6243 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6244 Context, ValType, /*consume*/ false); 6245 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 6246 if (ValArg.isInvalid()) 6247 return ExprError(); 6248 6249 TheCall->setArg(0, ValArg.get()); 6250 TheCall->setType(Context.VoidTy); 6251 return TheCallResult; 6252 } 6253 6254 /// CheckObjCString - Checks that the argument to the builtin 6255 /// CFString constructor is correct 6256 /// Note: It might also make sense to do the UTF-16 conversion here (would 6257 /// simplify the backend). 6258 bool Sema::CheckObjCString(Expr *Arg) { 6259 Arg = Arg->IgnoreParenCasts(); 6260 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 6261 6262 if (!Literal || !Literal->isAscii()) { 6263 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 6264 << Arg->getSourceRange(); 6265 return true; 6266 } 6267 6268 if (Literal->containsNonAsciiOrNull()) { 6269 StringRef String = Literal->getString(); 6270 unsigned NumBytes = String.size(); 6271 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6272 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6273 llvm::UTF16 *ToPtr = &ToBuf[0]; 6274 6275 llvm::ConversionResult Result = 6276 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6277 ToPtr + NumBytes, llvm::strictConversion); 6278 // Check for conversion failure. 6279 if (Result != llvm::conversionOK) 6280 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6281 << Arg->getSourceRange(); 6282 } 6283 return false; 6284 } 6285 6286 /// CheckObjCString - Checks that the format string argument to the os_log() 6287 /// and os_trace() functions is correct, and converts it to const char *. 6288 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6289 Arg = Arg->IgnoreParenCasts(); 6290 auto *Literal = dyn_cast<StringLiteral>(Arg); 6291 if (!Literal) { 6292 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6293 Literal = ObjcLiteral->getString(); 6294 } 6295 } 6296 6297 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6298 return ExprError( 6299 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 6300 << Arg->getSourceRange()); 6301 } 6302 6303 ExprResult Result(Literal); 6304 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 6305 InitializedEntity Entity = 6306 InitializedEntity::InitializeParameter(Context, ResultTy, false); 6307 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 6308 return Result; 6309 } 6310 6311 /// Check that the user is calling the appropriate va_start builtin for the 6312 /// target and calling convention. 6313 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 6314 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 6315 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 6316 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 6317 TT.getArch() == llvm::Triple::aarch64_32); 6318 bool IsWindows = TT.isOSWindows(); 6319 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 6320 if (IsX64 || IsAArch64) { 6321 CallingConv CC = CC_C; 6322 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 6323 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 6324 if (IsMSVAStart) { 6325 // Don't allow this in System V ABI functions. 6326 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 6327 return S.Diag(Fn->getBeginLoc(), 6328 diag::err_ms_va_start_used_in_sysv_function); 6329 } else { 6330 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 6331 // On x64 Windows, don't allow this in System V ABI functions. 6332 // (Yes, that means there's no corresponding way to support variadic 6333 // System V ABI functions on Windows.) 6334 if ((IsWindows && CC == CC_X86_64SysV) || 6335 (!IsWindows && CC == CC_Win64)) 6336 return S.Diag(Fn->getBeginLoc(), 6337 diag::err_va_start_used_in_wrong_abi_function) 6338 << !IsWindows; 6339 } 6340 return false; 6341 } 6342 6343 if (IsMSVAStart) 6344 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 6345 return false; 6346 } 6347 6348 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 6349 ParmVarDecl **LastParam = nullptr) { 6350 // Determine whether the current function, block, or obj-c method is variadic 6351 // and get its parameter list. 6352 bool IsVariadic = false; 6353 ArrayRef<ParmVarDecl *> Params; 6354 DeclContext *Caller = S.CurContext; 6355 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 6356 IsVariadic = Block->isVariadic(); 6357 Params = Block->parameters(); 6358 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 6359 IsVariadic = FD->isVariadic(); 6360 Params = FD->parameters(); 6361 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 6362 IsVariadic = MD->isVariadic(); 6363 // FIXME: This isn't correct for methods (results in bogus warning). 6364 Params = MD->parameters(); 6365 } else if (isa<CapturedDecl>(Caller)) { 6366 // We don't support va_start in a CapturedDecl. 6367 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 6368 return true; 6369 } else { 6370 // This must be some other declcontext that parses exprs. 6371 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 6372 return true; 6373 } 6374 6375 if (!IsVariadic) { 6376 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 6377 return true; 6378 } 6379 6380 if (LastParam) 6381 *LastParam = Params.empty() ? nullptr : Params.back(); 6382 6383 return false; 6384 } 6385 6386 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 6387 /// for validity. Emit an error and return true on failure; return false 6388 /// on success. 6389 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 6390 Expr *Fn = TheCall->getCallee(); 6391 6392 if (checkVAStartABI(*this, BuiltinID, Fn)) 6393 return true; 6394 6395 if (checkArgCount(*this, TheCall, 2)) 6396 return true; 6397 6398 // Type-check the first argument normally. 6399 if (checkBuiltinArgument(*this, TheCall, 0)) 6400 return true; 6401 6402 // Check that the current function is variadic, and get its last parameter. 6403 ParmVarDecl *LastParam; 6404 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6405 return true; 6406 6407 // Verify that the second argument to the builtin is the last argument of the 6408 // current function or method. 6409 bool SecondArgIsLastNamedArgument = false; 6410 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6411 6412 // These are valid if SecondArgIsLastNamedArgument is false after the next 6413 // block. 6414 QualType Type; 6415 SourceLocation ParamLoc; 6416 bool IsCRegister = false; 6417 6418 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6419 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6420 SecondArgIsLastNamedArgument = PV == LastParam; 6421 6422 Type = PV->getType(); 6423 ParamLoc = PV->getLocation(); 6424 IsCRegister = 6425 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6426 } 6427 } 6428 6429 if (!SecondArgIsLastNamedArgument) 6430 Diag(TheCall->getArg(1)->getBeginLoc(), 6431 diag::warn_second_arg_of_va_start_not_last_named_param); 6432 else if (IsCRegister || Type->isReferenceType() || 6433 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6434 // Promotable integers are UB, but enumerations need a bit of 6435 // extra checking to see what their promotable type actually is. 6436 if (!Type->isPromotableIntegerType()) 6437 return false; 6438 if (!Type->isEnumeralType()) 6439 return true; 6440 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6441 return !(ED && 6442 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6443 }()) { 6444 unsigned Reason = 0; 6445 if (Type->isReferenceType()) Reason = 1; 6446 else if (IsCRegister) Reason = 2; 6447 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6448 Diag(ParamLoc, diag::note_parameter_type) << Type; 6449 } 6450 6451 TheCall->setType(Context.VoidTy); 6452 return false; 6453 } 6454 6455 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6456 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool { 6457 const LangOptions &LO = getLangOpts(); 6458 6459 if (LO.CPlusPlus) 6460 return Arg->getType() 6461 .getCanonicalType() 6462 .getTypePtr() 6463 ->getPointeeType() 6464 .withoutLocalFastQualifiers() == Context.CharTy; 6465 6466 // In C, allow aliasing through `char *`, this is required for AArch64 at 6467 // least. 6468 return true; 6469 }; 6470 6471 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6472 // const char *named_addr); 6473 6474 Expr *Func = Call->getCallee(); 6475 6476 if (Call->getNumArgs() < 3) 6477 return Diag(Call->getEndLoc(), 6478 diag::err_typecheck_call_too_few_args_at_least) 6479 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6480 6481 // Type-check the first argument normally. 6482 if (checkBuiltinArgument(*this, Call, 0)) 6483 return true; 6484 6485 // Check that the current function is variadic. 6486 if (checkVAStartIsInVariadicFunction(*this, Func)) 6487 return true; 6488 6489 // __va_start on Windows does not validate the parameter qualifiers 6490 6491 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6492 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6493 6494 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6495 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6496 6497 const QualType &ConstCharPtrTy = 6498 Context.getPointerType(Context.CharTy.withConst()); 6499 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1)) 6500 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6501 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6502 << 0 /* qualifier difference */ 6503 << 3 /* parameter mismatch */ 6504 << 2 << Arg1->getType() << ConstCharPtrTy; 6505 6506 const QualType SizeTy = Context.getSizeType(); 6507 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6508 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6509 << Arg2->getType() << SizeTy << 1 /* different class */ 6510 << 0 /* qualifier difference */ 6511 << 3 /* parameter mismatch */ 6512 << 3 << Arg2->getType() << SizeTy; 6513 6514 return false; 6515 } 6516 6517 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6518 /// friends. This is declared to take (...), so we have to check everything. 6519 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6520 if (checkArgCount(*this, TheCall, 2)) 6521 return true; 6522 6523 ExprResult OrigArg0 = TheCall->getArg(0); 6524 ExprResult OrigArg1 = TheCall->getArg(1); 6525 6526 // Do standard promotions between the two arguments, returning their common 6527 // type. 6528 QualType Res = UsualArithmeticConversions( 6529 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6530 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6531 return true; 6532 6533 // Make sure any conversions are pushed back into the call; this is 6534 // type safe since unordered compare builtins are declared as "_Bool 6535 // foo(...)". 6536 TheCall->setArg(0, OrigArg0.get()); 6537 TheCall->setArg(1, OrigArg1.get()); 6538 6539 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6540 return false; 6541 6542 // If the common type isn't a real floating type, then the arguments were 6543 // invalid for this operation. 6544 if (Res.isNull() || !Res->isRealFloatingType()) 6545 return Diag(OrigArg0.get()->getBeginLoc(), 6546 diag::err_typecheck_call_invalid_ordered_compare) 6547 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6548 << SourceRange(OrigArg0.get()->getBeginLoc(), 6549 OrigArg1.get()->getEndLoc()); 6550 6551 return false; 6552 } 6553 6554 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6555 /// __builtin_isnan and friends. This is declared to take (...), so we have 6556 /// to check everything. We expect the last argument to be a floating point 6557 /// value. 6558 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6559 if (checkArgCount(*this, TheCall, NumArgs)) 6560 return true; 6561 6562 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6563 // on all preceding parameters just being int. Try all of those. 6564 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6565 Expr *Arg = TheCall->getArg(i); 6566 6567 if (Arg->isTypeDependent()) 6568 return false; 6569 6570 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6571 6572 if (Res.isInvalid()) 6573 return true; 6574 TheCall->setArg(i, Res.get()); 6575 } 6576 6577 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6578 6579 if (OrigArg->isTypeDependent()) 6580 return false; 6581 6582 // Usual Unary Conversions will convert half to float, which we want for 6583 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6584 // type how it is, but do normal L->Rvalue conversions. 6585 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6586 OrigArg = UsualUnaryConversions(OrigArg).get(); 6587 else 6588 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6589 TheCall->setArg(NumArgs - 1, OrigArg); 6590 6591 // This operation requires a non-_Complex floating-point number. 6592 if (!OrigArg->getType()->isRealFloatingType()) 6593 return Diag(OrigArg->getBeginLoc(), 6594 diag::err_typecheck_call_invalid_unary_fp) 6595 << OrigArg->getType() << OrigArg->getSourceRange(); 6596 6597 return false; 6598 } 6599 6600 /// Perform semantic analysis for a call to __builtin_complex. 6601 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6602 if (checkArgCount(*this, TheCall, 2)) 6603 return true; 6604 6605 bool Dependent = false; 6606 for (unsigned I = 0; I != 2; ++I) { 6607 Expr *Arg = TheCall->getArg(I); 6608 QualType T = Arg->getType(); 6609 if (T->isDependentType()) { 6610 Dependent = true; 6611 continue; 6612 } 6613 6614 // Despite supporting _Complex int, GCC requires a real floating point type 6615 // for the operands of __builtin_complex. 6616 if (!T->isRealFloatingType()) { 6617 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6618 << Arg->getType() << Arg->getSourceRange(); 6619 } 6620 6621 ExprResult Converted = DefaultLvalueConversion(Arg); 6622 if (Converted.isInvalid()) 6623 return true; 6624 TheCall->setArg(I, Converted.get()); 6625 } 6626 6627 if (Dependent) { 6628 TheCall->setType(Context.DependentTy); 6629 return false; 6630 } 6631 6632 Expr *Real = TheCall->getArg(0); 6633 Expr *Imag = TheCall->getArg(1); 6634 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6635 return Diag(Real->getBeginLoc(), 6636 diag::err_typecheck_call_different_arg_types) 6637 << Real->getType() << Imag->getType() 6638 << Real->getSourceRange() << Imag->getSourceRange(); 6639 } 6640 6641 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6642 // don't allow this builtin to form those types either. 6643 // FIXME: Should we allow these types? 6644 if (Real->getType()->isFloat16Type()) 6645 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6646 << "_Float16"; 6647 if (Real->getType()->isHalfType()) 6648 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6649 << "half"; 6650 6651 TheCall->setType(Context.getComplexType(Real->getType())); 6652 return false; 6653 } 6654 6655 // Customized Sema Checking for VSX builtins that have the following signature: 6656 // vector [...] builtinName(vector [...], vector [...], const int); 6657 // Which takes the same type of vectors (any legal vector type) for the first 6658 // two arguments and takes compile time constant for the third argument. 6659 // Example builtins are : 6660 // vector double vec_xxpermdi(vector double, vector double, int); 6661 // vector short vec_xxsldwi(vector short, vector short, int); 6662 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6663 unsigned ExpectedNumArgs = 3; 6664 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6665 return true; 6666 6667 // Check the third argument is a compile time constant 6668 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6669 return Diag(TheCall->getBeginLoc(), 6670 diag::err_vsx_builtin_nonconstant_argument) 6671 << 3 /* argument index */ << TheCall->getDirectCallee() 6672 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6673 TheCall->getArg(2)->getEndLoc()); 6674 6675 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6676 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6677 6678 // Check the type of argument 1 and argument 2 are vectors. 6679 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6680 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6681 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6682 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6683 << TheCall->getDirectCallee() 6684 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6685 TheCall->getArg(1)->getEndLoc()); 6686 } 6687 6688 // Check the first two arguments are the same type. 6689 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6690 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6691 << TheCall->getDirectCallee() 6692 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6693 TheCall->getArg(1)->getEndLoc()); 6694 } 6695 6696 // When default clang type checking is turned off and the customized type 6697 // checking is used, the returning type of the function must be explicitly 6698 // set. Otherwise it is _Bool by default. 6699 TheCall->setType(Arg1Ty); 6700 6701 return false; 6702 } 6703 6704 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6705 // This is declared to take (...), so we have to check everything. 6706 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6707 if (TheCall->getNumArgs() < 2) 6708 return ExprError(Diag(TheCall->getEndLoc(), 6709 diag::err_typecheck_call_too_few_args_at_least) 6710 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6711 << TheCall->getSourceRange()); 6712 6713 // Determine which of the following types of shufflevector we're checking: 6714 // 1) unary, vector mask: (lhs, mask) 6715 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6716 QualType resType = TheCall->getArg(0)->getType(); 6717 unsigned numElements = 0; 6718 6719 if (!TheCall->getArg(0)->isTypeDependent() && 6720 !TheCall->getArg(1)->isTypeDependent()) { 6721 QualType LHSType = TheCall->getArg(0)->getType(); 6722 QualType RHSType = TheCall->getArg(1)->getType(); 6723 6724 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6725 return ExprError( 6726 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6727 << TheCall->getDirectCallee() 6728 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6729 TheCall->getArg(1)->getEndLoc())); 6730 6731 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6732 unsigned numResElements = TheCall->getNumArgs() - 2; 6733 6734 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6735 // with mask. If so, verify that RHS is an integer vector type with the 6736 // same number of elts as lhs. 6737 if (TheCall->getNumArgs() == 2) { 6738 if (!RHSType->hasIntegerRepresentation() || 6739 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6740 return ExprError(Diag(TheCall->getBeginLoc(), 6741 diag::err_vec_builtin_incompatible_vector) 6742 << TheCall->getDirectCallee() 6743 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6744 TheCall->getArg(1)->getEndLoc())); 6745 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6746 return ExprError(Diag(TheCall->getBeginLoc(), 6747 diag::err_vec_builtin_incompatible_vector) 6748 << TheCall->getDirectCallee() 6749 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6750 TheCall->getArg(1)->getEndLoc())); 6751 } else if (numElements != numResElements) { 6752 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6753 resType = Context.getVectorType(eltType, numResElements, 6754 VectorType::GenericVector); 6755 } 6756 } 6757 6758 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6759 if (TheCall->getArg(i)->isTypeDependent() || 6760 TheCall->getArg(i)->isValueDependent()) 6761 continue; 6762 6763 Optional<llvm::APSInt> Result; 6764 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6765 return ExprError(Diag(TheCall->getBeginLoc(), 6766 diag::err_shufflevector_nonconstant_argument) 6767 << TheCall->getArg(i)->getSourceRange()); 6768 6769 // Allow -1 which will be translated to undef in the IR. 6770 if (Result->isSigned() && Result->isAllOnes()) 6771 continue; 6772 6773 if (Result->getActiveBits() > 64 || 6774 Result->getZExtValue() >= numElements * 2) 6775 return ExprError(Diag(TheCall->getBeginLoc(), 6776 diag::err_shufflevector_argument_too_large) 6777 << TheCall->getArg(i)->getSourceRange()); 6778 } 6779 6780 SmallVector<Expr*, 32> exprs; 6781 6782 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6783 exprs.push_back(TheCall->getArg(i)); 6784 TheCall->setArg(i, nullptr); 6785 } 6786 6787 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6788 TheCall->getCallee()->getBeginLoc(), 6789 TheCall->getRParenLoc()); 6790 } 6791 6792 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6793 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6794 SourceLocation BuiltinLoc, 6795 SourceLocation RParenLoc) { 6796 ExprValueKind VK = VK_PRValue; 6797 ExprObjectKind OK = OK_Ordinary; 6798 QualType DstTy = TInfo->getType(); 6799 QualType SrcTy = E->getType(); 6800 6801 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6802 return ExprError(Diag(BuiltinLoc, 6803 diag::err_convertvector_non_vector) 6804 << E->getSourceRange()); 6805 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6806 return ExprError(Diag(BuiltinLoc, 6807 diag::err_convertvector_non_vector_type)); 6808 6809 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6810 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6811 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6812 if (SrcElts != DstElts) 6813 return ExprError(Diag(BuiltinLoc, 6814 diag::err_convertvector_incompatible_vector) 6815 << E->getSourceRange()); 6816 } 6817 6818 return new (Context) 6819 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6820 } 6821 6822 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6823 // This is declared to take (const void*, ...) and can take two 6824 // optional constant int args. 6825 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6826 unsigned NumArgs = TheCall->getNumArgs(); 6827 6828 if (NumArgs > 3) 6829 return Diag(TheCall->getEndLoc(), 6830 diag::err_typecheck_call_too_many_args_at_most) 6831 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6832 6833 // Argument 0 is checked for us and the remaining arguments must be 6834 // constant integers. 6835 for (unsigned i = 1; i != NumArgs; ++i) 6836 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6837 return true; 6838 6839 return false; 6840 } 6841 6842 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 6843 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 6844 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 6845 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 6846 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6847 if (checkArgCount(*this, TheCall, 1)) 6848 return true; 6849 Expr *Arg = TheCall->getArg(0); 6850 if (Arg->isInstantiationDependent()) 6851 return false; 6852 6853 QualType ArgTy = Arg->getType(); 6854 if (!ArgTy->hasFloatingRepresentation()) 6855 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 6856 << ArgTy; 6857 if (Arg->isLValue()) { 6858 ExprResult FirstArg = DefaultLvalueConversion(Arg); 6859 TheCall->setArg(0, FirstArg.get()); 6860 } 6861 TheCall->setType(TheCall->getArg(0)->getType()); 6862 return false; 6863 } 6864 6865 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6866 // __assume does not evaluate its arguments, and should warn if its argument 6867 // has side effects. 6868 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6869 Expr *Arg = TheCall->getArg(0); 6870 if (Arg->isInstantiationDependent()) return false; 6871 6872 if (Arg->HasSideEffects(Context)) 6873 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6874 << Arg->getSourceRange() 6875 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6876 6877 return false; 6878 } 6879 6880 /// Handle __builtin_alloca_with_align. This is declared 6881 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6882 /// than 8. 6883 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6884 // The alignment must be a constant integer. 6885 Expr *Arg = TheCall->getArg(1); 6886 6887 // We can't check the value of a dependent argument. 6888 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6889 if (const auto *UE = 6890 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6891 if (UE->getKind() == UETT_AlignOf || 6892 UE->getKind() == UETT_PreferredAlignOf) 6893 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6894 << Arg->getSourceRange(); 6895 6896 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6897 6898 if (!Result.isPowerOf2()) 6899 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6900 << Arg->getSourceRange(); 6901 6902 if (Result < Context.getCharWidth()) 6903 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6904 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6905 6906 if (Result > std::numeric_limits<int32_t>::max()) 6907 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6908 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6909 } 6910 6911 return false; 6912 } 6913 6914 /// Handle __builtin_assume_aligned. This is declared 6915 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6916 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6917 unsigned NumArgs = TheCall->getNumArgs(); 6918 6919 if (NumArgs > 3) 6920 return Diag(TheCall->getEndLoc(), 6921 diag::err_typecheck_call_too_many_args_at_most) 6922 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6923 6924 // The alignment must be a constant integer. 6925 Expr *Arg = TheCall->getArg(1); 6926 6927 // We can't check the value of a dependent argument. 6928 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6929 llvm::APSInt Result; 6930 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6931 return true; 6932 6933 if (!Result.isPowerOf2()) 6934 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6935 << Arg->getSourceRange(); 6936 6937 if (Result > Sema::MaximumAlignment) 6938 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6939 << Arg->getSourceRange() << Sema::MaximumAlignment; 6940 } 6941 6942 if (NumArgs > 2) { 6943 ExprResult Arg(TheCall->getArg(2)); 6944 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6945 Context.getSizeType(), false); 6946 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6947 if (Arg.isInvalid()) return true; 6948 TheCall->setArg(2, Arg.get()); 6949 } 6950 6951 return false; 6952 } 6953 6954 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6955 unsigned BuiltinID = 6956 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6957 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6958 6959 unsigned NumArgs = TheCall->getNumArgs(); 6960 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6961 if (NumArgs < NumRequiredArgs) { 6962 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6963 << 0 /* function call */ << NumRequiredArgs << NumArgs 6964 << TheCall->getSourceRange(); 6965 } 6966 if (NumArgs >= NumRequiredArgs + 0x100) { 6967 return Diag(TheCall->getEndLoc(), 6968 diag::err_typecheck_call_too_many_args_at_most) 6969 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6970 << TheCall->getSourceRange(); 6971 } 6972 unsigned i = 0; 6973 6974 // For formatting call, check buffer arg. 6975 if (!IsSizeCall) { 6976 ExprResult Arg(TheCall->getArg(i)); 6977 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6978 Context, Context.VoidPtrTy, false); 6979 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6980 if (Arg.isInvalid()) 6981 return true; 6982 TheCall->setArg(i, Arg.get()); 6983 i++; 6984 } 6985 6986 // Check string literal arg. 6987 unsigned FormatIdx = i; 6988 { 6989 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6990 if (Arg.isInvalid()) 6991 return true; 6992 TheCall->setArg(i, Arg.get()); 6993 i++; 6994 } 6995 6996 // Make sure variadic args are scalar. 6997 unsigned FirstDataArg = i; 6998 while (i < NumArgs) { 6999 ExprResult Arg = DefaultVariadicArgumentPromotion( 7000 TheCall->getArg(i), VariadicFunction, nullptr); 7001 if (Arg.isInvalid()) 7002 return true; 7003 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 7004 if (ArgSize.getQuantity() >= 0x100) { 7005 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 7006 << i << (int)ArgSize.getQuantity() << 0xff 7007 << TheCall->getSourceRange(); 7008 } 7009 TheCall->setArg(i, Arg.get()); 7010 i++; 7011 } 7012 7013 // Check formatting specifiers. NOTE: We're only doing this for the non-size 7014 // call to avoid duplicate diagnostics. 7015 if (!IsSizeCall) { 7016 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 7017 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 7018 bool Success = CheckFormatArguments( 7019 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 7020 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 7021 CheckedVarArgs); 7022 if (!Success) 7023 return true; 7024 } 7025 7026 if (IsSizeCall) { 7027 TheCall->setType(Context.getSizeType()); 7028 } else { 7029 TheCall->setType(Context.VoidPtrTy); 7030 } 7031 return false; 7032 } 7033 7034 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 7035 /// TheCall is a constant expression. 7036 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 7037 llvm::APSInt &Result) { 7038 Expr *Arg = TheCall->getArg(ArgNum); 7039 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 7040 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 7041 7042 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 7043 7044 Optional<llvm::APSInt> R; 7045 if (!(R = Arg->getIntegerConstantExpr(Context))) 7046 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 7047 << FDecl->getDeclName() << Arg->getSourceRange(); 7048 Result = *R; 7049 return false; 7050 } 7051 7052 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 7053 /// TheCall is a constant expression in the range [Low, High]. 7054 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 7055 int Low, int High, bool RangeIsError) { 7056 if (isConstantEvaluated()) 7057 return false; 7058 llvm::APSInt Result; 7059 7060 // We can't check the value of a dependent argument. 7061 Expr *Arg = TheCall->getArg(ArgNum); 7062 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7063 return false; 7064 7065 // Check constant-ness first. 7066 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7067 return true; 7068 7069 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 7070 if (RangeIsError) 7071 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 7072 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 7073 else 7074 // Defer the warning until we know if the code will be emitted so that 7075 // dead code can ignore this. 7076 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 7077 PDiag(diag::warn_argument_invalid_range) 7078 << toString(Result, 10) << Low << High 7079 << Arg->getSourceRange()); 7080 } 7081 7082 return false; 7083 } 7084 7085 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 7086 /// TheCall is a constant expression is a multiple of Num.. 7087 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 7088 unsigned Num) { 7089 llvm::APSInt Result; 7090 7091 // We can't check the value of a dependent argument. 7092 Expr *Arg = TheCall->getArg(ArgNum); 7093 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7094 return false; 7095 7096 // Check constant-ness first. 7097 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7098 return true; 7099 7100 if (Result.getSExtValue() % Num != 0) 7101 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 7102 << Num << Arg->getSourceRange(); 7103 7104 return false; 7105 } 7106 7107 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 7108 /// constant expression representing a power of 2. 7109 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 7110 llvm::APSInt Result; 7111 7112 // We can't check the value of a dependent argument. 7113 Expr *Arg = TheCall->getArg(ArgNum); 7114 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7115 return false; 7116 7117 // Check constant-ness first. 7118 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7119 return true; 7120 7121 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 7122 // and only if x is a power of 2. 7123 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 7124 return false; 7125 7126 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 7127 << Arg->getSourceRange(); 7128 } 7129 7130 static bool IsShiftedByte(llvm::APSInt Value) { 7131 if (Value.isNegative()) 7132 return false; 7133 7134 // Check if it's a shifted byte, by shifting it down 7135 while (true) { 7136 // If the value fits in the bottom byte, the check passes. 7137 if (Value < 0x100) 7138 return true; 7139 7140 // Otherwise, if the value has _any_ bits in the bottom byte, the check 7141 // fails. 7142 if ((Value & 0xFF) != 0) 7143 return false; 7144 7145 // If the bottom 8 bits are all 0, but something above that is nonzero, 7146 // then shifting the value right by 8 bits won't affect whether it's a 7147 // shifted byte or not. So do that, and go round again. 7148 Value >>= 8; 7149 } 7150 } 7151 7152 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 7153 /// a constant expression representing an arbitrary byte value shifted left by 7154 /// a multiple of 8 bits. 7155 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 7156 unsigned ArgBits) { 7157 llvm::APSInt Result; 7158 7159 // We can't check the value of a dependent argument. 7160 Expr *Arg = TheCall->getArg(ArgNum); 7161 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7162 return false; 7163 7164 // Check constant-ness first. 7165 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7166 return true; 7167 7168 // Truncate to the given size. 7169 Result = Result.getLoBits(ArgBits); 7170 Result.setIsUnsigned(true); 7171 7172 if (IsShiftedByte(Result)) 7173 return false; 7174 7175 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 7176 << Arg->getSourceRange(); 7177 } 7178 7179 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 7180 /// TheCall is a constant expression representing either a shifted byte value, 7181 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 7182 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 7183 /// Arm MVE intrinsics. 7184 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 7185 int ArgNum, 7186 unsigned ArgBits) { 7187 llvm::APSInt Result; 7188 7189 // We can't check the value of a dependent argument. 7190 Expr *Arg = TheCall->getArg(ArgNum); 7191 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7192 return false; 7193 7194 // Check constant-ness first. 7195 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7196 return true; 7197 7198 // Truncate to the given size. 7199 Result = Result.getLoBits(ArgBits); 7200 Result.setIsUnsigned(true); 7201 7202 // Check to see if it's in either of the required forms. 7203 if (IsShiftedByte(Result) || 7204 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 7205 return false; 7206 7207 return Diag(TheCall->getBeginLoc(), 7208 diag::err_argument_not_shifted_byte_or_xxff) 7209 << Arg->getSourceRange(); 7210 } 7211 7212 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 7213 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 7214 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 7215 if (checkArgCount(*this, TheCall, 2)) 7216 return true; 7217 Expr *Arg0 = TheCall->getArg(0); 7218 Expr *Arg1 = TheCall->getArg(1); 7219 7220 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7221 if (FirstArg.isInvalid()) 7222 return true; 7223 QualType FirstArgType = FirstArg.get()->getType(); 7224 if (!FirstArgType->isAnyPointerType()) 7225 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7226 << "first" << FirstArgType << Arg0->getSourceRange(); 7227 TheCall->setArg(0, FirstArg.get()); 7228 7229 ExprResult SecArg = DefaultLvalueConversion(Arg1); 7230 if (SecArg.isInvalid()) 7231 return true; 7232 QualType SecArgType = SecArg.get()->getType(); 7233 if (!SecArgType->isIntegerType()) 7234 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7235 << "second" << SecArgType << Arg1->getSourceRange(); 7236 7237 // Derive the return type from the pointer argument. 7238 TheCall->setType(FirstArgType); 7239 return false; 7240 } 7241 7242 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 7243 if (checkArgCount(*this, TheCall, 2)) 7244 return true; 7245 7246 Expr *Arg0 = TheCall->getArg(0); 7247 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7248 if (FirstArg.isInvalid()) 7249 return true; 7250 QualType FirstArgType = FirstArg.get()->getType(); 7251 if (!FirstArgType->isAnyPointerType()) 7252 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7253 << "first" << FirstArgType << Arg0->getSourceRange(); 7254 TheCall->setArg(0, FirstArg.get()); 7255 7256 // Derive the return type from the pointer argument. 7257 TheCall->setType(FirstArgType); 7258 7259 // Second arg must be an constant in range [0,15] 7260 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7261 } 7262 7263 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 7264 if (checkArgCount(*this, TheCall, 2)) 7265 return true; 7266 Expr *Arg0 = TheCall->getArg(0); 7267 Expr *Arg1 = TheCall->getArg(1); 7268 7269 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7270 if (FirstArg.isInvalid()) 7271 return true; 7272 QualType FirstArgType = FirstArg.get()->getType(); 7273 if (!FirstArgType->isAnyPointerType()) 7274 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7275 << "first" << FirstArgType << Arg0->getSourceRange(); 7276 7277 QualType SecArgType = Arg1->getType(); 7278 if (!SecArgType->isIntegerType()) 7279 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7280 << "second" << SecArgType << Arg1->getSourceRange(); 7281 TheCall->setType(Context.IntTy); 7282 return false; 7283 } 7284 7285 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7286 BuiltinID == AArch64::BI__builtin_arm_stg) { 7287 if (checkArgCount(*this, TheCall, 1)) 7288 return true; 7289 Expr *Arg0 = TheCall->getArg(0); 7290 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7291 if (FirstArg.isInvalid()) 7292 return true; 7293 7294 QualType FirstArgType = FirstArg.get()->getType(); 7295 if (!FirstArgType->isAnyPointerType()) 7296 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7297 << "first" << FirstArgType << Arg0->getSourceRange(); 7298 TheCall->setArg(0, FirstArg.get()); 7299 7300 // Derive the return type from the pointer argument. 7301 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 7302 TheCall->setType(FirstArgType); 7303 return false; 7304 } 7305 7306 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 7307 Expr *ArgA = TheCall->getArg(0); 7308 Expr *ArgB = TheCall->getArg(1); 7309 7310 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 7311 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 7312 7313 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 7314 return true; 7315 7316 QualType ArgTypeA = ArgExprA.get()->getType(); 7317 QualType ArgTypeB = ArgExprB.get()->getType(); 7318 7319 auto isNull = [&] (Expr *E) -> bool { 7320 return E->isNullPointerConstant( 7321 Context, Expr::NPC_ValueDependentIsNotNull); }; 7322 7323 // argument should be either a pointer or null 7324 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 7325 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7326 << "first" << ArgTypeA << ArgA->getSourceRange(); 7327 7328 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 7329 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7330 << "second" << ArgTypeB << ArgB->getSourceRange(); 7331 7332 // Ensure Pointee types are compatible 7333 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 7334 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 7335 QualType pointeeA = ArgTypeA->getPointeeType(); 7336 QualType pointeeB = ArgTypeB->getPointeeType(); 7337 if (!Context.typesAreCompatible( 7338 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 7339 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 7340 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 7341 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 7342 << ArgB->getSourceRange(); 7343 } 7344 } 7345 7346 // at least one argument should be pointer type 7347 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 7348 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 7349 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 7350 7351 if (isNull(ArgA)) // adopt type of the other pointer 7352 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 7353 7354 if (isNull(ArgB)) 7355 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 7356 7357 TheCall->setArg(0, ArgExprA.get()); 7358 TheCall->setArg(1, ArgExprB.get()); 7359 TheCall->setType(Context.LongLongTy); 7360 return false; 7361 } 7362 assert(false && "Unhandled ARM MTE intrinsic"); 7363 return true; 7364 } 7365 7366 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 7367 /// TheCall is an ARM/AArch64 special register string literal. 7368 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 7369 int ArgNum, unsigned ExpectedFieldNum, 7370 bool AllowName) { 7371 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 7372 BuiltinID == ARM::BI__builtin_arm_wsr64 || 7373 BuiltinID == ARM::BI__builtin_arm_rsr || 7374 BuiltinID == ARM::BI__builtin_arm_rsrp || 7375 BuiltinID == ARM::BI__builtin_arm_wsr || 7376 BuiltinID == ARM::BI__builtin_arm_wsrp; 7377 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 7378 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 7379 BuiltinID == AArch64::BI__builtin_arm_rsr || 7380 BuiltinID == AArch64::BI__builtin_arm_rsrp || 7381 BuiltinID == AArch64::BI__builtin_arm_wsr || 7382 BuiltinID == AArch64::BI__builtin_arm_wsrp; 7383 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 7384 7385 // We can't check the value of a dependent argument. 7386 Expr *Arg = TheCall->getArg(ArgNum); 7387 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7388 return false; 7389 7390 // Check if the argument is a string literal. 7391 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 7392 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 7393 << Arg->getSourceRange(); 7394 7395 // Check the type of special register given. 7396 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 7397 SmallVector<StringRef, 6> Fields; 7398 Reg.split(Fields, ":"); 7399 7400 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 7401 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7402 << Arg->getSourceRange(); 7403 7404 // If the string is the name of a register then we cannot check that it is 7405 // valid here but if the string is of one the forms described in ACLE then we 7406 // can check that the supplied fields are integers and within the valid 7407 // ranges. 7408 if (Fields.size() > 1) { 7409 bool FiveFields = Fields.size() == 5; 7410 7411 bool ValidString = true; 7412 if (IsARMBuiltin) { 7413 ValidString &= Fields[0].startswith_insensitive("cp") || 7414 Fields[0].startswith_insensitive("p"); 7415 if (ValidString) 7416 Fields[0] = Fields[0].drop_front( 7417 Fields[0].startswith_insensitive("cp") ? 2 : 1); 7418 7419 ValidString &= Fields[2].startswith_insensitive("c"); 7420 if (ValidString) 7421 Fields[2] = Fields[2].drop_front(1); 7422 7423 if (FiveFields) { 7424 ValidString &= Fields[3].startswith_insensitive("c"); 7425 if (ValidString) 7426 Fields[3] = Fields[3].drop_front(1); 7427 } 7428 } 7429 7430 SmallVector<int, 5> Ranges; 7431 if (FiveFields) 7432 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 7433 else 7434 Ranges.append({15, 7, 15}); 7435 7436 for (unsigned i=0; i<Fields.size(); ++i) { 7437 int IntField; 7438 ValidString &= !Fields[i].getAsInteger(10, IntField); 7439 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7440 } 7441 7442 if (!ValidString) 7443 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7444 << Arg->getSourceRange(); 7445 } else if (IsAArch64Builtin && Fields.size() == 1) { 7446 // If the register name is one of those that appear in the condition below 7447 // and the special register builtin being used is one of the write builtins, 7448 // then we require that the argument provided for writing to the register 7449 // is an integer constant expression. This is because it will be lowered to 7450 // an MSR (immediate) instruction, so we need to know the immediate at 7451 // compile time. 7452 if (TheCall->getNumArgs() != 2) 7453 return false; 7454 7455 std::string RegLower = Reg.lower(); 7456 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7457 RegLower != "pan" && RegLower != "uao") 7458 return false; 7459 7460 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7461 } 7462 7463 return false; 7464 } 7465 7466 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7467 /// Emit an error and return true on failure; return false on success. 7468 /// TypeStr is a string containing the type descriptor of the value returned by 7469 /// the builtin and the descriptors of the expected type of the arguments. 7470 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID, 7471 const char *TypeStr) { 7472 7473 assert((TypeStr[0] != '\0') && 7474 "Invalid types in PPC MMA builtin declaration"); 7475 7476 switch (BuiltinID) { 7477 default: 7478 // This function is called in CheckPPCBuiltinFunctionCall where the 7479 // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here 7480 // we are isolating the pair vector memop builtins that can be used with mma 7481 // off so the default case is every builtin that requires mma and paired 7482 // vector memops. 7483 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7484 diag::err_ppc_builtin_only_on_arch, "10") || 7485 SemaFeatureCheck(*this, TheCall, "mma", 7486 diag::err_ppc_builtin_only_on_arch, "10")) 7487 return true; 7488 break; 7489 case PPC::BI__builtin_vsx_lxvp: 7490 case PPC::BI__builtin_vsx_stxvp: 7491 case PPC::BI__builtin_vsx_assemble_pair: 7492 case PPC::BI__builtin_vsx_disassemble_pair: 7493 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7494 diag::err_ppc_builtin_only_on_arch, "10")) 7495 return true; 7496 break; 7497 } 7498 7499 unsigned Mask = 0; 7500 unsigned ArgNum = 0; 7501 7502 // The first type in TypeStr is the type of the value returned by the 7503 // builtin. So we first read that type and change the type of TheCall. 7504 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7505 TheCall->setType(type); 7506 7507 while (*TypeStr != '\0') { 7508 Mask = 0; 7509 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7510 if (ArgNum >= TheCall->getNumArgs()) { 7511 ArgNum++; 7512 break; 7513 } 7514 7515 Expr *Arg = TheCall->getArg(ArgNum); 7516 QualType PassedType = Arg->getType(); 7517 QualType StrippedRVType = PassedType.getCanonicalType(); 7518 7519 // Strip Restrict/Volatile qualifiers. 7520 if (StrippedRVType.isRestrictQualified() || 7521 StrippedRVType.isVolatileQualified()) 7522 StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType(); 7523 7524 // The only case where the argument type and expected type are allowed to 7525 // mismatch is if the argument type is a non-void pointer and expected type 7526 // is a void pointer. 7527 if (StrippedRVType != ExpectedType) 7528 if (!(ExpectedType->isVoidPointerType() && 7529 StrippedRVType->isPointerType())) 7530 return Diag(Arg->getBeginLoc(), 7531 diag::err_typecheck_convert_incompatible) 7532 << PassedType << ExpectedType << 1 << 0 << 0; 7533 7534 // If the value of the Mask is not 0, we have a constraint in the size of 7535 // the integer argument so here we ensure the argument is a constant that 7536 // is in the valid range. 7537 if (Mask != 0 && 7538 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7539 return true; 7540 7541 ArgNum++; 7542 } 7543 7544 // In case we exited early from the previous loop, there are other types to 7545 // read from TypeStr. So we need to read them all to ensure we have the right 7546 // number of arguments in TheCall and if it is not the case, to display a 7547 // better error message. 7548 while (*TypeStr != '\0') { 7549 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7550 ArgNum++; 7551 } 7552 if (checkArgCount(*this, TheCall, ArgNum)) 7553 return true; 7554 7555 return false; 7556 } 7557 7558 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7559 /// This checks that the target supports __builtin_longjmp and 7560 /// that val is a constant 1. 7561 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7562 if (!Context.getTargetInfo().hasSjLjLowering()) 7563 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7564 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7565 7566 Expr *Arg = TheCall->getArg(1); 7567 llvm::APSInt Result; 7568 7569 // TODO: This is less than ideal. Overload this to take a value. 7570 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7571 return true; 7572 7573 if (Result != 1) 7574 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7575 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7576 7577 return false; 7578 } 7579 7580 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7581 /// This checks that the target supports __builtin_setjmp. 7582 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7583 if (!Context.getTargetInfo().hasSjLjLowering()) 7584 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7585 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7586 return false; 7587 } 7588 7589 namespace { 7590 7591 class UncoveredArgHandler { 7592 enum { Unknown = -1, AllCovered = -2 }; 7593 7594 signed FirstUncoveredArg = Unknown; 7595 SmallVector<const Expr *, 4> DiagnosticExprs; 7596 7597 public: 7598 UncoveredArgHandler() = default; 7599 7600 bool hasUncoveredArg() const { 7601 return (FirstUncoveredArg >= 0); 7602 } 7603 7604 unsigned getUncoveredArg() const { 7605 assert(hasUncoveredArg() && "no uncovered argument"); 7606 return FirstUncoveredArg; 7607 } 7608 7609 void setAllCovered() { 7610 // A string has been found with all arguments covered, so clear out 7611 // the diagnostics. 7612 DiagnosticExprs.clear(); 7613 FirstUncoveredArg = AllCovered; 7614 } 7615 7616 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7617 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7618 7619 // Don't update if a previous string covers all arguments. 7620 if (FirstUncoveredArg == AllCovered) 7621 return; 7622 7623 // UncoveredArgHandler tracks the highest uncovered argument index 7624 // and with it all the strings that match this index. 7625 if (NewFirstUncoveredArg == FirstUncoveredArg) 7626 DiagnosticExprs.push_back(StrExpr); 7627 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7628 DiagnosticExprs.clear(); 7629 DiagnosticExprs.push_back(StrExpr); 7630 FirstUncoveredArg = NewFirstUncoveredArg; 7631 } 7632 } 7633 7634 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7635 }; 7636 7637 enum StringLiteralCheckType { 7638 SLCT_NotALiteral, 7639 SLCT_UncheckedLiteral, 7640 SLCT_CheckedLiteral 7641 }; 7642 7643 } // namespace 7644 7645 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7646 BinaryOperatorKind BinOpKind, 7647 bool AddendIsRight) { 7648 unsigned BitWidth = Offset.getBitWidth(); 7649 unsigned AddendBitWidth = Addend.getBitWidth(); 7650 // There might be negative interim results. 7651 if (Addend.isUnsigned()) { 7652 Addend = Addend.zext(++AddendBitWidth); 7653 Addend.setIsSigned(true); 7654 } 7655 // Adjust the bit width of the APSInts. 7656 if (AddendBitWidth > BitWidth) { 7657 Offset = Offset.sext(AddendBitWidth); 7658 BitWidth = AddendBitWidth; 7659 } else if (BitWidth > AddendBitWidth) { 7660 Addend = Addend.sext(BitWidth); 7661 } 7662 7663 bool Ov = false; 7664 llvm::APSInt ResOffset = Offset; 7665 if (BinOpKind == BO_Add) 7666 ResOffset = Offset.sadd_ov(Addend, Ov); 7667 else { 7668 assert(AddendIsRight && BinOpKind == BO_Sub && 7669 "operator must be add or sub with addend on the right"); 7670 ResOffset = Offset.ssub_ov(Addend, Ov); 7671 } 7672 7673 // We add an offset to a pointer here so we should support an offset as big as 7674 // possible. 7675 if (Ov) { 7676 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7677 "index (intermediate) result too big"); 7678 Offset = Offset.sext(2 * BitWidth); 7679 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7680 return; 7681 } 7682 7683 Offset = ResOffset; 7684 } 7685 7686 namespace { 7687 7688 // This is a wrapper class around StringLiteral to support offsetted string 7689 // literals as format strings. It takes the offset into account when returning 7690 // the string and its length or the source locations to display notes correctly. 7691 class FormatStringLiteral { 7692 const StringLiteral *FExpr; 7693 int64_t Offset; 7694 7695 public: 7696 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7697 : FExpr(fexpr), Offset(Offset) {} 7698 7699 StringRef getString() const { 7700 return FExpr->getString().drop_front(Offset); 7701 } 7702 7703 unsigned getByteLength() const { 7704 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7705 } 7706 7707 unsigned getLength() const { return FExpr->getLength() - Offset; } 7708 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7709 7710 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7711 7712 QualType getType() const { return FExpr->getType(); } 7713 7714 bool isAscii() const { return FExpr->isAscii(); } 7715 bool isWide() const { return FExpr->isWide(); } 7716 bool isUTF8() const { return FExpr->isUTF8(); } 7717 bool isUTF16() const { return FExpr->isUTF16(); } 7718 bool isUTF32() const { return FExpr->isUTF32(); } 7719 bool isPascal() const { return FExpr->isPascal(); } 7720 7721 SourceLocation getLocationOfByte( 7722 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7723 const TargetInfo &Target, unsigned *StartToken = nullptr, 7724 unsigned *StartTokenByteOffset = nullptr) const { 7725 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7726 StartToken, StartTokenByteOffset); 7727 } 7728 7729 SourceLocation getBeginLoc() const LLVM_READONLY { 7730 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7731 } 7732 7733 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7734 }; 7735 7736 } // namespace 7737 7738 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7739 const Expr *OrigFormatExpr, 7740 ArrayRef<const Expr *> Args, 7741 bool HasVAListArg, unsigned format_idx, 7742 unsigned firstDataArg, 7743 Sema::FormatStringType Type, 7744 bool inFunctionCall, 7745 Sema::VariadicCallType CallType, 7746 llvm::SmallBitVector &CheckedVarArgs, 7747 UncoveredArgHandler &UncoveredArg, 7748 bool IgnoreStringsWithoutSpecifiers); 7749 7750 // Determine if an expression is a string literal or constant string. 7751 // If this function returns false on the arguments to a function expecting a 7752 // format string, we will usually need to emit a warning. 7753 // True string literals are then checked by CheckFormatString. 7754 static StringLiteralCheckType 7755 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7756 bool HasVAListArg, unsigned format_idx, 7757 unsigned firstDataArg, Sema::FormatStringType Type, 7758 Sema::VariadicCallType CallType, bool InFunctionCall, 7759 llvm::SmallBitVector &CheckedVarArgs, 7760 UncoveredArgHandler &UncoveredArg, 7761 llvm::APSInt Offset, 7762 bool IgnoreStringsWithoutSpecifiers = false) { 7763 if (S.isConstantEvaluated()) 7764 return SLCT_NotALiteral; 7765 tryAgain: 7766 assert(Offset.isSigned() && "invalid offset"); 7767 7768 if (E->isTypeDependent() || E->isValueDependent()) 7769 return SLCT_NotALiteral; 7770 7771 E = E->IgnoreParenCasts(); 7772 7773 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7774 // Technically -Wformat-nonliteral does not warn about this case. 7775 // The behavior of printf and friends in this case is implementation 7776 // dependent. Ideally if the format string cannot be null then 7777 // it should have a 'nonnull' attribute in the function prototype. 7778 return SLCT_UncheckedLiteral; 7779 7780 switch (E->getStmtClass()) { 7781 case Stmt::BinaryConditionalOperatorClass: 7782 case Stmt::ConditionalOperatorClass: { 7783 // The expression is a literal if both sub-expressions were, and it was 7784 // completely checked only if both sub-expressions were checked. 7785 const AbstractConditionalOperator *C = 7786 cast<AbstractConditionalOperator>(E); 7787 7788 // Determine whether it is necessary to check both sub-expressions, for 7789 // example, because the condition expression is a constant that can be 7790 // evaluated at compile time. 7791 bool CheckLeft = true, CheckRight = true; 7792 7793 bool Cond; 7794 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7795 S.isConstantEvaluated())) { 7796 if (Cond) 7797 CheckRight = false; 7798 else 7799 CheckLeft = false; 7800 } 7801 7802 // We need to maintain the offsets for the right and the left hand side 7803 // separately to check if every possible indexed expression is a valid 7804 // string literal. They might have different offsets for different string 7805 // literals in the end. 7806 StringLiteralCheckType Left; 7807 if (!CheckLeft) 7808 Left = SLCT_UncheckedLiteral; 7809 else { 7810 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7811 HasVAListArg, format_idx, firstDataArg, 7812 Type, CallType, InFunctionCall, 7813 CheckedVarArgs, UncoveredArg, Offset, 7814 IgnoreStringsWithoutSpecifiers); 7815 if (Left == SLCT_NotALiteral || !CheckRight) { 7816 return Left; 7817 } 7818 } 7819 7820 StringLiteralCheckType Right = checkFormatStringExpr( 7821 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7822 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7823 IgnoreStringsWithoutSpecifiers); 7824 7825 return (CheckLeft && Left < Right) ? Left : Right; 7826 } 7827 7828 case Stmt::ImplicitCastExprClass: 7829 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7830 goto tryAgain; 7831 7832 case Stmt::OpaqueValueExprClass: 7833 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7834 E = src; 7835 goto tryAgain; 7836 } 7837 return SLCT_NotALiteral; 7838 7839 case Stmt::PredefinedExprClass: 7840 // While __func__, etc., are technically not string literals, they 7841 // cannot contain format specifiers and thus are not a security 7842 // liability. 7843 return SLCT_UncheckedLiteral; 7844 7845 case Stmt::DeclRefExprClass: { 7846 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7847 7848 // As an exception, do not flag errors for variables binding to 7849 // const string literals. 7850 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7851 bool isConstant = false; 7852 QualType T = DR->getType(); 7853 7854 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7855 isConstant = AT->getElementType().isConstant(S.Context); 7856 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7857 isConstant = T.isConstant(S.Context) && 7858 PT->getPointeeType().isConstant(S.Context); 7859 } else if (T->isObjCObjectPointerType()) { 7860 // In ObjC, there is usually no "const ObjectPointer" type, 7861 // so don't check if the pointee type is constant. 7862 isConstant = T.isConstant(S.Context); 7863 } 7864 7865 if (isConstant) { 7866 if (const Expr *Init = VD->getAnyInitializer()) { 7867 // Look through initializers like const char c[] = { "foo" } 7868 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7869 if (InitList->isStringLiteralInit()) 7870 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7871 } 7872 return checkFormatStringExpr(S, Init, Args, 7873 HasVAListArg, format_idx, 7874 firstDataArg, Type, CallType, 7875 /*InFunctionCall*/ false, CheckedVarArgs, 7876 UncoveredArg, Offset); 7877 } 7878 } 7879 7880 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7881 // special check to see if the format string is a function parameter 7882 // of the function calling the printf function. If the function 7883 // has an attribute indicating it is a printf-like function, then we 7884 // should suppress warnings concerning non-literals being used in a call 7885 // to a vprintf function. For example: 7886 // 7887 // void 7888 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7889 // va_list ap; 7890 // va_start(ap, fmt); 7891 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7892 // ... 7893 // } 7894 if (HasVAListArg) { 7895 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7896 if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) { 7897 int PVIndex = PV->getFunctionScopeIndex() + 1; 7898 for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) { 7899 // adjust for implicit parameter 7900 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) 7901 if (MD->isInstance()) 7902 ++PVIndex; 7903 // We also check if the formats are compatible. 7904 // We can't pass a 'scanf' string to a 'printf' function. 7905 if (PVIndex == PVFormat->getFormatIdx() && 7906 Type == S.GetFormatStringType(PVFormat)) 7907 return SLCT_UncheckedLiteral; 7908 } 7909 } 7910 } 7911 } 7912 } 7913 7914 return SLCT_NotALiteral; 7915 } 7916 7917 case Stmt::CallExprClass: 7918 case Stmt::CXXMemberCallExprClass: { 7919 const CallExpr *CE = cast<CallExpr>(E); 7920 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7921 bool IsFirst = true; 7922 StringLiteralCheckType CommonResult; 7923 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7924 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7925 StringLiteralCheckType Result = checkFormatStringExpr( 7926 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7927 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7928 IgnoreStringsWithoutSpecifiers); 7929 if (IsFirst) { 7930 CommonResult = Result; 7931 IsFirst = false; 7932 } 7933 } 7934 if (!IsFirst) 7935 return CommonResult; 7936 7937 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7938 unsigned BuiltinID = FD->getBuiltinID(); 7939 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7940 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7941 const Expr *Arg = CE->getArg(0); 7942 return checkFormatStringExpr(S, Arg, Args, 7943 HasVAListArg, format_idx, 7944 firstDataArg, Type, CallType, 7945 InFunctionCall, CheckedVarArgs, 7946 UncoveredArg, Offset, 7947 IgnoreStringsWithoutSpecifiers); 7948 } 7949 } 7950 } 7951 7952 return SLCT_NotALiteral; 7953 } 7954 case Stmt::ObjCMessageExprClass: { 7955 const auto *ME = cast<ObjCMessageExpr>(E); 7956 if (const auto *MD = ME->getMethodDecl()) { 7957 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7958 // As a special case heuristic, if we're using the method -[NSBundle 7959 // localizedStringForKey:value:table:], ignore any key strings that lack 7960 // format specifiers. The idea is that if the key doesn't have any 7961 // format specifiers then its probably just a key to map to the 7962 // localized strings. If it does have format specifiers though, then its 7963 // likely that the text of the key is the format string in the 7964 // programmer's language, and should be checked. 7965 const ObjCInterfaceDecl *IFace; 7966 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7967 IFace->getIdentifier()->isStr("NSBundle") && 7968 MD->getSelector().isKeywordSelector( 7969 {"localizedStringForKey", "value", "table"})) { 7970 IgnoreStringsWithoutSpecifiers = true; 7971 } 7972 7973 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7974 return checkFormatStringExpr( 7975 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7976 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7977 IgnoreStringsWithoutSpecifiers); 7978 } 7979 } 7980 7981 return SLCT_NotALiteral; 7982 } 7983 case Stmt::ObjCStringLiteralClass: 7984 case Stmt::StringLiteralClass: { 7985 const StringLiteral *StrE = nullptr; 7986 7987 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7988 StrE = ObjCFExpr->getString(); 7989 else 7990 StrE = cast<StringLiteral>(E); 7991 7992 if (StrE) { 7993 if (Offset.isNegative() || Offset > StrE->getLength()) { 7994 // TODO: It would be better to have an explicit warning for out of 7995 // bounds literals. 7996 return SLCT_NotALiteral; 7997 } 7998 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7999 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 8000 firstDataArg, Type, InFunctionCall, CallType, 8001 CheckedVarArgs, UncoveredArg, 8002 IgnoreStringsWithoutSpecifiers); 8003 return SLCT_CheckedLiteral; 8004 } 8005 8006 return SLCT_NotALiteral; 8007 } 8008 case Stmt::BinaryOperatorClass: { 8009 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 8010 8011 // A string literal + an int offset is still a string literal. 8012 if (BinOp->isAdditiveOp()) { 8013 Expr::EvalResult LResult, RResult; 8014 8015 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 8016 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8017 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 8018 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8019 8020 if (LIsInt != RIsInt) { 8021 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 8022 8023 if (LIsInt) { 8024 if (BinOpKind == BO_Add) { 8025 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 8026 E = BinOp->getRHS(); 8027 goto tryAgain; 8028 } 8029 } else { 8030 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 8031 E = BinOp->getLHS(); 8032 goto tryAgain; 8033 } 8034 } 8035 } 8036 8037 return SLCT_NotALiteral; 8038 } 8039 case Stmt::UnaryOperatorClass: { 8040 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 8041 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 8042 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 8043 Expr::EvalResult IndexResult; 8044 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 8045 Expr::SE_NoSideEffects, 8046 S.isConstantEvaluated())) { 8047 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 8048 /*RHS is int*/ true); 8049 E = ASE->getBase(); 8050 goto tryAgain; 8051 } 8052 } 8053 8054 return SLCT_NotALiteral; 8055 } 8056 8057 default: 8058 return SLCT_NotALiteral; 8059 } 8060 } 8061 8062 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 8063 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 8064 .Case("scanf", FST_Scanf) 8065 .Cases("printf", "printf0", FST_Printf) 8066 .Cases("NSString", "CFString", FST_NSString) 8067 .Case("strftime", FST_Strftime) 8068 .Case("strfmon", FST_Strfmon) 8069 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 8070 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 8071 .Case("os_trace", FST_OSLog) 8072 .Case("os_log", FST_OSLog) 8073 .Default(FST_Unknown); 8074 } 8075 8076 /// CheckFormatArguments - Check calls to printf and scanf (and similar 8077 /// functions) for correct use of format strings. 8078 /// Returns true if a format string has been fully checked. 8079 bool Sema::CheckFormatArguments(const FormatAttr *Format, 8080 ArrayRef<const Expr *> Args, 8081 bool IsCXXMember, 8082 VariadicCallType CallType, 8083 SourceLocation Loc, SourceRange Range, 8084 llvm::SmallBitVector &CheckedVarArgs) { 8085 FormatStringInfo FSI; 8086 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 8087 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 8088 FSI.FirstDataArg, GetFormatStringType(Format), 8089 CallType, Loc, Range, CheckedVarArgs); 8090 return false; 8091 } 8092 8093 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 8094 bool HasVAListArg, unsigned format_idx, 8095 unsigned firstDataArg, FormatStringType Type, 8096 VariadicCallType CallType, 8097 SourceLocation Loc, SourceRange Range, 8098 llvm::SmallBitVector &CheckedVarArgs) { 8099 // CHECK: printf/scanf-like function is called with no format string. 8100 if (format_idx >= Args.size()) { 8101 Diag(Loc, diag::warn_missing_format_string) << Range; 8102 return false; 8103 } 8104 8105 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 8106 8107 // CHECK: format string is not a string literal. 8108 // 8109 // Dynamically generated format strings are difficult to 8110 // automatically vet at compile time. Requiring that format strings 8111 // are string literals: (1) permits the checking of format strings by 8112 // the compiler and thereby (2) can practically remove the source of 8113 // many format string exploits. 8114 8115 // Format string can be either ObjC string (e.g. @"%d") or 8116 // C string (e.g. "%d") 8117 // ObjC string uses the same format specifiers as C string, so we can use 8118 // the same format string checking logic for both ObjC and C strings. 8119 UncoveredArgHandler UncoveredArg; 8120 StringLiteralCheckType CT = 8121 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 8122 format_idx, firstDataArg, Type, CallType, 8123 /*IsFunctionCall*/ true, CheckedVarArgs, 8124 UncoveredArg, 8125 /*no string offset*/ llvm::APSInt(64, false) = 0); 8126 8127 // Generate a diagnostic where an uncovered argument is detected. 8128 if (UncoveredArg.hasUncoveredArg()) { 8129 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 8130 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 8131 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 8132 } 8133 8134 if (CT != SLCT_NotALiteral) 8135 // Literal format string found, check done! 8136 return CT == SLCT_CheckedLiteral; 8137 8138 // Strftime is particular as it always uses a single 'time' argument, 8139 // so it is safe to pass a non-literal string. 8140 if (Type == FST_Strftime) 8141 return false; 8142 8143 // Do not emit diag when the string param is a macro expansion and the 8144 // format is either NSString or CFString. This is a hack to prevent 8145 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 8146 // which are usually used in place of NS and CF string literals. 8147 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 8148 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 8149 return false; 8150 8151 // If there are no arguments specified, warn with -Wformat-security, otherwise 8152 // warn only with -Wformat-nonliteral. 8153 if (Args.size() == firstDataArg) { 8154 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 8155 << OrigFormatExpr->getSourceRange(); 8156 switch (Type) { 8157 default: 8158 break; 8159 case FST_Kprintf: 8160 case FST_FreeBSDKPrintf: 8161 case FST_Printf: 8162 Diag(FormatLoc, diag::note_format_security_fixit) 8163 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 8164 break; 8165 case FST_NSString: 8166 Diag(FormatLoc, diag::note_format_security_fixit) 8167 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 8168 break; 8169 } 8170 } else { 8171 Diag(FormatLoc, diag::warn_format_nonliteral) 8172 << OrigFormatExpr->getSourceRange(); 8173 } 8174 return false; 8175 } 8176 8177 namespace { 8178 8179 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 8180 protected: 8181 Sema &S; 8182 const FormatStringLiteral *FExpr; 8183 const Expr *OrigFormatExpr; 8184 const Sema::FormatStringType FSType; 8185 const unsigned FirstDataArg; 8186 const unsigned NumDataArgs; 8187 const char *Beg; // Start of format string. 8188 const bool HasVAListArg; 8189 ArrayRef<const Expr *> Args; 8190 unsigned FormatIdx; 8191 llvm::SmallBitVector CoveredArgs; 8192 bool usesPositionalArgs = false; 8193 bool atFirstArg = true; 8194 bool inFunctionCall; 8195 Sema::VariadicCallType CallType; 8196 llvm::SmallBitVector &CheckedVarArgs; 8197 UncoveredArgHandler &UncoveredArg; 8198 8199 public: 8200 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 8201 const Expr *origFormatExpr, 8202 const Sema::FormatStringType type, unsigned firstDataArg, 8203 unsigned numDataArgs, const char *beg, bool hasVAListArg, 8204 ArrayRef<const Expr *> Args, unsigned formatIdx, 8205 bool inFunctionCall, Sema::VariadicCallType callType, 8206 llvm::SmallBitVector &CheckedVarArgs, 8207 UncoveredArgHandler &UncoveredArg) 8208 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 8209 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 8210 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 8211 inFunctionCall(inFunctionCall), CallType(callType), 8212 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 8213 CoveredArgs.resize(numDataArgs); 8214 CoveredArgs.reset(); 8215 } 8216 8217 void DoneProcessing(); 8218 8219 void HandleIncompleteSpecifier(const char *startSpecifier, 8220 unsigned specifierLen) override; 8221 8222 void HandleInvalidLengthModifier( 8223 const analyze_format_string::FormatSpecifier &FS, 8224 const analyze_format_string::ConversionSpecifier &CS, 8225 const char *startSpecifier, unsigned specifierLen, 8226 unsigned DiagID); 8227 8228 void HandleNonStandardLengthModifier( 8229 const analyze_format_string::FormatSpecifier &FS, 8230 const char *startSpecifier, unsigned specifierLen); 8231 8232 void HandleNonStandardConversionSpecifier( 8233 const analyze_format_string::ConversionSpecifier &CS, 8234 const char *startSpecifier, unsigned specifierLen); 8235 8236 void HandlePosition(const char *startPos, unsigned posLen) override; 8237 8238 void HandleInvalidPosition(const char *startSpecifier, 8239 unsigned specifierLen, 8240 analyze_format_string::PositionContext p) override; 8241 8242 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 8243 8244 void HandleNullChar(const char *nullCharacter) override; 8245 8246 template <typename Range> 8247 static void 8248 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 8249 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 8250 bool IsStringLocation, Range StringRange, 8251 ArrayRef<FixItHint> Fixit = None); 8252 8253 protected: 8254 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 8255 const char *startSpec, 8256 unsigned specifierLen, 8257 const char *csStart, unsigned csLen); 8258 8259 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 8260 const char *startSpec, 8261 unsigned specifierLen); 8262 8263 SourceRange getFormatStringRange(); 8264 CharSourceRange getSpecifierRange(const char *startSpecifier, 8265 unsigned specifierLen); 8266 SourceLocation getLocationOfByte(const char *x); 8267 8268 const Expr *getDataArg(unsigned i) const; 8269 8270 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 8271 const analyze_format_string::ConversionSpecifier &CS, 8272 const char *startSpecifier, unsigned specifierLen, 8273 unsigned argIndex); 8274 8275 template <typename Range> 8276 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 8277 bool IsStringLocation, Range StringRange, 8278 ArrayRef<FixItHint> Fixit = None); 8279 }; 8280 8281 } // namespace 8282 8283 SourceRange CheckFormatHandler::getFormatStringRange() { 8284 return OrigFormatExpr->getSourceRange(); 8285 } 8286 8287 CharSourceRange CheckFormatHandler:: 8288 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 8289 SourceLocation Start = getLocationOfByte(startSpecifier); 8290 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 8291 8292 // Advance the end SourceLocation by one due to half-open ranges. 8293 End = End.getLocWithOffset(1); 8294 8295 return CharSourceRange::getCharRange(Start, End); 8296 } 8297 8298 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 8299 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 8300 S.getLangOpts(), S.Context.getTargetInfo()); 8301 } 8302 8303 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 8304 unsigned specifierLen){ 8305 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 8306 getLocationOfByte(startSpecifier), 8307 /*IsStringLocation*/true, 8308 getSpecifierRange(startSpecifier, specifierLen)); 8309 } 8310 8311 void CheckFormatHandler::HandleInvalidLengthModifier( 8312 const analyze_format_string::FormatSpecifier &FS, 8313 const analyze_format_string::ConversionSpecifier &CS, 8314 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 8315 using namespace analyze_format_string; 8316 8317 const LengthModifier &LM = FS.getLengthModifier(); 8318 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8319 8320 // See if we know how to fix this length modifier. 8321 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8322 if (FixedLM) { 8323 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8324 getLocationOfByte(LM.getStart()), 8325 /*IsStringLocation*/true, 8326 getSpecifierRange(startSpecifier, specifierLen)); 8327 8328 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8329 << FixedLM->toString() 8330 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8331 8332 } else { 8333 FixItHint Hint; 8334 if (DiagID == diag::warn_format_nonsensical_length) 8335 Hint = FixItHint::CreateRemoval(LMRange); 8336 8337 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8338 getLocationOfByte(LM.getStart()), 8339 /*IsStringLocation*/true, 8340 getSpecifierRange(startSpecifier, specifierLen), 8341 Hint); 8342 } 8343 } 8344 8345 void CheckFormatHandler::HandleNonStandardLengthModifier( 8346 const analyze_format_string::FormatSpecifier &FS, 8347 const char *startSpecifier, unsigned specifierLen) { 8348 using namespace analyze_format_string; 8349 8350 const LengthModifier &LM = FS.getLengthModifier(); 8351 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8352 8353 // See if we know how to fix this length modifier. 8354 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8355 if (FixedLM) { 8356 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8357 << LM.toString() << 0, 8358 getLocationOfByte(LM.getStart()), 8359 /*IsStringLocation*/true, 8360 getSpecifierRange(startSpecifier, specifierLen)); 8361 8362 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8363 << FixedLM->toString() 8364 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8365 8366 } else { 8367 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8368 << LM.toString() << 0, 8369 getLocationOfByte(LM.getStart()), 8370 /*IsStringLocation*/true, 8371 getSpecifierRange(startSpecifier, specifierLen)); 8372 } 8373 } 8374 8375 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 8376 const analyze_format_string::ConversionSpecifier &CS, 8377 const char *startSpecifier, unsigned specifierLen) { 8378 using namespace analyze_format_string; 8379 8380 // See if we know how to fix this conversion specifier. 8381 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 8382 if (FixedCS) { 8383 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8384 << CS.toString() << /*conversion specifier*/1, 8385 getLocationOfByte(CS.getStart()), 8386 /*IsStringLocation*/true, 8387 getSpecifierRange(startSpecifier, specifierLen)); 8388 8389 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 8390 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 8391 << FixedCS->toString() 8392 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 8393 } else { 8394 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8395 << CS.toString() << /*conversion specifier*/1, 8396 getLocationOfByte(CS.getStart()), 8397 /*IsStringLocation*/true, 8398 getSpecifierRange(startSpecifier, specifierLen)); 8399 } 8400 } 8401 8402 void CheckFormatHandler::HandlePosition(const char *startPos, 8403 unsigned posLen) { 8404 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 8405 getLocationOfByte(startPos), 8406 /*IsStringLocation*/true, 8407 getSpecifierRange(startPos, posLen)); 8408 } 8409 8410 void 8411 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 8412 analyze_format_string::PositionContext p) { 8413 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 8414 << (unsigned) p, 8415 getLocationOfByte(startPos), /*IsStringLocation*/true, 8416 getSpecifierRange(startPos, posLen)); 8417 } 8418 8419 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 8420 unsigned posLen) { 8421 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 8422 getLocationOfByte(startPos), 8423 /*IsStringLocation*/true, 8424 getSpecifierRange(startPos, posLen)); 8425 } 8426 8427 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 8428 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 8429 // The presence of a null character is likely an error. 8430 EmitFormatDiagnostic( 8431 S.PDiag(diag::warn_printf_format_string_contains_null_char), 8432 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 8433 getFormatStringRange()); 8434 } 8435 } 8436 8437 // Note that this may return NULL if there was an error parsing or building 8438 // one of the argument expressions. 8439 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 8440 return Args[FirstDataArg + i]; 8441 } 8442 8443 void CheckFormatHandler::DoneProcessing() { 8444 // Does the number of data arguments exceed the number of 8445 // format conversions in the format string? 8446 if (!HasVAListArg) { 8447 // Find any arguments that weren't covered. 8448 CoveredArgs.flip(); 8449 signed notCoveredArg = CoveredArgs.find_first(); 8450 if (notCoveredArg >= 0) { 8451 assert((unsigned)notCoveredArg < NumDataArgs); 8452 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 8453 } else { 8454 UncoveredArg.setAllCovered(); 8455 } 8456 } 8457 } 8458 8459 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 8460 const Expr *ArgExpr) { 8461 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 8462 "Invalid state"); 8463 8464 if (!ArgExpr) 8465 return; 8466 8467 SourceLocation Loc = ArgExpr->getBeginLoc(); 8468 8469 if (S.getSourceManager().isInSystemMacro(Loc)) 8470 return; 8471 8472 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8473 for (auto E : DiagnosticExprs) 8474 PDiag << E->getSourceRange(); 8475 8476 CheckFormatHandler::EmitFormatDiagnostic( 8477 S, IsFunctionCall, DiagnosticExprs[0], 8478 PDiag, Loc, /*IsStringLocation*/false, 8479 DiagnosticExprs[0]->getSourceRange()); 8480 } 8481 8482 bool 8483 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8484 SourceLocation Loc, 8485 const char *startSpec, 8486 unsigned specifierLen, 8487 const char *csStart, 8488 unsigned csLen) { 8489 bool keepGoing = true; 8490 if (argIndex < NumDataArgs) { 8491 // Consider the argument coverered, even though the specifier doesn't 8492 // make sense. 8493 CoveredArgs.set(argIndex); 8494 } 8495 else { 8496 // If argIndex exceeds the number of data arguments we 8497 // don't issue a warning because that is just a cascade of warnings (and 8498 // they may have intended '%%' anyway). We don't want to continue processing 8499 // the format string after this point, however, as we will like just get 8500 // gibberish when trying to match arguments. 8501 keepGoing = false; 8502 } 8503 8504 StringRef Specifier(csStart, csLen); 8505 8506 // If the specifier in non-printable, it could be the first byte of a UTF-8 8507 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8508 // hex value. 8509 std::string CodePointStr; 8510 if (!llvm::sys::locale::isPrint(*csStart)) { 8511 llvm::UTF32 CodePoint; 8512 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8513 const llvm::UTF8 *E = 8514 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8515 llvm::ConversionResult Result = 8516 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8517 8518 if (Result != llvm::conversionOK) { 8519 unsigned char FirstChar = *csStart; 8520 CodePoint = (llvm::UTF32)FirstChar; 8521 } 8522 8523 llvm::raw_string_ostream OS(CodePointStr); 8524 if (CodePoint < 256) 8525 OS << "\\x" << llvm::format("%02x", CodePoint); 8526 else if (CodePoint <= 0xFFFF) 8527 OS << "\\u" << llvm::format("%04x", CodePoint); 8528 else 8529 OS << "\\U" << llvm::format("%08x", CodePoint); 8530 OS.flush(); 8531 Specifier = CodePointStr; 8532 } 8533 8534 EmitFormatDiagnostic( 8535 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8536 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8537 8538 return keepGoing; 8539 } 8540 8541 void 8542 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8543 const char *startSpec, 8544 unsigned specifierLen) { 8545 EmitFormatDiagnostic( 8546 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8547 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8548 } 8549 8550 bool 8551 CheckFormatHandler::CheckNumArgs( 8552 const analyze_format_string::FormatSpecifier &FS, 8553 const analyze_format_string::ConversionSpecifier &CS, 8554 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8555 8556 if (argIndex >= NumDataArgs) { 8557 PartialDiagnostic PDiag = FS.usesPositionalArg() 8558 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8559 << (argIndex+1) << NumDataArgs) 8560 : S.PDiag(diag::warn_printf_insufficient_data_args); 8561 EmitFormatDiagnostic( 8562 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8563 getSpecifierRange(startSpecifier, specifierLen)); 8564 8565 // Since more arguments than conversion tokens are given, by extension 8566 // all arguments are covered, so mark this as so. 8567 UncoveredArg.setAllCovered(); 8568 return false; 8569 } 8570 return true; 8571 } 8572 8573 template<typename Range> 8574 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8575 SourceLocation Loc, 8576 bool IsStringLocation, 8577 Range StringRange, 8578 ArrayRef<FixItHint> FixIt) { 8579 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8580 Loc, IsStringLocation, StringRange, FixIt); 8581 } 8582 8583 /// If the format string is not within the function call, emit a note 8584 /// so that the function call and string are in diagnostic messages. 8585 /// 8586 /// \param InFunctionCall if true, the format string is within the function 8587 /// call and only one diagnostic message will be produced. Otherwise, an 8588 /// extra note will be emitted pointing to location of the format string. 8589 /// 8590 /// \param ArgumentExpr the expression that is passed as the format string 8591 /// argument in the function call. Used for getting locations when two 8592 /// diagnostics are emitted. 8593 /// 8594 /// \param PDiag the callee should already have provided any strings for the 8595 /// diagnostic message. This function only adds locations and fixits 8596 /// to diagnostics. 8597 /// 8598 /// \param Loc primary location for diagnostic. If two diagnostics are 8599 /// required, one will be at Loc and a new SourceLocation will be created for 8600 /// the other one. 8601 /// 8602 /// \param IsStringLocation if true, Loc points to the format string should be 8603 /// used for the note. Otherwise, Loc points to the argument list and will 8604 /// be used with PDiag. 8605 /// 8606 /// \param StringRange some or all of the string to highlight. This is 8607 /// templated so it can accept either a CharSourceRange or a SourceRange. 8608 /// 8609 /// \param FixIt optional fix it hint for the format string. 8610 template <typename Range> 8611 void CheckFormatHandler::EmitFormatDiagnostic( 8612 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8613 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8614 Range StringRange, ArrayRef<FixItHint> FixIt) { 8615 if (InFunctionCall) { 8616 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8617 D << StringRange; 8618 D << FixIt; 8619 } else { 8620 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8621 << ArgumentExpr->getSourceRange(); 8622 8623 const Sema::SemaDiagnosticBuilder &Note = 8624 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8625 diag::note_format_string_defined); 8626 8627 Note << StringRange; 8628 Note << FixIt; 8629 } 8630 } 8631 8632 //===--- CHECK: Printf format string checking ------------------------------===// 8633 8634 namespace { 8635 8636 class CheckPrintfHandler : public CheckFormatHandler { 8637 public: 8638 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8639 const Expr *origFormatExpr, 8640 const Sema::FormatStringType type, unsigned firstDataArg, 8641 unsigned numDataArgs, bool isObjC, const char *beg, 8642 bool hasVAListArg, ArrayRef<const Expr *> Args, 8643 unsigned formatIdx, bool inFunctionCall, 8644 Sema::VariadicCallType CallType, 8645 llvm::SmallBitVector &CheckedVarArgs, 8646 UncoveredArgHandler &UncoveredArg) 8647 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8648 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8649 inFunctionCall, CallType, CheckedVarArgs, 8650 UncoveredArg) {} 8651 8652 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8653 8654 /// Returns true if '%@' specifiers are allowed in the format string. 8655 bool allowsObjCArg() const { 8656 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8657 FSType == Sema::FST_OSTrace; 8658 } 8659 8660 bool HandleInvalidPrintfConversionSpecifier( 8661 const analyze_printf::PrintfSpecifier &FS, 8662 const char *startSpecifier, 8663 unsigned specifierLen) override; 8664 8665 void handleInvalidMaskType(StringRef MaskType) override; 8666 8667 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8668 const char *startSpecifier, 8669 unsigned specifierLen) override; 8670 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8671 const char *StartSpecifier, 8672 unsigned SpecifierLen, 8673 const Expr *E); 8674 8675 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8676 const char *startSpecifier, unsigned specifierLen); 8677 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8678 const analyze_printf::OptionalAmount &Amt, 8679 unsigned type, 8680 const char *startSpecifier, unsigned specifierLen); 8681 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8682 const analyze_printf::OptionalFlag &flag, 8683 const char *startSpecifier, unsigned specifierLen); 8684 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8685 const analyze_printf::OptionalFlag &ignoredFlag, 8686 const analyze_printf::OptionalFlag &flag, 8687 const char *startSpecifier, unsigned specifierLen); 8688 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8689 const Expr *E); 8690 8691 void HandleEmptyObjCModifierFlag(const char *startFlag, 8692 unsigned flagLen) override; 8693 8694 void HandleInvalidObjCModifierFlag(const char *startFlag, 8695 unsigned flagLen) override; 8696 8697 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8698 const char *flagsEnd, 8699 const char *conversionPosition) 8700 override; 8701 }; 8702 8703 } // namespace 8704 8705 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8706 const analyze_printf::PrintfSpecifier &FS, 8707 const char *startSpecifier, 8708 unsigned specifierLen) { 8709 const analyze_printf::PrintfConversionSpecifier &CS = 8710 FS.getConversionSpecifier(); 8711 8712 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8713 getLocationOfByte(CS.getStart()), 8714 startSpecifier, specifierLen, 8715 CS.getStart(), CS.getLength()); 8716 } 8717 8718 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8719 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8720 } 8721 8722 bool CheckPrintfHandler::HandleAmount( 8723 const analyze_format_string::OptionalAmount &Amt, 8724 unsigned k, const char *startSpecifier, 8725 unsigned specifierLen) { 8726 if (Amt.hasDataArgument()) { 8727 if (!HasVAListArg) { 8728 unsigned argIndex = Amt.getArgIndex(); 8729 if (argIndex >= NumDataArgs) { 8730 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8731 << k, 8732 getLocationOfByte(Amt.getStart()), 8733 /*IsStringLocation*/true, 8734 getSpecifierRange(startSpecifier, specifierLen)); 8735 // Don't do any more checking. We will just emit 8736 // spurious errors. 8737 return false; 8738 } 8739 8740 // Type check the data argument. It should be an 'int'. 8741 // Although not in conformance with C99, we also allow the argument to be 8742 // an 'unsigned int' as that is a reasonably safe case. GCC also 8743 // doesn't emit a warning for that case. 8744 CoveredArgs.set(argIndex); 8745 const Expr *Arg = getDataArg(argIndex); 8746 if (!Arg) 8747 return false; 8748 8749 QualType T = Arg->getType(); 8750 8751 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8752 assert(AT.isValid()); 8753 8754 if (!AT.matchesType(S.Context, T)) { 8755 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8756 << k << AT.getRepresentativeTypeName(S.Context) 8757 << T << Arg->getSourceRange(), 8758 getLocationOfByte(Amt.getStart()), 8759 /*IsStringLocation*/true, 8760 getSpecifierRange(startSpecifier, specifierLen)); 8761 // Don't do any more checking. We will just emit 8762 // spurious errors. 8763 return false; 8764 } 8765 } 8766 } 8767 return true; 8768 } 8769 8770 void CheckPrintfHandler::HandleInvalidAmount( 8771 const analyze_printf::PrintfSpecifier &FS, 8772 const analyze_printf::OptionalAmount &Amt, 8773 unsigned type, 8774 const char *startSpecifier, 8775 unsigned specifierLen) { 8776 const analyze_printf::PrintfConversionSpecifier &CS = 8777 FS.getConversionSpecifier(); 8778 8779 FixItHint fixit = 8780 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8781 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8782 Amt.getConstantLength())) 8783 : FixItHint(); 8784 8785 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8786 << type << CS.toString(), 8787 getLocationOfByte(Amt.getStart()), 8788 /*IsStringLocation*/true, 8789 getSpecifierRange(startSpecifier, specifierLen), 8790 fixit); 8791 } 8792 8793 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8794 const analyze_printf::OptionalFlag &flag, 8795 const char *startSpecifier, 8796 unsigned specifierLen) { 8797 // Warn about pointless flag with a fixit removal. 8798 const analyze_printf::PrintfConversionSpecifier &CS = 8799 FS.getConversionSpecifier(); 8800 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8801 << flag.toString() << CS.toString(), 8802 getLocationOfByte(flag.getPosition()), 8803 /*IsStringLocation*/true, 8804 getSpecifierRange(startSpecifier, specifierLen), 8805 FixItHint::CreateRemoval( 8806 getSpecifierRange(flag.getPosition(), 1))); 8807 } 8808 8809 void CheckPrintfHandler::HandleIgnoredFlag( 8810 const analyze_printf::PrintfSpecifier &FS, 8811 const analyze_printf::OptionalFlag &ignoredFlag, 8812 const analyze_printf::OptionalFlag &flag, 8813 const char *startSpecifier, 8814 unsigned specifierLen) { 8815 // Warn about ignored flag with a fixit removal. 8816 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8817 << ignoredFlag.toString() << flag.toString(), 8818 getLocationOfByte(ignoredFlag.getPosition()), 8819 /*IsStringLocation*/true, 8820 getSpecifierRange(startSpecifier, specifierLen), 8821 FixItHint::CreateRemoval( 8822 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8823 } 8824 8825 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8826 unsigned flagLen) { 8827 // Warn about an empty flag. 8828 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8829 getLocationOfByte(startFlag), 8830 /*IsStringLocation*/true, 8831 getSpecifierRange(startFlag, flagLen)); 8832 } 8833 8834 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8835 unsigned flagLen) { 8836 // Warn about an invalid flag. 8837 auto Range = getSpecifierRange(startFlag, flagLen); 8838 StringRef flag(startFlag, flagLen); 8839 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8840 getLocationOfByte(startFlag), 8841 /*IsStringLocation*/true, 8842 Range, FixItHint::CreateRemoval(Range)); 8843 } 8844 8845 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8846 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8847 // Warn about using '[...]' without a '@' conversion. 8848 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8849 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8850 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8851 getLocationOfByte(conversionPosition), 8852 /*IsStringLocation*/true, 8853 Range, FixItHint::CreateRemoval(Range)); 8854 } 8855 8856 // Determines if the specified is a C++ class or struct containing 8857 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8858 // "c_str()"). 8859 template<typename MemberKind> 8860 static llvm::SmallPtrSet<MemberKind*, 1> 8861 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8862 const RecordType *RT = Ty->getAs<RecordType>(); 8863 llvm::SmallPtrSet<MemberKind*, 1> Results; 8864 8865 if (!RT) 8866 return Results; 8867 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8868 if (!RD || !RD->getDefinition()) 8869 return Results; 8870 8871 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8872 Sema::LookupMemberName); 8873 R.suppressDiagnostics(); 8874 8875 // We just need to include all members of the right kind turned up by the 8876 // filter, at this point. 8877 if (S.LookupQualifiedName(R, RT->getDecl())) 8878 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8879 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8880 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8881 Results.insert(FK); 8882 } 8883 return Results; 8884 } 8885 8886 /// Check if we could call '.c_str()' on an object. 8887 /// 8888 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8889 /// allow the call, or if it would be ambiguous). 8890 bool Sema::hasCStrMethod(const Expr *E) { 8891 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8892 8893 MethodSet Results = 8894 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8895 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8896 MI != ME; ++MI) 8897 if ((*MI)->getMinRequiredArguments() == 0) 8898 return true; 8899 return false; 8900 } 8901 8902 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8903 // better diagnostic if so. AT is assumed to be valid. 8904 // Returns true when a c_str() conversion method is found. 8905 bool CheckPrintfHandler::checkForCStrMembers( 8906 const analyze_printf::ArgType &AT, const Expr *E) { 8907 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8908 8909 MethodSet Results = 8910 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8911 8912 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8913 MI != ME; ++MI) { 8914 const CXXMethodDecl *Method = *MI; 8915 if (Method->getMinRequiredArguments() == 0 && 8916 AT.matchesType(S.Context, Method->getReturnType())) { 8917 // FIXME: Suggest parens if the expression needs them. 8918 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8919 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8920 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8921 return true; 8922 } 8923 } 8924 8925 return false; 8926 } 8927 8928 bool 8929 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8930 &FS, 8931 const char *startSpecifier, 8932 unsigned specifierLen) { 8933 using namespace analyze_format_string; 8934 using namespace analyze_printf; 8935 8936 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8937 8938 if (FS.consumesDataArgument()) { 8939 if (atFirstArg) { 8940 atFirstArg = false; 8941 usesPositionalArgs = FS.usesPositionalArg(); 8942 } 8943 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8944 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8945 startSpecifier, specifierLen); 8946 return false; 8947 } 8948 } 8949 8950 // First check if the field width, precision, and conversion specifier 8951 // have matching data arguments. 8952 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8953 startSpecifier, specifierLen)) { 8954 return false; 8955 } 8956 8957 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8958 startSpecifier, specifierLen)) { 8959 return false; 8960 } 8961 8962 if (!CS.consumesDataArgument()) { 8963 // FIXME: Technically specifying a precision or field width here 8964 // makes no sense. Worth issuing a warning at some point. 8965 return true; 8966 } 8967 8968 // Consume the argument. 8969 unsigned argIndex = FS.getArgIndex(); 8970 if (argIndex < NumDataArgs) { 8971 // The check to see if the argIndex is valid will come later. 8972 // We set the bit here because we may exit early from this 8973 // function if we encounter some other error. 8974 CoveredArgs.set(argIndex); 8975 } 8976 8977 // FreeBSD kernel extensions. 8978 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8979 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8980 // We need at least two arguments. 8981 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8982 return false; 8983 8984 // Claim the second argument. 8985 CoveredArgs.set(argIndex + 1); 8986 8987 // Type check the first argument (int for %b, pointer for %D) 8988 const Expr *Ex = getDataArg(argIndex); 8989 const analyze_printf::ArgType &AT = 8990 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8991 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8992 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8993 EmitFormatDiagnostic( 8994 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8995 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8996 << false << Ex->getSourceRange(), 8997 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8998 getSpecifierRange(startSpecifier, specifierLen)); 8999 9000 // Type check the second argument (char * for both %b and %D) 9001 Ex = getDataArg(argIndex + 1); 9002 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 9003 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 9004 EmitFormatDiagnostic( 9005 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9006 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 9007 << false << Ex->getSourceRange(), 9008 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9009 getSpecifierRange(startSpecifier, specifierLen)); 9010 9011 return true; 9012 } 9013 9014 // Check for using an Objective-C specific conversion specifier 9015 // in a non-ObjC literal. 9016 if (!allowsObjCArg() && CS.isObjCArg()) { 9017 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9018 specifierLen); 9019 } 9020 9021 // %P can only be used with os_log. 9022 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 9023 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9024 specifierLen); 9025 } 9026 9027 // %n is not allowed with os_log. 9028 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 9029 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 9030 getLocationOfByte(CS.getStart()), 9031 /*IsStringLocation*/ false, 9032 getSpecifierRange(startSpecifier, specifierLen)); 9033 9034 return true; 9035 } 9036 9037 // Only scalars are allowed for os_trace. 9038 if (FSType == Sema::FST_OSTrace && 9039 (CS.getKind() == ConversionSpecifier::PArg || 9040 CS.getKind() == ConversionSpecifier::sArg || 9041 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 9042 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9043 specifierLen); 9044 } 9045 9046 // Check for use of public/private annotation outside of os_log(). 9047 if (FSType != Sema::FST_OSLog) { 9048 if (FS.isPublic().isSet()) { 9049 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9050 << "public", 9051 getLocationOfByte(FS.isPublic().getPosition()), 9052 /*IsStringLocation*/ false, 9053 getSpecifierRange(startSpecifier, specifierLen)); 9054 } 9055 if (FS.isPrivate().isSet()) { 9056 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9057 << "private", 9058 getLocationOfByte(FS.isPrivate().getPosition()), 9059 /*IsStringLocation*/ false, 9060 getSpecifierRange(startSpecifier, specifierLen)); 9061 } 9062 } 9063 9064 // Check for invalid use of field width 9065 if (!FS.hasValidFieldWidth()) { 9066 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 9067 startSpecifier, specifierLen); 9068 } 9069 9070 // Check for invalid use of precision 9071 if (!FS.hasValidPrecision()) { 9072 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 9073 startSpecifier, specifierLen); 9074 } 9075 9076 // Precision is mandatory for %P specifier. 9077 if (CS.getKind() == ConversionSpecifier::PArg && 9078 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 9079 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 9080 getLocationOfByte(startSpecifier), 9081 /*IsStringLocation*/ false, 9082 getSpecifierRange(startSpecifier, specifierLen)); 9083 } 9084 9085 // Check each flag does not conflict with any other component. 9086 if (!FS.hasValidThousandsGroupingPrefix()) 9087 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 9088 if (!FS.hasValidLeadingZeros()) 9089 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 9090 if (!FS.hasValidPlusPrefix()) 9091 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 9092 if (!FS.hasValidSpacePrefix()) 9093 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 9094 if (!FS.hasValidAlternativeForm()) 9095 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 9096 if (!FS.hasValidLeftJustified()) 9097 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 9098 9099 // Check that flags are not ignored by another flag 9100 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 9101 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 9102 startSpecifier, specifierLen); 9103 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 9104 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 9105 startSpecifier, specifierLen); 9106 9107 // Check the length modifier is valid with the given conversion specifier. 9108 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9109 S.getLangOpts())) 9110 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9111 diag::warn_format_nonsensical_length); 9112 else if (!FS.hasStandardLengthModifier()) 9113 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9114 else if (!FS.hasStandardLengthConversionCombination()) 9115 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9116 diag::warn_format_non_standard_conversion_spec); 9117 9118 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9119 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9120 9121 // The remaining checks depend on the data arguments. 9122 if (HasVAListArg) 9123 return true; 9124 9125 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9126 return false; 9127 9128 const Expr *Arg = getDataArg(argIndex); 9129 if (!Arg) 9130 return true; 9131 9132 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 9133 } 9134 9135 static bool requiresParensToAddCast(const Expr *E) { 9136 // FIXME: We should have a general way to reason about operator 9137 // precedence and whether parens are actually needed here. 9138 // Take care of a few common cases where they aren't. 9139 const Expr *Inside = E->IgnoreImpCasts(); 9140 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 9141 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 9142 9143 switch (Inside->getStmtClass()) { 9144 case Stmt::ArraySubscriptExprClass: 9145 case Stmt::CallExprClass: 9146 case Stmt::CharacterLiteralClass: 9147 case Stmt::CXXBoolLiteralExprClass: 9148 case Stmt::DeclRefExprClass: 9149 case Stmt::FloatingLiteralClass: 9150 case Stmt::IntegerLiteralClass: 9151 case Stmt::MemberExprClass: 9152 case Stmt::ObjCArrayLiteralClass: 9153 case Stmt::ObjCBoolLiteralExprClass: 9154 case Stmt::ObjCBoxedExprClass: 9155 case Stmt::ObjCDictionaryLiteralClass: 9156 case Stmt::ObjCEncodeExprClass: 9157 case Stmt::ObjCIvarRefExprClass: 9158 case Stmt::ObjCMessageExprClass: 9159 case Stmt::ObjCPropertyRefExprClass: 9160 case Stmt::ObjCStringLiteralClass: 9161 case Stmt::ObjCSubscriptRefExprClass: 9162 case Stmt::ParenExprClass: 9163 case Stmt::StringLiteralClass: 9164 case Stmt::UnaryOperatorClass: 9165 return false; 9166 default: 9167 return true; 9168 } 9169 } 9170 9171 static std::pair<QualType, StringRef> 9172 shouldNotPrintDirectly(const ASTContext &Context, 9173 QualType IntendedTy, 9174 const Expr *E) { 9175 // Use a 'while' to peel off layers of typedefs. 9176 QualType TyTy = IntendedTy; 9177 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 9178 StringRef Name = UserTy->getDecl()->getName(); 9179 QualType CastTy = llvm::StringSwitch<QualType>(Name) 9180 .Case("CFIndex", Context.getNSIntegerType()) 9181 .Case("NSInteger", Context.getNSIntegerType()) 9182 .Case("NSUInteger", Context.getNSUIntegerType()) 9183 .Case("SInt32", Context.IntTy) 9184 .Case("UInt32", Context.UnsignedIntTy) 9185 .Default(QualType()); 9186 9187 if (!CastTy.isNull()) 9188 return std::make_pair(CastTy, Name); 9189 9190 TyTy = UserTy->desugar(); 9191 } 9192 9193 // Strip parens if necessary. 9194 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 9195 return shouldNotPrintDirectly(Context, 9196 PE->getSubExpr()->getType(), 9197 PE->getSubExpr()); 9198 9199 // If this is a conditional expression, then its result type is constructed 9200 // via usual arithmetic conversions and thus there might be no necessary 9201 // typedef sugar there. Recurse to operands to check for NSInteger & 9202 // Co. usage condition. 9203 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9204 QualType TrueTy, FalseTy; 9205 StringRef TrueName, FalseName; 9206 9207 std::tie(TrueTy, TrueName) = 9208 shouldNotPrintDirectly(Context, 9209 CO->getTrueExpr()->getType(), 9210 CO->getTrueExpr()); 9211 std::tie(FalseTy, FalseName) = 9212 shouldNotPrintDirectly(Context, 9213 CO->getFalseExpr()->getType(), 9214 CO->getFalseExpr()); 9215 9216 if (TrueTy == FalseTy) 9217 return std::make_pair(TrueTy, TrueName); 9218 else if (TrueTy.isNull()) 9219 return std::make_pair(FalseTy, FalseName); 9220 else if (FalseTy.isNull()) 9221 return std::make_pair(TrueTy, TrueName); 9222 } 9223 9224 return std::make_pair(QualType(), StringRef()); 9225 } 9226 9227 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 9228 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 9229 /// type do not count. 9230 static bool 9231 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 9232 QualType From = ICE->getSubExpr()->getType(); 9233 QualType To = ICE->getType(); 9234 // It's an integer promotion if the destination type is the promoted 9235 // source type. 9236 if (ICE->getCastKind() == CK_IntegralCast && 9237 From->isPromotableIntegerType() && 9238 S.Context.getPromotedIntegerType(From) == To) 9239 return true; 9240 // Look through vector types, since we do default argument promotion for 9241 // those in OpenCL. 9242 if (const auto *VecTy = From->getAs<ExtVectorType>()) 9243 From = VecTy->getElementType(); 9244 if (const auto *VecTy = To->getAs<ExtVectorType>()) 9245 To = VecTy->getElementType(); 9246 // It's a floating promotion if the source type is a lower rank. 9247 return ICE->getCastKind() == CK_FloatingCast && 9248 S.Context.getFloatingTypeOrder(From, To) < 0; 9249 } 9250 9251 bool 9252 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9253 const char *StartSpecifier, 9254 unsigned SpecifierLen, 9255 const Expr *E) { 9256 using namespace analyze_format_string; 9257 using namespace analyze_printf; 9258 9259 // Now type check the data expression that matches the 9260 // format specifier. 9261 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 9262 if (!AT.isValid()) 9263 return true; 9264 9265 QualType ExprTy = E->getType(); 9266 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 9267 ExprTy = TET->getUnderlyingExpr()->getType(); 9268 } 9269 9270 // Diagnose attempts to print a boolean value as a character. Unlike other 9271 // -Wformat diagnostics, this is fine from a type perspective, but it still 9272 // doesn't make sense. 9273 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 9274 E->isKnownToHaveBooleanValue()) { 9275 const CharSourceRange &CSR = 9276 getSpecifierRange(StartSpecifier, SpecifierLen); 9277 SmallString<4> FSString; 9278 llvm::raw_svector_ostream os(FSString); 9279 FS.toString(os); 9280 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 9281 << FSString, 9282 E->getExprLoc(), false, CSR); 9283 return true; 9284 } 9285 9286 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 9287 if (Match == analyze_printf::ArgType::Match) 9288 return true; 9289 9290 // Look through argument promotions for our error message's reported type. 9291 // This includes the integral and floating promotions, but excludes array 9292 // and function pointer decay (seeing that an argument intended to be a 9293 // string has type 'char [6]' is probably more confusing than 'char *') and 9294 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 9295 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9296 if (isArithmeticArgumentPromotion(S, ICE)) { 9297 E = ICE->getSubExpr(); 9298 ExprTy = E->getType(); 9299 9300 // Check if we didn't match because of an implicit cast from a 'char' 9301 // or 'short' to an 'int'. This is done because printf is a varargs 9302 // function. 9303 if (ICE->getType() == S.Context.IntTy || 9304 ICE->getType() == S.Context.UnsignedIntTy) { 9305 // All further checking is done on the subexpression 9306 const analyze_printf::ArgType::MatchKind ImplicitMatch = 9307 AT.matchesType(S.Context, ExprTy); 9308 if (ImplicitMatch == analyze_printf::ArgType::Match) 9309 return true; 9310 if (ImplicitMatch == ArgType::NoMatchPedantic || 9311 ImplicitMatch == ArgType::NoMatchTypeConfusion) 9312 Match = ImplicitMatch; 9313 } 9314 } 9315 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 9316 // Special case for 'a', which has type 'int' in C. 9317 // Note, however, that we do /not/ want to treat multibyte constants like 9318 // 'MooV' as characters! This form is deprecated but still exists. In 9319 // addition, don't treat expressions as of type 'char' if one byte length 9320 // modifier is provided. 9321 if (ExprTy == S.Context.IntTy && 9322 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 9323 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 9324 ExprTy = S.Context.CharTy; 9325 } 9326 9327 // Look through enums to their underlying type. 9328 bool IsEnum = false; 9329 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 9330 ExprTy = EnumTy->getDecl()->getIntegerType(); 9331 IsEnum = true; 9332 } 9333 9334 // %C in an Objective-C context prints a unichar, not a wchar_t. 9335 // If the argument is an integer of some kind, believe the %C and suggest 9336 // a cast instead of changing the conversion specifier. 9337 QualType IntendedTy = ExprTy; 9338 if (isObjCContext() && 9339 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 9340 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 9341 !ExprTy->isCharType()) { 9342 // 'unichar' is defined as a typedef of unsigned short, but we should 9343 // prefer using the typedef if it is visible. 9344 IntendedTy = S.Context.UnsignedShortTy; 9345 9346 // While we are here, check if the value is an IntegerLiteral that happens 9347 // to be within the valid range. 9348 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 9349 const llvm::APInt &V = IL->getValue(); 9350 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 9351 return true; 9352 } 9353 9354 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 9355 Sema::LookupOrdinaryName); 9356 if (S.LookupName(Result, S.getCurScope())) { 9357 NamedDecl *ND = Result.getFoundDecl(); 9358 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 9359 if (TD->getUnderlyingType() == IntendedTy) 9360 IntendedTy = S.Context.getTypedefType(TD); 9361 } 9362 } 9363 } 9364 9365 // Special-case some of Darwin's platform-independence types by suggesting 9366 // casts to primitive types that are known to be large enough. 9367 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 9368 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 9369 QualType CastTy; 9370 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 9371 if (!CastTy.isNull()) { 9372 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 9373 // (long in ASTContext). Only complain to pedants. 9374 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 9375 (AT.isSizeT() || AT.isPtrdiffT()) && 9376 AT.matchesType(S.Context, CastTy)) 9377 Match = ArgType::NoMatchPedantic; 9378 IntendedTy = CastTy; 9379 ShouldNotPrintDirectly = true; 9380 } 9381 } 9382 9383 // We may be able to offer a FixItHint if it is a supported type. 9384 PrintfSpecifier fixedFS = FS; 9385 bool Success = 9386 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 9387 9388 if (Success) { 9389 // Get the fix string from the fixed format specifier 9390 SmallString<16> buf; 9391 llvm::raw_svector_ostream os(buf); 9392 fixedFS.toString(os); 9393 9394 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 9395 9396 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 9397 unsigned Diag; 9398 switch (Match) { 9399 case ArgType::Match: llvm_unreachable("expected non-matching"); 9400 case ArgType::NoMatchPedantic: 9401 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9402 break; 9403 case ArgType::NoMatchTypeConfusion: 9404 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9405 break; 9406 case ArgType::NoMatch: 9407 Diag = diag::warn_format_conversion_argument_type_mismatch; 9408 break; 9409 } 9410 9411 // In this case, the specifier is wrong and should be changed to match 9412 // the argument. 9413 EmitFormatDiagnostic(S.PDiag(Diag) 9414 << AT.getRepresentativeTypeName(S.Context) 9415 << IntendedTy << IsEnum << E->getSourceRange(), 9416 E->getBeginLoc(), 9417 /*IsStringLocation*/ false, SpecRange, 9418 FixItHint::CreateReplacement(SpecRange, os.str())); 9419 } else { 9420 // The canonical type for formatting this value is different from the 9421 // actual type of the expression. (This occurs, for example, with Darwin's 9422 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 9423 // should be printed as 'long' for 64-bit compatibility.) 9424 // Rather than emitting a normal format/argument mismatch, we want to 9425 // add a cast to the recommended type (and correct the format string 9426 // if necessary). 9427 SmallString<16> CastBuf; 9428 llvm::raw_svector_ostream CastFix(CastBuf); 9429 CastFix << "("; 9430 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 9431 CastFix << ")"; 9432 9433 SmallVector<FixItHint,4> Hints; 9434 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 9435 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 9436 9437 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 9438 // If there's already a cast present, just replace it. 9439 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 9440 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 9441 9442 } else if (!requiresParensToAddCast(E)) { 9443 // If the expression has high enough precedence, 9444 // just write the C-style cast. 9445 Hints.push_back( 9446 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9447 } else { 9448 // Otherwise, add parens around the expression as well as the cast. 9449 CastFix << "("; 9450 Hints.push_back( 9451 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9452 9453 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 9454 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 9455 } 9456 9457 if (ShouldNotPrintDirectly) { 9458 // The expression has a type that should not be printed directly. 9459 // We extract the name from the typedef because we don't want to show 9460 // the underlying type in the diagnostic. 9461 StringRef Name; 9462 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 9463 Name = TypedefTy->getDecl()->getName(); 9464 else 9465 Name = CastTyName; 9466 unsigned Diag = Match == ArgType::NoMatchPedantic 9467 ? diag::warn_format_argument_needs_cast_pedantic 9468 : diag::warn_format_argument_needs_cast; 9469 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 9470 << E->getSourceRange(), 9471 E->getBeginLoc(), /*IsStringLocation=*/false, 9472 SpecRange, Hints); 9473 } else { 9474 // In this case, the expression could be printed using a different 9475 // specifier, but we've decided that the specifier is probably correct 9476 // and we should cast instead. Just use the normal warning message. 9477 EmitFormatDiagnostic( 9478 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9479 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9480 << E->getSourceRange(), 9481 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9482 } 9483 } 9484 } else { 9485 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9486 SpecifierLen); 9487 // Since the warning for passing non-POD types to variadic functions 9488 // was deferred until now, we emit a warning for non-POD 9489 // arguments here. 9490 switch (S.isValidVarArgType(ExprTy)) { 9491 case Sema::VAK_Valid: 9492 case Sema::VAK_ValidInCXX11: { 9493 unsigned Diag; 9494 switch (Match) { 9495 case ArgType::Match: llvm_unreachable("expected non-matching"); 9496 case ArgType::NoMatchPedantic: 9497 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9498 break; 9499 case ArgType::NoMatchTypeConfusion: 9500 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9501 break; 9502 case ArgType::NoMatch: 9503 Diag = diag::warn_format_conversion_argument_type_mismatch; 9504 break; 9505 } 9506 9507 EmitFormatDiagnostic( 9508 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9509 << IsEnum << CSR << E->getSourceRange(), 9510 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9511 break; 9512 } 9513 case Sema::VAK_Undefined: 9514 case Sema::VAK_MSVCUndefined: 9515 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9516 << S.getLangOpts().CPlusPlus11 << ExprTy 9517 << CallType 9518 << AT.getRepresentativeTypeName(S.Context) << CSR 9519 << E->getSourceRange(), 9520 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9521 checkForCStrMembers(AT, E); 9522 break; 9523 9524 case Sema::VAK_Invalid: 9525 if (ExprTy->isObjCObjectType()) 9526 EmitFormatDiagnostic( 9527 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9528 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9529 << AT.getRepresentativeTypeName(S.Context) << CSR 9530 << E->getSourceRange(), 9531 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9532 else 9533 // FIXME: If this is an initializer list, suggest removing the braces 9534 // or inserting a cast to the target type. 9535 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9536 << isa<InitListExpr>(E) << ExprTy << CallType 9537 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9538 break; 9539 } 9540 9541 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9542 "format string specifier index out of range"); 9543 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9544 } 9545 9546 return true; 9547 } 9548 9549 //===--- CHECK: Scanf format string checking ------------------------------===// 9550 9551 namespace { 9552 9553 class CheckScanfHandler : public CheckFormatHandler { 9554 public: 9555 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9556 const Expr *origFormatExpr, Sema::FormatStringType type, 9557 unsigned firstDataArg, unsigned numDataArgs, 9558 const char *beg, bool hasVAListArg, 9559 ArrayRef<const Expr *> Args, unsigned formatIdx, 9560 bool inFunctionCall, Sema::VariadicCallType CallType, 9561 llvm::SmallBitVector &CheckedVarArgs, 9562 UncoveredArgHandler &UncoveredArg) 9563 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9564 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9565 inFunctionCall, CallType, CheckedVarArgs, 9566 UncoveredArg) {} 9567 9568 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9569 const char *startSpecifier, 9570 unsigned specifierLen) override; 9571 9572 bool HandleInvalidScanfConversionSpecifier( 9573 const analyze_scanf::ScanfSpecifier &FS, 9574 const char *startSpecifier, 9575 unsigned specifierLen) override; 9576 9577 void HandleIncompleteScanList(const char *start, const char *end) override; 9578 }; 9579 9580 } // namespace 9581 9582 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9583 const char *end) { 9584 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9585 getLocationOfByte(end), /*IsStringLocation*/true, 9586 getSpecifierRange(start, end - start)); 9587 } 9588 9589 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9590 const analyze_scanf::ScanfSpecifier &FS, 9591 const char *startSpecifier, 9592 unsigned specifierLen) { 9593 const analyze_scanf::ScanfConversionSpecifier &CS = 9594 FS.getConversionSpecifier(); 9595 9596 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9597 getLocationOfByte(CS.getStart()), 9598 startSpecifier, specifierLen, 9599 CS.getStart(), CS.getLength()); 9600 } 9601 9602 bool CheckScanfHandler::HandleScanfSpecifier( 9603 const analyze_scanf::ScanfSpecifier &FS, 9604 const char *startSpecifier, 9605 unsigned specifierLen) { 9606 using namespace analyze_scanf; 9607 using namespace analyze_format_string; 9608 9609 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9610 9611 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9612 // be used to decide if we are using positional arguments consistently. 9613 if (FS.consumesDataArgument()) { 9614 if (atFirstArg) { 9615 atFirstArg = false; 9616 usesPositionalArgs = FS.usesPositionalArg(); 9617 } 9618 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9619 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9620 startSpecifier, specifierLen); 9621 return false; 9622 } 9623 } 9624 9625 // Check if the field with is non-zero. 9626 const OptionalAmount &Amt = FS.getFieldWidth(); 9627 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9628 if (Amt.getConstantAmount() == 0) { 9629 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9630 Amt.getConstantLength()); 9631 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9632 getLocationOfByte(Amt.getStart()), 9633 /*IsStringLocation*/true, R, 9634 FixItHint::CreateRemoval(R)); 9635 } 9636 } 9637 9638 if (!FS.consumesDataArgument()) { 9639 // FIXME: Technically specifying a precision or field width here 9640 // makes no sense. Worth issuing a warning at some point. 9641 return true; 9642 } 9643 9644 // Consume the argument. 9645 unsigned argIndex = FS.getArgIndex(); 9646 if (argIndex < NumDataArgs) { 9647 // The check to see if the argIndex is valid will come later. 9648 // We set the bit here because we may exit early from this 9649 // function if we encounter some other error. 9650 CoveredArgs.set(argIndex); 9651 } 9652 9653 // Check the length modifier is valid with the given conversion specifier. 9654 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9655 S.getLangOpts())) 9656 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9657 diag::warn_format_nonsensical_length); 9658 else if (!FS.hasStandardLengthModifier()) 9659 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9660 else if (!FS.hasStandardLengthConversionCombination()) 9661 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9662 diag::warn_format_non_standard_conversion_spec); 9663 9664 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9665 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9666 9667 // The remaining checks depend on the data arguments. 9668 if (HasVAListArg) 9669 return true; 9670 9671 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9672 return false; 9673 9674 // Check that the argument type matches the format specifier. 9675 const Expr *Ex = getDataArg(argIndex); 9676 if (!Ex) 9677 return true; 9678 9679 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9680 9681 if (!AT.isValid()) { 9682 return true; 9683 } 9684 9685 analyze_format_string::ArgType::MatchKind Match = 9686 AT.matchesType(S.Context, Ex->getType()); 9687 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9688 if (Match == analyze_format_string::ArgType::Match) 9689 return true; 9690 9691 ScanfSpecifier fixedFS = FS; 9692 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9693 S.getLangOpts(), S.Context); 9694 9695 unsigned Diag = 9696 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9697 : diag::warn_format_conversion_argument_type_mismatch; 9698 9699 if (Success) { 9700 // Get the fix string from the fixed format specifier. 9701 SmallString<128> buf; 9702 llvm::raw_svector_ostream os(buf); 9703 fixedFS.toString(os); 9704 9705 EmitFormatDiagnostic( 9706 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9707 << Ex->getType() << false << Ex->getSourceRange(), 9708 Ex->getBeginLoc(), 9709 /*IsStringLocation*/ false, 9710 getSpecifierRange(startSpecifier, specifierLen), 9711 FixItHint::CreateReplacement( 9712 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9713 } else { 9714 EmitFormatDiagnostic(S.PDiag(Diag) 9715 << AT.getRepresentativeTypeName(S.Context) 9716 << Ex->getType() << false << Ex->getSourceRange(), 9717 Ex->getBeginLoc(), 9718 /*IsStringLocation*/ false, 9719 getSpecifierRange(startSpecifier, specifierLen)); 9720 } 9721 9722 return true; 9723 } 9724 9725 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9726 const Expr *OrigFormatExpr, 9727 ArrayRef<const Expr *> Args, 9728 bool HasVAListArg, unsigned format_idx, 9729 unsigned firstDataArg, 9730 Sema::FormatStringType Type, 9731 bool inFunctionCall, 9732 Sema::VariadicCallType CallType, 9733 llvm::SmallBitVector &CheckedVarArgs, 9734 UncoveredArgHandler &UncoveredArg, 9735 bool IgnoreStringsWithoutSpecifiers) { 9736 // CHECK: is the format string a wide literal? 9737 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9738 CheckFormatHandler::EmitFormatDiagnostic( 9739 S, inFunctionCall, Args[format_idx], 9740 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9741 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9742 return; 9743 } 9744 9745 // Str - The format string. NOTE: this is NOT null-terminated! 9746 StringRef StrRef = FExpr->getString(); 9747 const char *Str = StrRef.data(); 9748 // Account for cases where the string literal is truncated in a declaration. 9749 const ConstantArrayType *T = 9750 S.Context.getAsConstantArrayType(FExpr->getType()); 9751 assert(T && "String literal not of constant array type!"); 9752 size_t TypeSize = T->getSize().getZExtValue(); 9753 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9754 const unsigned numDataArgs = Args.size() - firstDataArg; 9755 9756 if (IgnoreStringsWithoutSpecifiers && 9757 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9758 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9759 return; 9760 9761 // Emit a warning if the string literal is truncated and does not contain an 9762 // embedded null character. 9763 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) { 9764 CheckFormatHandler::EmitFormatDiagnostic( 9765 S, inFunctionCall, Args[format_idx], 9766 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9767 FExpr->getBeginLoc(), 9768 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9769 return; 9770 } 9771 9772 // CHECK: empty format string? 9773 if (StrLen == 0 && numDataArgs > 0) { 9774 CheckFormatHandler::EmitFormatDiagnostic( 9775 S, inFunctionCall, Args[format_idx], 9776 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9777 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9778 return; 9779 } 9780 9781 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9782 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9783 Type == Sema::FST_OSTrace) { 9784 CheckPrintfHandler H( 9785 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9786 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9787 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9788 CheckedVarArgs, UncoveredArg); 9789 9790 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9791 S.getLangOpts(), 9792 S.Context.getTargetInfo(), 9793 Type == Sema::FST_FreeBSDKPrintf)) 9794 H.DoneProcessing(); 9795 } else if (Type == Sema::FST_Scanf) { 9796 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9797 numDataArgs, Str, HasVAListArg, Args, format_idx, 9798 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9799 9800 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9801 S.getLangOpts(), 9802 S.Context.getTargetInfo())) 9803 H.DoneProcessing(); 9804 } // TODO: handle other formats 9805 } 9806 9807 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9808 // Str - The format string. NOTE: this is NOT null-terminated! 9809 StringRef StrRef = FExpr->getString(); 9810 const char *Str = StrRef.data(); 9811 // Account for cases where the string literal is truncated in a declaration. 9812 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9813 assert(T && "String literal not of constant array type!"); 9814 size_t TypeSize = T->getSize().getZExtValue(); 9815 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9816 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9817 getLangOpts(), 9818 Context.getTargetInfo()); 9819 } 9820 9821 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9822 9823 // Returns the related absolute value function that is larger, of 0 if one 9824 // does not exist. 9825 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9826 switch (AbsFunction) { 9827 default: 9828 return 0; 9829 9830 case Builtin::BI__builtin_abs: 9831 return Builtin::BI__builtin_labs; 9832 case Builtin::BI__builtin_labs: 9833 return Builtin::BI__builtin_llabs; 9834 case Builtin::BI__builtin_llabs: 9835 return 0; 9836 9837 case Builtin::BI__builtin_fabsf: 9838 return Builtin::BI__builtin_fabs; 9839 case Builtin::BI__builtin_fabs: 9840 return Builtin::BI__builtin_fabsl; 9841 case Builtin::BI__builtin_fabsl: 9842 return 0; 9843 9844 case Builtin::BI__builtin_cabsf: 9845 return Builtin::BI__builtin_cabs; 9846 case Builtin::BI__builtin_cabs: 9847 return Builtin::BI__builtin_cabsl; 9848 case Builtin::BI__builtin_cabsl: 9849 return 0; 9850 9851 case Builtin::BIabs: 9852 return Builtin::BIlabs; 9853 case Builtin::BIlabs: 9854 return Builtin::BIllabs; 9855 case Builtin::BIllabs: 9856 return 0; 9857 9858 case Builtin::BIfabsf: 9859 return Builtin::BIfabs; 9860 case Builtin::BIfabs: 9861 return Builtin::BIfabsl; 9862 case Builtin::BIfabsl: 9863 return 0; 9864 9865 case Builtin::BIcabsf: 9866 return Builtin::BIcabs; 9867 case Builtin::BIcabs: 9868 return Builtin::BIcabsl; 9869 case Builtin::BIcabsl: 9870 return 0; 9871 } 9872 } 9873 9874 // Returns the argument type of the absolute value function. 9875 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9876 unsigned AbsType) { 9877 if (AbsType == 0) 9878 return QualType(); 9879 9880 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9881 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9882 if (Error != ASTContext::GE_None) 9883 return QualType(); 9884 9885 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9886 if (!FT) 9887 return QualType(); 9888 9889 if (FT->getNumParams() != 1) 9890 return QualType(); 9891 9892 return FT->getParamType(0); 9893 } 9894 9895 // Returns the best absolute value function, or zero, based on type and 9896 // current absolute value function. 9897 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9898 unsigned AbsFunctionKind) { 9899 unsigned BestKind = 0; 9900 uint64_t ArgSize = Context.getTypeSize(ArgType); 9901 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9902 Kind = getLargerAbsoluteValueFunction(Kind)) { 9903 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9904 if (Context.getTypeSize(ParamType) >= ArgSize) { 9905 if (BestKind == 0) 9906 BestKind = Kind; 9907 else if (Context.hasSameType(ParamType, ArgType)) { 9908 BestKind = Kind; 9909 break; 9910 } 9911 } 9912 } 9913 return BestKind; 9914 } 9915 9916 enum AbsoluteValueKind { 9917 AVK_Integer, 9918 AVK_Floating, 9919 AVK_Complex 9920 }; 9921 9922 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9923 if (T->isIntegralOrEnumerationType()) 9924 return AVK_Integer; 9925 if (T->isRealFloatingType()) 9926 return AVK_Floating; 9927 if (T->isAnyComplexType()) 9928 return AVK_Complex; 9929 9930 llvm_unreachable("Type not integer, floating, or complex"); 9931 } 9932 9933 // Changes the absolute value function to a different type. Preserves whether 9934 // the function is a builtin. 9935 static unsigned changeAbsFunction(unsigned AbsKind, 9936 AbsoluteValueKind ValueKind) { 9937 switch (ValueKind) { 9938 case AVK_Integer: 9939 switch (AbsKind) { 9940 default: 9941 return 0; 9942 case Builtin::BI__builtin_fabsf: 9943 case Builtin::BI__builtin_fabs: 9944 case Builtin::BI__builtin_fabsl: 9945 case Builtin::BI__builtin_cabsf: 9946 case Builtin::BI__builtin_cabs: 9947 case Builtin::BI__builtin_cabsl: 9948 return Builtin::BI__builtin_abs; 9949 case Builtin::BIfabsf: 9950 case Builtin::BIfabs: 9951 case Builtin::BIfabsl: 9952 case Builtin::BIcabsf: 9953 case Builtin::BIcabs: 9954 case Builtin::BIcabsl: 9955 return Builtin::BIabs; 9956 } 9957 case AVK_Floating: 9958 switch (AbsKind) { 9959 default: 9960 return 0; 9961 case Builtin::BI__builtin_abs: 9962 case Builtin::BI__builtin_labs: 9963 case Builtin::BI__builtin_llabs: 9964 case Builtin::BI__builtin_cabsf: 9965 case Builtin::BI__builtin_cabs: 9966 case Builtin::BI__builtin_cabsl: 9967 return Builtin::BI__builtin_fabsf; 9968 case Builtin::BIabs: 9969 case Builtin::BIlabs: 9970 case Builtin::BIllabs: 9971 case Builtin::BIcabsf: 9972 case Builtin::BIcabs: 9973 case Builtin::BIcabsl: 9974 return Builtin::BIfabsf; 9975 } 9976 case AVK_Complex: 9977 switch (AbsKind) { 9978 default: 9979 return 0; 9980 case Builtin::BI__builtin_abs: 9981 case Builtin::BI__builtin_labs: 9982 case Builtin::BI__builtin_llabs: 9983 case Builtin::BI__builtin_fabsf: 9984 case Builtin::BI__builtin_fabs: 9985 case Builtin::BI__builtin_fabsl: 9986 return Builtin::BI__builtin_cabsf; 9987 case Builtin::BIabs: 9988 case Builtin::BIlabs: 9989 case Builtin::BIllabs: 9990 case Builtin::BIfabsf: 9991 case Builtin::BIfabs: 9992 case Builtin::BIfabsl: 9993 return Builtin::BIcabsf; 9994 } 9995 } 9996 llvm_unreachable("Unable to convert function"); 9997 } 9998 9999 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 10000 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 10001 if (!FnInfo) 10002 return 0; 10003 10004 switch (FDecl->getBuiltinID()) { 10005 default: 10006 return 0; 10007 case Builtin::BI__builtin_abs: 10008 case Builtin::BI__builtin_fabs: 10009 case Builtin::BI__builtin_fabsf: 10010 case Builtin::BI__builtin_fabsl: 10011 case Builtin::BI__builtin_labs: 10012 case Builtin::BI__builtin_llabs: 10013 case Builtin::BI__builtin_cabs: 10014 case Builtin::BI__builtin_cabsf: 10015 case Builtin::BI__builtin_cabsl: 10016 case Builtin::BIabs: 10017 case Builtin::BIlabs: 10018 case Builtin::BIllabs: 10019 case Builtin::BIfabs: 10020 case Builtin::BIfabsf: 10021 case Builtin::BIfabsl: 10022 case Builtin::BIcabs: 10023 case Builtin::BIcabsf: 10024 case Builtin::BIcabsl: 10025 return FDecl->getBuiltinID(); 10026 } 10027 llvm_unreachable("Unknown Builtin type"); 10028 } 10029 10030 // If the replacement is valid, emit a note with replacement function. 10031 // Additionally, suggest including the proper header if not already included. 10032 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 10033 unsigned AbsKind, QualType ArgType) { 10034 bool EmitHeaderHint = true; 10035 const char *HeaderName = nullptr; 10036 const char *FunctionName = nullptr; 10037 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 10038 FunctionName = "std::abs"; 10039 if (ArgType->isIntegralOrEnumerationType()) { 10040 HeaderName = "cstdlib"; 10041 } else if (ArgType->isRealFloatingType()) { 10042 HeaderName = "cmath"; 10043 } else { 10044 llvm_unreachable("Invalid Type"); 10045 } 10046 10047 // Lookup all std::abs 10048 if (NamespaceDecl *Std = S.getStdNamespace()) { 10049 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 10050 R.suppressDiagnostics(); 10051 S.LookupQualifiedName(R, Std); 10052 10053 for (const auto *I : R) { 10054 const FunctionDecl *FDecl = nullptr; 10055 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 10056 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 10057 } else { 10058 FDecl = dyn_cast<FunctionDecl>(I); 10059 } 10060 if (!FDecl) 10061 continue; 10062 10063 // Found std::abs(), check that they are the right ones. 10064 if (FDecl->getNumParams() != 1) 10065 continue; 10066 10067 // Check that the parameter type can handle the argument. 10068 QualType ParamType = FDecl->getParamDecl(0)->getType(); 10069 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 10070 S.Context.getTypeSize(ArgType) <= 10071 S.Context.getTypeSize(ParamType)) { 10072 // Found a function, don't need the header hint. 10073 EmitHeaderHint = false; 10074 break; 10075 } 10076 } 10077 } 10078 } else { 10079 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 10080 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 10081 10082 if (HeaderName) { 10083 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 10084 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 10085 R.suppressDiagnostics(); 10086 S.LookupName(R, S.getCurScope()); 10087 10088 if (R.isSingleResult()) { 10089 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 10090 if (FD && FD->getBuiltinID() == AbsKind) { 10091 EmitHeaderHint = false; 10092 } else { 10093 return; 10094 } 10095 } else if (!R.empty()) { 10096 return; 10097 } 10098 } 10099 } 10100 10101 S.Diag(Loc, diag::note_replace_abs_function) 10102 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 10103 10104 if (!HeaderName) 10105 return; 10106 10107 if (!EmitHeaderHint) 10108 return; 10109 10110 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 10111 << FunctionName; 10112 } 10113 10114 template <std::size_t StrLen> 10115 static bool IsStdFunction(const FunctionDecl *FDecl, 10116 const char (&Str)[StrLen]) { 10117 if (!FDecl) 10118 return false; 10119 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 10120 return false; 10121 if (!FDecl->isInStdNamespace()) 10122 return false; 10123 10124 return true; 10125 } 10126 10127 // Warn when using the wrong abs() function. 10128 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 10129 const FunctionDecl *FDecl) { 10130 if (Call->getNumArgs() != 1) 10131 return; 10132 10133 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 10134 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 10135 if (AbsKind == 0 && !IsStdAbs) 10136 return; 10137 10138 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10139 QualType ParamType = Call->getArg(0)->getType(); 10140 10141 // Unsigned types cannot be negative. Suggest removing the absolute value 10142 // function call. 10143 if (ArgType->isUnsignedIntegerType()) { 10144 const char *FunctionName = 10145 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 10146 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 10147 Diag(Call->getExprLoc(), diag::note_remove_abs) 10148 << FunctionName 10149 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 10150 return; 10151 } 10152 10153 // Taking the absolute value of a pointer is very suspicious, they probably 10154 // wanted to index into an array, dereference a pointer, call a function, etc. 10155 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 10156 unsigned DiagType = 0; 10157 if (ArgType->isFunctionType()) 10158 DiagType = 1; 10159 else if (ArgType->isArrayType()) 10160 DiagType = 2; 10161 10162 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 10163 return; 10164 } 10165 10166 // std::abs has overloads which prevent most of the absolute value problems 10167 // from occurring. 10168 if (IsStdAbs) 10169 return; 10170 10171 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 10172 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 10173 10174 // The argument and parameter are the same kind. Check if they are the right 10175 // size. 10176 if (ArgValueKind == ParamValueKind) { 10177 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 10178 return; 10179 10180 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 10181 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 10182 << FDecl << ArgType << ParamType; 10183 10184 if (NewAbsKind == 0) 10185 return; 10186 10187 emitReplacement(*this, Call->getExprLoc(), 10188 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10189 return; 10190 } 10191 10192 // ArgValueKind != ParamValueKind 10193 // The wrong type of absolute value function was used. Attempt to find the 10194 // proper one. 10195 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 10196 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 10197 if (NewAbsKind == 0) 10198 return; 10199 10200 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 10201 << FDecl << ParamValueKind << ArgValueKind; 10202 10203 emitReplacement(*this, Call->getExprLoc(), 10204 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10205 } 10206 10207 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 10208 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 10209 const FunctionDecl *FDecl) { 10210 if (!Call || !FDecl) return; 10211 10212 // Ignore template specializations and macros. 10213 if (inTemplateInstantiation()) return; 10214 if (Call->getExprLoc().isMacroID()) return; 10215 10216 // Only care about the one template argument, two function parameter std::max 10217 if (Call->getNumArgs() != 2) return; 10218 if (!IsStdFunction(FDecl, "max")) return; 10219 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 10220 if (!ArgList) return; 10221 if (ArgList->size() != 1) return; 10222 10223 // Check that template type argument is unsigned integer. 10224 const auto& TA = ArgList->get(0); 10225 if (TA.getKind() != TemplateArgument::Type) return; 10226 QualType ArgType = TA.getAsType(); 10227 if (!ArgType->isUnsignedIntegerType()) return; 10228 10229 // See if either argument is a literal zero. 10230 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 10231 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 10232 if (!MTE) return false; 10233 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 10234 if (!Num) return false; 10235 if (Num->getValue() != 0) return false; 10236 return true; 10237 }; 10238 10239 const Expr *FirstArg = Call->getArg(0); 10240 const Expr *SecondArg = Call->getArg(1); 10241 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 10242 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 10243 10244 // Only warn when exactly one argument is zero. 10245 if (IsFirstArgZero == IsSecondArgZero) return; 10246 10247 SourceRange FirstRange = FirstArg->getSourceRange(); 10248 SourceRange SecondRange = SecondArg->getSourceRange(); 10249 10250 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 10251 10252 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 10253 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 10254 10255 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 10256 SourceRange RemovalRange; 10257 if (IsFirstArgZero) { 10258 RemovalRange = SourceRange(FirstRange.getBegin(), 10259 SecondRange.getBegin().getLocWithOffset(-1)); 10260 } else { 10261 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 10262 SecondRange.getEnd()); 10263 } 10264 10265 Diag(Call->getExprLoc(), diag::note_remove_max_call) 10266 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 10267 << FixItHint::CreateRemoval(RemovalRange); 10268 } 10269 10270 //===--- CHECK: Standard memory functions ---------------------------------===// 10271 10272 /// Takes the expression passed to the size_t parameter of functions 10273 /// such as memcmp, strncat, etc and warns if it's a comparison. 10274 /// 10275 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 10276 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 10277 IdentifierInfo *FnName, 10278 SourceLocation FnLoc, 10279 SourceLocation RParenLoc) { 10280 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 10281 if (!Size) 10282 return false; 10283 10284 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 10285 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 10286 return false; 10287 10288 SourceRange SizeRange = Size->getSourceRange(); 10289 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 10290 << SizeRange << FnName; 10291 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 10292 << FnName 10293 << FixItHint::CreateInsertion( 10294 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 10295 << FixItHint::CreateRemoval(RParenLoc); 10296 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 10297 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 10298 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 10299 ")"); 10300 10301 return true; 10302 } 10303 10304 /// Determine whether the given type is or contains a dynamic class type 10305 /// (e.g., whether it has a vtable). 10306 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 10307 bool &IsContained) { 10308 // Look through array types while ignoring qualifiers. 10309 const Type *Ty = T->getBaseElementTypeUnsafe(); 10310 IsContained = false; 10311 10312 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 10313 RD = RD ? RD->getDefinition() : nullptr; 10314 if (!RD || RD->isInvalidDecl()) 10315 return nullptr; 10316 10317 if (RD->isDynamicClass()) 10318 return RD; 10319 10320 // Check all the fields. If any bases were dynamic, the class is dynamic. 10321 // It's impossible for a class to transitively contain itself by value, so 10322 // infinite recursion is impossible. 10323 for (auto *FD : RD->fields()) { 10324 bool SubContained; 10325 if (const CXXRecordDecl *ContainedRD = 10326 getContainedDynamicClass(FD->getType(), SubContained)) { 10327 IsContained = true; 10328 return ContainedRD; 10329 } 10330 } 10331 10332 return nullptr; 10333 } 10334 10335 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 10336 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 10337 if (Unary->getKind() == UETT_SizeOf) 10338 return Unary; 10339 return nullptr; 10340 } 10341 10342 /// If E is a sizeof expression, returns its argument expression, 10343 /// otherwise returns NULL. 10344 static const Expr *getSizeOfExprArg(const Expr *E) { 10345 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10346 if (!SizeOf->isArgumentType()) 10347 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 10348 return nullptr; 10349 } 10350 10351 /// If E is a sizeof expression, returns its argument type. 10352 static QualType getSizeOfArgType(const Expr *E) { 10353 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10354 return SizeOf->getTypeOfArgument(); 10355 return QualType(); 10356 } 10357 10358 namespace { 10359 10360 struct SearchNonTrivialToInitializeField 10361 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 10362 using Super = 10363 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 10364 10365 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 10366 10367 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 10368 SourceLocation SL) { 10369 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10370 asDerived().visitArray(PDIK, AT, SL); 10371 return; 10372 } 10373 10374 Super::visitWithKind(PDIK, FT, SL); 10375 } 10376 10377 void visitARCStrong(QualType FT, SourceLocation SL) { 10378 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10379 } 10380 void visitARCWeak(QualType FT, SourceLocation SL) { 10381 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10382 } 10383 void visitStruct(QualType FT, SourceLocation SL) { 10384 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10385 visit(FD->getType(), FD->getLocation()); 10386 } 10387 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 10388 const ArrayType *AT, SourceLocation SL) { 10389 visit(getContext().getBaseElementType(AT), SL); 10390 } 10391 void visitTrivial(QualType FT, SourceLocation SL) {} 10392 10393 static void diag(QualType RT, const Expr *E, Sema &S) { 10394 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 10395 } 10396 10397 ASTContext &getContext() { return S.getASTContext(); } 10398 10399 const Expr *E; 10400 Sema &S; 10401 }; 10402 10403 struct SearchNonTrivialToCopyField 10404 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 10405 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 10406 10407 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 10408 10409 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 10410 SourceLocation SL) { 10411 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10412 asDerived().visitArray(PCK, AT, SL); 10413 return; 10414 } 10415 10416 Super::visitWithKind(PCK, FT, SL); 10417 } 10418 10419 void visitARCStrong(QualType FT, SourceLocation SL) { 10420 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10421 } 10422 void visitARCWeak(QualType FT, SourceLocation SL) { 10423 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10424 } 10425 void visitStruct(QualType FT, SourceLocation SL) { 10426 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10427 visit(FD->getType(), FD->getLocation()); 10428 } 10429 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 10430 SourceLocation SL) { 10431 visit(getContext().getBaseElementType(AT), SL); 10432 } 10433 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 10434 SourceLocation SL) {} 10435 void visitTrivial(QualType FT, SourceLocation SL) {} 10436 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 10437 10438 static void diag(QualType RT, const Expr *E, Sema &S) { 10439 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 10440 } 10441 10442 ASTContext &getContext() { return S.getASTContext(); } 10443 10444 const Expr *E; 10445 Sema &S; 10446 }; 10447 10448 } 10449 10450 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 10451 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 10452 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 10453 10454 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 10455 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 10456 return false; 10457 10458 return doesExprLikelyComputeSize(BO->getLHS()) || 10459 doesExprLikelyComputeSize(BO->getRHS()); 10460 } 10461 10462 return getAsSizeOfExpr(SizeofExpr) != nullptr; 10463 } 10464 10465 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 10466 /// 10467 /// \code 10468 /// #define MACRO 0 10469 /// foo(MACRO); 10470 /// foo(0); 10471 /// \endcode 10472 /// 10473 /// This should return true for the first call to foo, but not for the second 10474 /// (regardless of whether foo is a macro or function). 10475 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10476 SourceLocation CallLoc, 10477 SourceLocation ArgLoc) { 10478 if (!CallLoc.isMacroID()) 10479 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10480 10481 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10482 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10483 } 10484 10485 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10486 /// last two arguments transposed. 10487 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10488 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10489 return; 10490 10491 const Expr *SizeArg = 10492 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10493 10494 auto isLiteralZero = [](const Expr *E) { 10495 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10496 }; 10497 10498 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10499 SourceLocation CallLoc = Call->getRParenLoc(); 10500 SourceManager &SM = S.getSourceManager(); 10501 if (isLiteralZero(SizeArg) && 10502 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10503 10504 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10505 10506 // Some platforms #define bzero to __builtin_memset. See if this is the 10507 // case, and if so, emit a better diagnostic. 10508 if (BId == Builtin::BIbzero || 10509 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10510 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10511 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10512 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10513 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10514 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10515 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10516 } 10517 return; 10518 } 10519 10520 // If the second argument to a memset is a sizeof expression and the third 10521 // isn't, this is also likely an error. This should catch 10522 // 'memset(buf, sizeof(buf), 0xff)'. 10523 if (BId == Builtin::BImemset && 10524 doesExprLikelyComputeSize(Call->getArg(1)) && 10525 !doesExprLikelyComputeSize(Call->getArg(2))) { 10526 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10527 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10528 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10529 return; 10530 } 10531 } 10532 10533 /// Check for dangerous or invalid arguments to memset(). 10534 /// 10535 /// This issues warnings on known problematic, dangerous or unspecified 10536 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10537 /// function calls. 10538 /// 10539 /// \param Call The call expression to diagnose. 10540 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10541 unsigned BId, 10542 IdentifierInfo *FnName) { 10543 assert(BId != 0); 10544 10545 // It is possible to have a non-standard definition of memset. Validate 10546 // we have enough arguments, and if not, abort further checking. 10547 unsigned ExpectedNumArgs = 10548 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10549 if (Call->getNumArgs() < ExpectedNumArgs) 10550 return; 10551 10552 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10553 BId == Builtin::BIstrndup ? 1 : 2); 10554 unsigned LenArg = 10555 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10556 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10557 10558 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10559 Call->getBeginLoc(), Call->getRParenLoc())) 10560 return; 10561 10562 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10563 CheckMemaccessSize(*this, BId, Call); 10564 10565 // We have special checking when the length is a sizeof expression. 10566 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10567 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10568 llvm::FoldingSetNodeID SizeOfArgID; 10569 10570 // Although widely used, 'bzero' is not a standard function. Be more strict 10571 // with the argument types before allowing diagnostics and only allow the 10572 // form bzero(ptr, sizeof(...)). 10573 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10574 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10575 return; 10576 10577 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10578 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10579 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10580 10581 QualType DestTy = Dest->getType(); 10582 QualType PointeeTy; 10583 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10584 PointeeTy = DestPtrTy->getPointeeType(); 10585 10586 // Never warn about void type pointers. This can be used to suppress 10587 // false positives. 10588 if (PointeeTy->isVoidType()) 10589 continue; 10590 10591 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10592 // actually comparing the expressions for equality. Because computing the 10593 // expression IDs can be expensive, we only do this if the diagnostic is 10594 // enabled. 10595 if (SizeOfArg && 10596 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10597 SizeOfArg->getExprLoc())) { 10598 // We only compute IDs for expressions if the warning is enabled, and 10599 // cache the sizeof arg's ID. 10600 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10601 SizeOfArg->Profile(SizeOfArgID, Context, true); 10602 llvm::FoldingSetNodeID DestID; 10603 Dest->Profile(DestID, Context, true); 10604 if (DestID == SizeOfArgID) { 10605 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10606 // over sizeof(src) as well. 10607 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10608 StringRef ReadableName = FnName->getName(); 10609 10610 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10611 if (UnaryOp->getOpcode() == UO_AddrOf) 10612 ActionIdx = 1; // If its an address-of operator, just remove it. 10613 if (!PointeeTy->isIncompleteType() && 10614 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10615 ActionIdx = 2; // If the pointee's size is sizeof(char), 10616 // suggest an explicit length. 10617 10618 // If the function is defined as a builtin macro, do not show macro 10619 // expansion. 10620 SourceLocation SL = SizeOfArg->getExprLoc(); 10621 SourceRange DSR = Dest->getSourceRange(); 10622 SourceRange SSR = SizeOfArg->getSourceRange(); 10623 SourceManager &SM = getSourceManager(); 10624 10625 if (SM.isMacroArgExpansion(SL)) { 10626 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10627 SL = SM.getSpellingLoc(SL); 10628 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10629 SM.getSpellingLoc(DSR.getEnd())); 10630 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10631 SM.getSpellingLoc(SSR.getEnd())); 10632 } 10633 10634 DiagRuntimeBehavior(SL, SizeOfArg, 10635 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10636 << ReadableName 10637 << PointeeTy 10638 << DestTy 10639 << DSR 10640 << SSR); 10641 DiagRuntimeBehavior(SL, SizeOfArg, 10642 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10643 << ActionIdx 10644 << SSR); 10645 10646 break; 10647 } 10648 } 10649 10650 // Also check for cases where the sizeof argument is the exact same 10651 // type as the memory argument, and where it points to a user-defined 10652 // record type. 10653 if (SizeOfArgTy != QualType()) { 10654 if (PointeeTy->isRecordType() && 10655 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10656 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10657 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10658 << FnName << SizeOfArgTy << ArgIdx 10659 << PointeeTy << Dest->getSourceRange() 10660 << LenExpr->getSourceRange()); 10661 break; 10662 } 10663 } 10664 } else if (DestTy->isArrayType()) { 10665 PointeeTy = DestTy; 10666 } 10667 10668 if (PointeeTy == QualType()) 10669 continue; 10670 10671 // Always complain about dynamic classes. 10672 bool IsContained; 10673 if (const CXXRecordDecl *ContainedRD = 10674 getContainedDynamicClass(PointeeTy, IsContained)) { 10675 10676 unsigned OperationType = 0; 10677 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10678 // "overwritten" if we're warning about the destination for any call 10679 // but memcmp; otherwise a verb appropriate to the call. 10680 if (ArgIdx != 0 || IsCmp) { 10681 if (BId == Builtin::BImemcpy) 10682 OperationType = 1; 10683 else if(BId == Builtin::BImemmove) 10684 OperationType = 2; 10685 else if (IsCmp) 10686 OperationType = 3; 10687 } 10688 10689 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10690 PDiag(diag::warn_dyn_class_memaccess) 10691 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10692 << IsContained << ContainedRD << OperationType 10693 << Call->getCallee()->getSourceRange()); 10694 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10695 BId != Builtin::BImemset) 10696 DiagRuntimeBehavior( 10697 Dest->getExprLoc(), Dest, 10698 PDiag(diag::warn_arc_object_memaccess) 10699 << ArgIdx << FnName << PointeeTy 10700 << Call->getCallee()->getSourceRange()); 10701 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10702 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10703 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10704 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10705 PDiag(diag::warn_cstruct_memaccess) 10706 << ArgIdx << FnName << PointeeTy << 0); 10707 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10708 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10709 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10710 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10711 PDiag(diag::warn_cstruct_memaccess) 10712 << ArgIdx << FnName << PointeeTy << 1); 10713 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10714 } else { 10715 continue; 10716 } 10717 } else 10718 continue; 10719 10720 DiagRuntimeBehavior( 10721 Dest->getExprLoc(), Dest, 10722 PDiag(diag::note_bad_memaccess_silence) 10723 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10724 break; 10725 } 10726 } 10727 10728 // A little helper routine: ignore addition and subtraction of integer literals. 10729 // This intentionally does not ignore all integer constant expressions because 10730 // we don't want to remove sizeof(). 10731 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10732 Ex = Ex->IgnoreParenCasts(); 10733 10734 while (true) { 10735 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10736 if (!BO || !BO->isAdditiveOp()) 10737 break; 10738 10739 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10740 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10741 10742 if (isa<IntegerLiteral>(RHS)) 10743 Ex = LHS; 10744 else if (isa<IntegerLiteral>(LHS)) 10745 Ex = RHS; 10746 else 10747 break; 10748 } 10749 10750 return Ex; 10751 } 10752 10753 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10754 ASTContext &Context) { 10755 // Only handle constant-sized or VLAs, but not flexible members. 10756 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10757 // Only issue the FIXIT for arrays of size > 1. 10758 if (CAT->getSize().getSExtValue() <= 1) 10759 return false; 10760 } else if (!Ty->isVariableArrayType()) { 10761 return false; 10762 } 10763 return true; 10764 } 10765 10766 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10767 // be the size of the source, instead of the destination. 10768 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10769 IdentifierInfo *FnName) { 10770 10771 // Don't crash if the user has the wrong number of arguments 10772 unsigned NumArgs = Call->getNumArgs(); 10773 if ((NumArgs != 3) && (NumArgs != 4)) 10774 return; 10775 10776 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10777 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10778 const Expr *CompareWithSrc = nullptr; 10779 10780 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10781 Call->getBeginLoc(), Call->getRParenLoc())) 10782 return; 10783 10784 // Look for 'strlcpy(dst, x, sizeof(x))' 10785 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10786 CompareWithSrc = Ex; 10787 else { 10788 // Look for 'strlcpy(dst, x, strlen(x))' 10789 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10790 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10791 SizeCall->getNumArgs() == 1) 10792 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10793 } 10794 } 10795 10796 if (!CompareWithSrc) 10797 return; 10798 10799 // Determine if the argument to sizeof/strlen is equal to the source 10800 // argument. In principle there's all kinds of things you could do 10801 // here, for instance creating an == expression and evaluating it with 10802 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10803 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10804 if (!SrcArgDRE) 10805 return; 10806 10807 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10808 if (!CompareWithSrcDRE || 10809 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10810 return; 10811 10812 const Expr *OriginalSizeArg = Call->getArg(2); 10813 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10814 << OriginalSizeArg->getSourceRange() << FnName; 10815 10816 // Output a FIXIT hint if the destination is an array (rather than a 10817 // pointer to an array). This could be enhanced to handle some 10818 // pointers if we know the actual size, like if DstArg is 'array+2' 10819 // we could say 'sizeof(array)-2'. 10820 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10821 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10822 return; 10823 10824 SmallString<128> sizeString; 10825 llvm::raw_svector_ostream OS(sizeString); 10826 OS << "sizeof("; 10827 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10828 OS << ")"; 10829 10830 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10831 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10832 OS.str()); 10833 } 10834 10835 /// Check if two expressions refer to the same declaration. 10836 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10837 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10838 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10839 return D1->getDecl() == D2->getDecl(); 10840 return false; 10841 } 10842 10843 static const Expr *getStrlenExprArg(const Expr *E) { 10844 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10845 const FunctionDecl *FD = CE->getDirectCallee(); 10846 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10847 return nullptr; 10848 return CE->getArg(0)->IgnoreParenCasts(); 10849 } 10850 return nullptr; 10851 } 10852 10853 // Warn on anti-patterns as the 'size' argument to strncat. 10854 // The correct size argument should look like following: 10855 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10856 void Sema::CheckStrncatArguments(const CallExpr *CE, 10857 IdentifierInfo *FnName) { 10858 // Don't crash if the user has the wrong number of arguments. 10859 if (CE->getNumArgs() < 3) 10860 return; 10861 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10862 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10863 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10864 10865 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10866 CE->getRParenLoc())) 10867 return; 10868 10869 // Identify common expressions, which are wrongly used as the size argument 10870 // to strncat and may lead to buffer overflows. 10871 unsigned PatternType = 0; 10872 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10873 // - sizeof(dst) 10874 if (referToTheSameDecl(SizeOfArg, DstArg)) 10875 PatternType = 1; 10876 // - sizeof(src) 10877 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10878 PatternType = 2; 10879 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10880 if (BE->getOpcode() == BO_Sub) { 10881 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10882 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10883 // - sizeof(dst) - strlen(dst) 10884 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10885 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10886 PatternType = 1; 10887 // - sizeof(src) - (anything) 10888 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10889 PatternType = 2; 10890 } 10891 } 10892 10893 if (PatternType == 0) 10894 return; 10895 10896 // Generate the diagnostic. 10897 SourceLocation SL = LenArg->getBeginLoc(); 10898 SourceRange SR = LenArg->getSourceRange(); 10899 SourceManager &SM = getSourceManager(); 10900 10901 // If the function is defined as a builtin macro, do not show macro expansion. 10902 if (SM.isMacroArgExpansion(SL)) { 10903 SL = SM.getSpellingLoc(SL); 10904 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10905 SM.getSpellingLoc(SR.getEnd())); 10906 } 10907 10908 // Check if the destination is an array (rather than a pointer to an array). 10909 QualType DstTy = DstArg->getType(); 10910 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10911 Context); 10912 if (!isKnownSizeArray) { 10913 if (PatternType == 1) 10914 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10915 else 10916 Diag(SL, diag::warn_strncat_src_size) << SR; 10917 return; 10918 } 10919 10920 if (PatternType == 1) 10921 Diag(SL, diag::warn_strncat_large_size) << SR; 10922 else 10923 Diag(SL, diag::warn_strncat_src_size) << SR; 10924 10925 SmallString<128> sizeString; 10926 llvm::raw_svector_ostream OS(sizeString); 10927 OS << "sizeof("; 10928 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10929 OS << ") - "; 10930 OS << "strlen("; 10931 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10932 OS << ") - 1"; 10933 10934 Diag(SL, diag::note_strncat_wrong_size) 10935 << FixItHint::CreateReplacement(SR, OS.str()); 10936 } 10937 10938 namespace { 10939 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10940 const UnaryOperator *UnaryExpr, const Decl *D) { 10941 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10942 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10943 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10944 return; 10945 } 10946 } 10947 10948 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10949 const UnaryOperator *UnaryExpr) { 10950 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10951 const Decl *D = Lvalue->getDecl(); 10952 if (isa<DeclaratorDecl>(D)) 10953 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType()) 10954 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10955 } 10956 10957 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10958 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10959 Lvalue->getMemberDecl()); 10960 } 10961 10962 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10963 const UnaryOperator *UnaryExpr) { 10964 const auto *Lambda = dyn_cast<LambdaExpr>( 10965 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10966 if (!Lambda) 10967 return; 10968 10969 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 10970 << CalleeName << 2 /*object: lambda expression*/; 10971 } 10972 10973 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10974 const DeclRefExpr *Lvalue) { 10975 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10976 if (Var == nullptr) 10977 return; 10978 10979 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10980 << CalleeName << 0 /*object: */ << Var; 10981 } 10982 10983 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 10984 const CastExpr *Cast) { 10985 SmallString<128> SizeString; 10986 llvm::raw_svector_ostream OS(SizeString); 10987 10988 clang::CastKind Kind = Cast->getCastKind(); 10989 if (Kind == clang::CK_BitCast && 10990 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 10991 return; 10992 if (Kind == clang::CK_IntegralToPointer && 10993 !isa<IntegerLiteral>( 10994 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 10995 return; 10996 10997 switch (Cast->getCastKind()) { 10998 case clang::CK_BitCast: 10999 case clang::CK_IntegralToPointer: 11000 case clang::CK_FunctionToPointerDecay: 11001 OS << '\''; 11002 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 11003 OS << '\''; 11004 break; 11005 default: 11006 return; 11007 } 11008 11009 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 11010 << CalleeName << 0 /*object: */ << OS.str(); 11011 } 11012 } // namespace 11013 11014 /// Alerts the user that they are attempting to free a non-malloc'd object. 11015 void Sema::CheckFreeArguments(const CallExpr *E) { 11016 const std::string CalleeName = 11017 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 11018 11019 { // Prefer something that doesn't involve a cast to make things simpler. 11020 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 11021 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 11022 switch (UnaryExpr->getOpcode()) { 11023 case UnaryOperator::Opcode::UO_AddrOf: 11024 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 11025 case UnaryOperator::Opcode::UO_Plus: 11026 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 11027 default: 11028 break; 11029 } 11030 11031 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 11032 if (Lvalue->getType()->isArrayType()) 11033 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 11034 11035 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 11036 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 11037 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 11038 return; 11039 } 11040 11041 if (isa<BlockExpr>(Arg)) { 11042 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 11043 << CalleeName << 1 /*object: block*/; 11044 return; 11045 } 11046 } 11047 // Maybe the cast was important, check after the other cases. 11048 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 11049 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 11050 } 11051 11052 void 11053 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 11054 SourceLocation ReturnLoc, 11055 bool isObjCMethod, 11056 const AttrVec *Attrs, 11057 const FunctionDecl *FD) { 11058 // Check if the return value is null but should not be. 11059 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 11060 (!isObjCMethod && isNonNullType(Context, lhsType))) && 11061 CheckNonNullExpr(*this, RetValExp)) 11062 Diag(ReturnLoc, diag::warn_null_ret) 11063 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 11064 11065 // C++11 [basic.stc.dynamic.allocation]p4: 11066 // If an allocation function declared with a non-throwing 11067 // exception-specification fails to allocate storage, it shall return 11068 // a null pointer. Any other allocation function that fails to allocate 11069 // storage shall indicate failure only by throwing an exception [...] 11070 if (FD) { 11071 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 11072 if (Op == OO_New || Op == OO_Array_New) { 11073 const FunctionProtoType *Proto 11074 = FD->getType()->castAs<FunctionProtoType>(); 11075 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 11076 CheckNonNullExpr(*this, RetValExp)) 11077 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 11078 << FD << getLangOpts().CPlusPlus11; 11079 } 11080 } 11081 11082 // PPC MMA non-pointer types are not allowed as return type. Checking the type 11083 // here prevent the user from using a PPC MMA type as trailing return type. 11084 if (Context.getTargetInfo().getTriple().isPPC64()) 11085 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 11086 } 11087 11088 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 11089 11090 /// Check for comparisons of floating point operands using != and ==. 11091 /// Issue a warning if these are no self-comparisons, as they are not likely 11092 /// to do what the programmer intended. 11093 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 11094 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 11095 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 11096 11097 // Special case: check for x == x (which is OK). 11098 // Do not emit warnings for such cases. 11099 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 11100 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 11101 if (DRL->getDecl() == DRR->getDecl()) 11102 return; 11103 11104 // Special case: check for comparisons against literals that can be exactly 11105 // represented by APFloat. In such cases, do not emit a warning. This 11106 // is a heuristic: often comparison against such literals are used to 11107 // detect if a value in a variable has not changed. This clearly can 11108 // lead to false negatives. 11109 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 11110 if (FLL->isExact()) 11111 return; 11112 } else 11113 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 11114 if (FLR->isExact()) 11115 return; 11116 11117 // Check for comparisons with builtin types. 11118 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 11119 if (CL->getBuiltinCallee()) 11120 return; 11121 11122 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 11123 if (CR->getBuiltinCallee()) 11124 return; 11125 11126 // Emit the diagnostic. 11127 Diag(Loc, diag::warn_floatingpoint_eq) 11128 << LHS->getSourceRange() << RHS->getSourceRange(); 11129 } 11130 11131 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 11132 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 11133 11134 namespace { 11135 11136 /// Structure recording the 'active' range of an integer-valued 11137 /// expression. 11138 struct IntRange { 11139 /// The number of bits active in the int. Note that this includes exactly one 11140 /// sign bit if !NonNegative. 11141 unsigned Width; 11142 11143 /// True if the int is known not to have negative values. If so, all leading 11144 /// bits before Width are known zero, otherwise they are known to be the 11145 /// same as the MSB within Width. 11146 bool NonNegative; 11147 11148 IntRange(unsigned Width, bool NonNegative) 11149 : Width(Width), NonNegative(NonNegative) {} 11150 11151 /// Number of bits excluding the sign bit. 11152 unsigned valueBits() const { 11153 return NonNegative ? Width : Width - 1; 11154 } 11155 11156 /// Returns the range of the bool type. 11157 static IntRange forBoolType() { 11158 return IntRange(1, true); 11159 } 11160 11161 /// Returns the range of an opaque value of the given integral type. 11162 static IntRange forValueOfType(ASTContext &C, QualType T) { 11163 return forValueOfCanonicalType(C, 11164 T->getCanonicalTypeInternal().getTypePtr()); 11165 } 11166 11167 /// Returns the range of an opaque value of a canonical integral type. 11168 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 11169 assert(T->isCanonicalUnqualified()); 11170 11171 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11172 T = VT->getElementType().getTypePtr(); 11173 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11174 T = CT->getElementType().getTypePtr(); 11175 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11176 T = AT->getValueType().getTypePtr(); 11177 11178 if (!C.getLangOpts().CPlusPlus) { 11179 // For enum types in C code, use the underlying datatype. 11180 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11181 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 11182 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 11183 // For enum types in C++, use the known bit width of the enumerators. 11184 EnumDecl *Enum = ET->getDecl(); 11185 // In C++11, enums can have a fixed underlying type. Use this type to 11186 // compute the range. 11187 if (Enum->isFixed()) { 11188 return IntRange(C.getIntWidth(QualType(T, 0)), 11189 !ET->isSignedIntegerOrEnumerationType()); 11190 } 11191 11192 unsigned NumPositive = Enum->getNumPositiveBits(); 11193 unsigned NumNegative = Enum->getNumNegativeBits(); 11194 11195 if (NumNegative == 0) 11196 return IntRange(NumPositive, true/*NonNegative*/); 11197 else 11198 return IntRange(std::max(NumPositive + 1, NumNegative), 11199 false/*NonNegative*/); 11200 } 11201 11202 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11203 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11204 11205 const BuiltinType *BT = cast<BuiltinType>(T); 11206 assert(BT->isInteger()); 11207 11208 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11209 } 11210 11211 /// Returns the "target" range of a canonical integral type, i.e. 11212 /// the range of values expressible in the type. 11213 /// 11214 /// This matches forValueOfCanonicalType except that enums have the 11215 /// full range of their type, not the range of their enumerators. 11216 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 11217 assert(T->isCanonicalUnqualified()); 11218 11219 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11220 T = VT->getElementType().getTypePtr(); 11221 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11222 T = CT->getElementType().getTypePtr(); 11223 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11224 T = AT->getValueType().getTypePtr(); 11225 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11226 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 11227 11228 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11229 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11230 11231 const BuiltinType *BT = cast<BuiltinType>(T); 11232 assert(BT->isInteger()); 11233 11234 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11235 } 11236 11237 /// Returns the supremum of two ranges: i.e. their conservative merge. 11238 static IntRange join(IntRange L, IntRange R) { 11239 bool Unsigned = L.NonNegative && R.NonNegative; 11240 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 11241 L.NonNegative && R.NonNegative); 11242 } 11243 11244 /// Return the range of a bitwise-AND of the two ranges. 11245 static IntRange bit_and(IntRange L, IntRange R) { 11246 unsigned Bits = std::max(L.Width, R.Width); 11247 bool NonNegative = false; 11248 if (L.NonNegative) { 11249 Bits = std::min(Bits, L.Width); 11250 NonNegative = true; 11251 } 11252 if (R.NonNegative) { 11253 Bits = std::min(Bits, R.Width); 11254 NonNegative = true; 11255 } 11256 return IntRange(Bits, NonNegative); 11257 } 11258 11259 /// Return the range of a sum of the two ranges. 11260 static IntRange sum(IntRange L, IntRange R) { 11261 bool Unsigned = L.NonNegative && R.NonNegative; 11262 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 11263 Unsigned); 11264 } 11265 11266 /// Return the range of a difference of the two ranges. 11267 static IntRange difference(IntRange L, IntRange R) { 11268 // We need a 1-bit-wider range if: 11269 // 1) LHS can be negative: least value can be reduced. 11270 // 2) RHS can be negative: greatest value can be increased. 11271 bool CanWiden = !L.NonNegative || !R.NonNegative; 11272 bool Unsigned = L.NonNegative && R.Width == 0; 11273 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 11274 !Unsigned, 11275 Unsigned); 11276 } 11277 11278 /// Return the range of a product of the two ranges. 11279 static IntRange product(IntRange L, IntRange R) { 11280 // If both LHS and RHS can be negative, we can form 11281 // -2^L * -2^R = 2^(L + R) 11282 // which requires L + R + 1 value bits to represent. 11283 bool CanWiden = !L.NonNegative && !R.NonNegative; 11284 bool Unsigned = L.NonNegative && R.NonNegative; 11285 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 11286 Unsigned); 11287 } 11288 11289 /// Return the range of a remainder operation between the two ranges. 11290 static IntRange rem(IntRange L, IntRange R) { 11291 // The result of a remainder can't be larger than the result of 11292 // either side. The sign of the result is the sign of the LHS. 11293 bool Unsigned = L.NonNegative; 11294 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 11295 Unsigned); 11296 } 11297 }; 11298 11299 } // namespace 11300 11301 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 11302 unsigned MaxWidth) { 11303 if (value.isSigned() && value.isNegative()) 11304 return IntRange(value.getMinSignedBits(), false); 11305 11306 if (value.getBitWidth() > MaxWidth) 11307 value = value.trunc(MaxWidth); 11308 11309 // isNonNegative() just checks the sign bit without considering 11310 // signedness. 11311 return IntRange(value.getActiveBits(), true); 11312 } 11313 11314 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 11315 unsigned MaxWidth) { 11316 if (result.isInt()) 11317 return GetValueRange(C, result.getInt(), MaxWidth); 11318 11319 if (result.isVector()) { 11320 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 11321 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 11322 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 11323 R = IntRange::join(R, El); 11324 } 11325 return R; 11326 } 11327 11328 if (result.isComplexInt()) { 11329 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 11330 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 11331 return IntRange::join(R, I); 11332 } 11333 11334 // This can happen with lossless casts to intptr_t of "based" lvalues. 11335 // Assume it might use arbitrary bits. 11336 // FIXME: The only reason we need to pass the type in here is to get 11337 // the sign right on this one case. It would be nice if APValue 11338 // preserved this. 11339 assert(result.isLValue() || result.isAddrLabelDiff()); 11340 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 11341 } 11342 11343 static QualType GetExprType(const Expr *E) { 11344 QualType Ty = E->getType(); 11345 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 11346 Ty = AtomicRHS->getValueType(); 11347 return Ty; 11348 } 11349 11350 /// Pseudo-evaluate the given integer expression, estimating the 11351 /// range of values it might take. 11352 /// 11353 /// \param MaxWidth The width to which the value will be truncated. 11354 /// \param Approximate If \c true, return a likely range for the result: in 11355 /// particular, assume that arithmetic on narrower types doesn't leave 11356 /// those types. If \c false, return a range including all possible 11357 /// result values. 11358 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 11359 bool InConstantContext, bool Approximate) { 11360 E = E->IgnoreParens(); 11361 11362 // Try a full evaluation first. 11363 Expr::EvalResult result; 11364 if (E->EvaluateAsRValue(result, C, InConstantContext)) 11365 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 11366 11367 // I think we only want to look through implicit casts here; if the 11368 // user has an explicit widening cast, we should treat the value as 11369 // being of the new, wider type. 11370 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 11371 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 11372 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 11373 Approximate); 11374 11375 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 11376 11377 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 11378 CE->getCastKind() == CK_BooleanToSignedIntegral; 11379 11380 // Assume that non-integer casts can span the full range of the type. 11381 if (!isIntegerCast) 11382 return OutputTypeRange; 11383 11384 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 11385 std::min(MaxWidth, OutputTypeRange.Width), 11386 InConstantContext, Approximate); 11387 11388 // Bail out if the subexpr's range is as wide as the cast type. 11389 if (SubRange.Width >= OutputTypeRange.Width) 11390 return OutputTypeRange; 11391 11392 // Otherwise, we take the smaller width, and we're non-negative if 11393 // either the output type or the subexpr is. 11394 return IntRange(SubRange.Width, 11395 SubRange.NonNegative || OutputTypeRange.NonNegative); 11396 } 11397 11398 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11399 // If we can fold the condition, just take that operand. 11400 bool CondResult; 11401 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 11402 return GetExprRange(C, 11403 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 11404 MaxWidth, InConstantContext, Approximate); 11405 11406 // Otherwise, conservatively merge. 11407 // GetExprRange requires an integer expression, but a throw expression 11408 // results in a void type. 11409 Expr *E = CO->getTrueExpr(); 11410 IntRange L = E->getType()->isVoidType() 11411 ? IntRange{0, true} 11412 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11413 E = CO->getFalseExpr(); 11414 IntRange R = E->getType()->isVoidType() 11415 ? IntRange{0, true} 11416 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11417 return IntRange::join(L, R); 11418 } 11419 11420 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11421 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 11422 11423 switch (BO->getOpcode()) { 11424 case BO_Cmp: 11425 llvm_unreachable("builtin <=> should have class type"); 11426 11427 // Boolean-valued operations are single-bit and positive. 11428 case BO_LAnd: 11429 case BO_LOr: 11430 case BO_LT: 11431 case BO_GT: 11432 case BO_LE: 11433 case BO_GE: 11434 case BO_EQ: 11435 case BO_NE: 11436 return IntRange::forBoolType(); 11437 11438 // The type of the assignments is the type of the LHS, so the RHS 11439 // is not necessarily the same type. 11440 case BO_MulAssign: 11441 case BO_DivAssign: 11442 case BO_RemAssign: 11443 case BO_AddAssign: 11444 case BO_SubAssign: 11445 case BO_XorAssign: 11446 case BO_OrAssign: 11447 // TODO: bitfields? 11448 return IntRange::forValueOfType(C, GetExprType(E)); 11449 11450 // Simple assignments just pass through the RHS, which will have 11451 // been coerced to the LHS type. 11452 case BO_Assign: 11453 // TODO: bitfields? 11454 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11455 Approximate); 11456 11457 // Operations with opaque sources are black-listed. 11458 case BO_PtrMemD: 11459 case BO_PtrMemI: 11460 return IntRange::forValueOfType(C, GetExprType(E)); 11461 11462 // Bitwise-and uses the *infinum* of the two source ranges. 11463 case BO_And: 11464 case BO_AndAssign: 11465 Combine = IntRange::bit_and; 11466 break; 11467 11468 // Left shift gets black-listed based on a judgement call. 11469 case BO_Shl: 11470 // ...except that we want to treat '1 << (blah)' as logically 11471 // positive. It's an important idiom. 11472 if (IntegerLiteral *I 11473 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11474 if (I->getValue() == 1) { 11475 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11476 return IntRange(R.Width, /*NonNegative*/ true); 11477 } 11478 } 11479 LLVM_FALLTHROUGH; 11480 11481 case BO_ShlAssign: 11482 return IntRange::forValueOfType(C, GetExprType(E)); 11483 11484 // Right shift by a constant can narrow its left argument. 11485 case BO_Shr: 11486 case BO_ShrAssign: { 11487 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11488 Approximate); 11489 11490 // If the shift amount is a positive constant, drop the width by 11491 // that much. 11492 if (Optional<llvm::APSInt> shift = 11493 BO->getRHS()->getIntegerConstantExpr(C)) { 11494 if (shift->isNonNegative()) { 11495 unsigned zext = shift->getZExtValue(); 11496 if (zext >= L.Width) 11497 L.Width = (L.NonNegative ? 0 : 1); 11498 else 11499 L.Width -= zext; 11500 } 11501 } 11502 11503 return L; 11504 } 11505 11506 // Comma acts as its right operand. 11507 case BO_Comma: 11508 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11509 Approximate); 11510 11511 case BO_Add: 11512 if (!Approximate) 11513 Combine = IntRange::sum; 11514 break; 11515 11516 case BO_Sub: 11517 if (BO->getLHS()->getType()->isPointerType()) 11518 return IntRange::forValueOfType(C, GetExprType(E)); 11519 if (!Approximate) 11520 Combine = IntRange::difference; 11521 break; 11522 11523 case BO_Mul: 11524 if (!Approximate) 11525 Combine = IntRange::product; 11526 break; 11527 11528 // The width of a division result is mostly determined by the size 11529 // of the LHS. 11530 case BO_Div: { 11531 // Don't 'pre-truncate' the operands. 11532 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11533 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11534 Approximate); 11535 11536 // If the divisor is constant, use that. 11537 if (Optional<llvm::APSInt> divisor = 11538 BO->getRHS()->getIntegerConstantExpr(C)) { 11539 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11540 if (log2 >= L.Width) 11541 L.Width = (L.NonNegative ? 0 : 1); 11542 else 11543 L.Width = std::min(L.Width - log2, MaxWidth); 11544 return L; 11545 } 11546 11547 // Otherwise, just use the LHS's width. 11548 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11549 // could be -1. 11550 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11551 Approximate); 11552 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11553 } 11554 11555 case BO_Rem: 11556 Combine = IntRange::rem; 11557 break; 11558 11559 // The default behavior is okay for these. 11560 case BO_Xor: 11561 case BO_Or: 11562 break; 11563 } 11564 11565 // Combine the two ranges, but limit the result to the type in which we 11566 // performed the computation. 11567 QualType T = GetExprType(E); 11568 unsigned opWidth = C.getIntWidth(T); 11569 IntRange L = 11570 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11571 IntRange R = 11572 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11573 IntRange C = Combine(L, R); 11574 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11575 C.Width = std::min(C.Width, MaxWidth); 11576 return C; 11577 } 11578 11579 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11580 switch (UO->getOpcode()) { 11581 // Boolean-valued operations are white-listed. 11582 case UO_LNot: 11583 return IntRange::forBoolType(); 11584 11585 // Operations with opaque sources are black-listed. 11586 case UO_Deref: 11587 case UO_AddrOf: // should be impossible 11588 return IntRange::forValueOfType(C, GetExprType(E)); 11589 11590 default: 11591 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11592 Approximate); 11593 } 11594 } 11595 11596 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11597 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11598 Approximate); 11599 11600 if (const auto *BitField = E->getSourceBitField()) 11601 return IntRange(BitField->getBitWidthValue(C), 11602 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11603 11604 return IntRange::forValueOfType(C, GetExprType(E)); 11605 } 11606 11607 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11608 bool InConstantContext, bool Approximate) { 11609 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11610 Approximate); 11611 } 11612 11613 /// Checks whether the given value, which currently has the given 11614 /// source semantics, has the same value when coerced through the 11615 /// target semantics. 11616 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11617 const llvm::fltSemantics &Src, 11618 const llvm::fltSemantics &Tgt) { 11619 llvm::APFloat truncated = value; 11620 11621 bool ignored; 11622 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11623 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11624 11625 return truncated.bitwiseIsEqual(value); 11626 } 11627 11628 /// Checks whether the given value, which currently has the given 11629 /// source semantics, has the same value when coerced through the 11630 /// target semantics. 11631 /// 11632 /// The value might be a vector of floats (or a complex number). 11633 static bool IsSameFloatAfterCast(const APValue &value, 11634 const llvm::fltSemantics &Src, 11635 const llvm::fltSemantics &Tgt) { 11636 if (value.isFloat()) 11637 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11638 11639 if (value.isVector()) { 11640 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11641 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11642 return false; 11643 return true; 11644 } 11645 11646 assert(value.isComplexFloat()); 11647 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11648 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11649 } 11650 11651 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11652 bool IsListInit = false); 11653 11654 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11655 // Suppress cases where we are comparing against an enum constant. 11656 if (const DeclRefExpr *DR = 11657 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11658 if (isa<EnumConstantDecl>(DR->getDecl())) 11659 return true; 11660 11661 // Suppress cases where the value is expanded from a macro, unless that macro 11662 // is how a language represents a boolean literal. This is the case in both C 11663 // and Objective-C. 11664 SourceLocation BeginLoc = E->getBeginLoc(); 11665 if (BeginLoc.isMacroID()) { 11666 StringRef MacroName = Lexer::getImmediateMacroName( 11667 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11668 return MacroName != "YES" && MacroName != "NO" && 11669 MacroName != "true" && MacroName != "false"; 11670 } 11671 11672 return false; 11673 } 11674 11675 static bool isKnownToHaveUnsignedValue(Expr *E) { 11676 return E->getType()->isIntegerType() && 11677 (!E->getType()->isSignedIntegerType() || 11678 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11679 } 11680 11681 namespace { 11682 /// The promoted range of values of a type. In general this has the 11683 /// following structure: 11684 /// 11685 /// |-----------| . . . |-----------| 11686 /// ^ ^ ^ ^ 11687 /// Min HoleMin HoleMax Max 11688 /// 11689 /// ... where there is only a hole if a signed type is promoted to unsigned 11690 /// (in which case Min and Max are the smallest and largest representable 11691 /// values). 11692 struct PromotedRange { 11693 // Min, or HoleMax if there is a hole. 11694 llvm::APSInt PromotedMin; 11695 // Max, or HoleMin if there is a hole. 11696 llvm::APSInt PromotedMax; 11697 11698 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11699 if (R.Width == 0) 11700 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11701 else if (R.Width >= BitWidth && !Unsigned) { 11702 // Promotion made the type *narrower*. This happens when promoting 11703 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11704 // Treat all values of 'signed int' as being in range for now. 11705 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11706 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11707 } else { 11708 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11709 .extOrTrunc(BitWidth); 11710 PromotedMin.setIsUnsigned(Unsigned); 11711 11712 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11713 .extOrTrunc(BitWidth); 11714 PromotedMax.setIsUnsigned(Unsigned); 11715 } 11716 } 11717 11718 // Determine whether this range is contiguous (has no hole). 11719 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11720 11721 // Where a constant value is within the range. 11722 enum ComparisonResult { 11723 LT = 0x1, 11724 LE = 0x2, 11725 GT = 0x4, 11726 GE = 0x8, 11727 EQ = 0x10, 11728 NE = 0x20, 11729 InRangeFlag = 0x40, 11730 11731 Less = LE | LT | NE, 11732 Min = LE | InRangeFlag, 11733 InRange = InRangeFlag, 11734 Max = GE | InRangeFlag, 11735 Greater = GE | GT | NE, 11736 11737 OnlyValue = LE | GE | EQ | InRangeFlag, 11738 InHole = NE 11739 }; 11740 11741 ComparisonResult compare(const llvm::APSInt &Value) const { 11742 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11743 Value.isUnsigned() == PromotedMin.isUnsigned()); 11744 if (!isContiguous()) { 11745 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11746 if (Value.isMinValue()) return Min; 11747 if (Value.isMaxValue()) return Max; 11748 if (Value >= PromotedMin) return InRange; 11749 if (Value <= PromotedMax) return InRange; 11750 return InHole; 11751 } 11752 11753 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11754 case -1: return Less; 11755 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11756 case 1: 11757 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11758 case -1: return InRange; 11759 case 0: return Max; 11760 case 1: return Greater; 11761 } 11762 } 11763 11764 llvm_unreachable("impossible compare result"); 11765 } 11766 11767 static llvm::Optional<StringRef> 11768 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11769 if (Op == BO_Cmp) { 11770 ComparisonResult LTFlag = LT, GTFlag = GT; 11771 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11772 11773 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11774 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11775 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11776 return llvm::None; 11777 } 11778 11779 ComparisonResult TrueFlag, FalseFlag; 11780 if (Op == BO_EQ) { 11781 TrueFlag = EQ; 11782 FalseFlag = NE; 11783 } else if (Op == BO_NE) { 11784 TrueFlag = NE; 11785 FalseFlag = EQ; 11786 } else { 11787 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11788 TrueFlag = LT; 11789 FalseFlag = GE; 11790 } else { 11791 TrueFlag = GT; 11792 FalseFlag = LE; 11793 } 11794 if (Op == BO_GE || Op == BO_LE) 11795 std::swap(TrueFlag, FalseFlag); 11796 } 11797 if (R & TrueFlag) 11798 return StringRef("true"); 11799 if (R & FalseFlag) 11800 return StringRef("false"); 11801 return llvm::None; 11802 } 11803 }; 11804 } 11805 11806 static bool HasEnumType(Expr *E) { 11807 // Strip off implicit integral promotions. 11808 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11809 if (ICE->getCastKind() != CK_IntegralCast && 11810 ICE->getCastKind() != CK_NoOp) 11811 break; 11812 E = ICE->getSubExpr(); 11813 } 11814 11815 return E->getType()->isEnumeralType(); 11816 } 11817 11818 static int classifyConstantValue(Expr *Constant) { 11819 // The values of this enumeration are used in the diagnostics 11820 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11821 enum ConstantValueKind { 11822 Miscellaneous = 0, 11823 LiteralTrue, 11824 LiteralFalse 11825 }; 11826 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11827 return BL->getValue() ? ConstantValueKind::LiteralTrue 11828 : ConstantValueKind::LiteralFalse; 11829 return ConstantValueKind::Miscellaneous; 11830 } 11831 11832 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11833 Expr *Constant, Expr *Other, 11834 const llvm::APSInt &Value, 11835 bool RhsConstant) { 11836 if (S.inTemplateInstantiation()) 11837 return false; 11838 11839 Expr *OriginalOther = Other; 11840 11841 Constant = Constant->IgnoreParenImpCasts(); 11842 Other = Other->IgnoreParenImpCasts(); 11843 11844 // Suppress warnings on tautological comparisons between values of the same 11845 // enumeration type. There are only two ways we could warn on this: 11846 // - If the constant is outside the range of representable values of 11847 // the enumeration. In such a case, we should warn about the cast 11848 // to enumeration type, not about the comparison. 11849 // - If the constant is the maximum / minimum in-range value. For an 11850 // enumeratin type, such comparisons can be meaningful and useful. 11851 if (Constant->getType()->isEnumeralType() && 11852 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11853 return false; 11854 11855 IntRange OtherValueRange = GetExprRange( 11856 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11857 11858 QualType OtherT = Other->getType(); 11859 if (const auto *AT = OtherT->getAs<AtomicType>()) 11860 OtherT = AT->getValueType(); 11861 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11862 11863 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11864 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11865 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11866 S.NSAPIObj->isObjCBOOLType(OtherT) && 11867 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11868 11869 // Whether we're treating Other as being a bool because of the form of 11870 // expression despite it having another type (typically 'int' in C). 11871 bool OtherIsBooleanDespiteType = 11872 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11873 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11874 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11875 11876 // Check if all values in the range of possible values of this expression 11877 // lead to the same comparison outcome. 11878 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11879 Value.isUnsigned()); 11880 auto Cmp = OtherPromotedValueRange.compare(Value); 11881 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11882 if (!Result) 11883 return false; 11884 11885 // Also consider the range determined by the type alone. This allows us to 11886 // classify the warning under the proper diagnostic group. 11887 bool TautologicalTypeCompare = false; 11888 { 11889 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11890 Value.isUnsigned()); 11891 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11892 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11893 RhsConstant)) { 11894 TautologicalTypeCompare = true; 11895 Cmp = TypeCmp; 11896 Result = TypeResult; 11897 } 11898 } 11899 11900 // Don't warn if the non-constant operand actually always evaluates to the 11901 // same value. 11902 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11903 return false; 11904 11905 // Suppress the diagnostic for an in-range comparison if the constant comes 11906 // from a macro or enumerator. We don't want to diagnose 11907 // 11908 // some_long_value <= INT_MAX 11909 // 11910 // when sizeof(int) == sizeof(long). 11911 bool InRange = Cmp & PromotedRange::InRangeFlag; 11912 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11913 return false; 11914 11915 // A comparison of an unsigned bit-field against 0 is really a type problem, 11916 // even though at the type level the bit-field might promote to 'signed int'. 11917 if (Other->refersToBitField() && InRange && Value == 0 && 11918 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11919 TautologicalTypeCompare = true; 11920 11921 // If this is a comparison to an enum constant, include that 11922 // constant in the diagnostic. 11923 const EnumConstantDecl *ED = nullptr; 11924 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11925 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11926 11927 // Should be enough for uint128 (39 decimal digits) 11928 SmallString<64> PrettySourceValue; 11929 llvm::raw_svector_ostream OS(PrettySourceValue); 11930 if (ED) { 11931 OS << '\'' << *ED << "' (" << Value << ")"; 11932 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11933 Constant->IgnoreParenImpCasts())) { 11934 OS << (BL->getValue() ? "YES" : "NO"); 11935 } else { 11936 OS << Value; 11937 } 11938 11939 if (!TautologicalTypeCompare) { 11940 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11941 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11942 << E->getOpcodeStr() << OS.str() << *Result 11943 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11944 return true; 11945 } 11946 11947 if (IsObjCSignedCharBool) { 11948 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11949 S.PDiag(diag::warn_tautological_compare_objc_bool) 11950 << OS.str() << *Result); 11951 return true; 11952 } 11953 11954 // FIXME: We use a somewhat different formatting for the in-range cases and 11955 // cases involving boolean values for historical reasons. We should pick a 11956 // consistent way of presenting these diagnostics. 11957 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11958 11959 S.DiagRuntimeBehavior( 11960 E->getOperatorLoc(), E, 11961 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11962 : diag::warn_tautological_bool_compare) 11963 << OS.str() << classifyConstantValue(Constant) << OtherT 11964 << OtherIsBooleanDespiteType << *Result 11965 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11966 } else { 11967 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 11968 unsigned Diag = 11969 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11970 ? (HasEnumType(OriginalOther) 11971 ? diag::warn_unsigned_enum_always_true_comparison 11972 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 11973 : diag::warn_unsigned_always_true_comparison) 11974 : diag::warn_tautological_constant_compare; 11975 11976 S.Diag(E->getOperatorLoc(), Diag) 11977 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11978 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11979 } 11980 11981 return true; 11982 } 11983 11984 /// Analyze the operands of the given comparison. Implements the 11985 /// fallback case from AnalyzeComparison. 11986 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11987 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11988 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11989 } 11990 11991 /// Implements -Wsign-compare. 11992 /// 11993 /// \param E the binary operator to check for warnings 11994 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 11995 // The type the comparison is being performed in. 11996 QualType T = E->getLHS()->getType(); 11997 11998 // Only analyze comparison operators where both sides have been converted to 11999 // the same type. 12000 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 12001 return AnalyzeImpConvsInComparison(S, E); 12002 12003 // Don't analyze value-dependent comparisons directly. 12004 if (E->isValueDependent()) 12005 return AnalyzeImpConvsInComparison(S, E); 12006 12007 Expr *LHS = E->getLHS(); 12008 Expr *RHS = E->getRHS(); 12009 12010 if (T->isIntegralType(S.Context)) { 12011 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 12012 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 12013 12014 // We don't care about expressions whose result is a constant. 12015 if (RHSValue && LHSValue) 12016 return AnalyzeImpConvsInComparison(S, E); 12017 12018 // We only care about expressions where just one side is literal 12019 if ((bool)RHSValue ^ (bool)LHSValue) { 12020 // Is the constant on the RHS or LHS? 12021 const bool RhsConstant = (bool)RHSValue; 12022 Expr *Const = RhsConstant ? RHS : LHS; 12023 Expr *Other = RhsConstant ? LHS : RHS; 12024 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 12025 12026 // Check whether an integer constant comparison results in a value 12027 // of 'true' or 'false'. 12028 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 12029 return AnalyzeImpConvsInComparison(S, E); 12030 } 12031 } 12032 12033 if (!T->hasUnsignedIntegerRepresentation()) { 12034 // We don't do anything special if this isn't an unsigned integral 12035 // comparison: we're only interested in integral comparisons, and 12036 // signed comparisons only happen in cases we don't care to warn about. 12037 return AnalyzeImpConvsInComparison(S, E); 12038 } 12039 12040 LHS = LHS->IgnoreParenImpCasts(); 12041 RHS = RHS->IgnoreParenImpCasts(); 12042 12043 if (!S.getLangOpts().CPlusPlus) { 12044 // Avoid warning about comparison of integers with different signs when 12045 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 12046 // the type of `E`. 12047 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 12048 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12049 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 12050 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12051 } 12052 12053 // Check to see if one of the (unmodified) operands is of different 12054 // signedness. 12055 Expr *signedOperand, *unsignedOperand; 12056 if (LHS->getType()->hasSignedIntegerRepresentation()) { 12057 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 12058 "unsigned comparison between two signed integer expressions?"); 12059 signedOperand = LHS; 12060 unsignedOperand = RHS; 12061 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 12062 signedOperand = RHS; 12063 unsignedOperand = LHS; 12064 } else { 12065 return AnalyzeImpConvsInComparison(S, E); 12066 } 12067 12068 // Otherwise, calculate the effective range of the signed operand. 12069 IntRange signedRange = GetExprRange( 12070 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 12071 12072 // Go ahead and analyze implicit conversions in the operands. Note 12073 // that we skip the implicit conversions on both sides. 12074 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 12075 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 12076 12077 // If the signed range is non-negative, -Wsign-compare won't fire. 12078 if (signedRange.NonNegative) 12079 return; 12080 12081 // For (in)equality comparisons, if the unsigned operand is a 12082 // constant which cannot collide with a overflowed signed operand, 12083 // then reinterpreting the signed operand as unsigned will not 12084 // change the result of the comparison. 12085 if (E->isEqualityOp()) { 12086 unsigned comparisonWidth = S.Context.getIntWidth(T); 12087 IntRange unsignedRange = 12088 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 12089 /*Approximate*/ true); 12090 12091 // We should never be unable to prove that the unsigned operand is 12092 // non-negative. 12093 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 12094 12095 if (unsignedRange.Width < comparisonWidth) 12096 return; 12097 } 12098 12099 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12100 S.PDiag(diag::warn_mixed_sign_comparison) 12101 << LHS->getType() << RHS->getType() 12102 << LHS->getSourceRange() << RHS->getSourceRange()); 12103 } 12104 12105 /// Analyzes an attempt to assign the given value to a bitfield. 12106 /// 12107 /// Returns true if there was something fishy about the attempt. 12108 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 12109 SourceLocation InitLoc) { 12110 assert(Bitfield->isBitField()); 12111 if (Bitfield->isInvalidDecl()) 12112 return false; 12113 12114 // White-list bool bitfields. 12115 QualType BitfieldType = Bitfield->getType(); 12116 if (BitfieldType->isBooleanType()) 12117 return false; 12118 12119 if (BitfieldType->isEnumeralType()) { 12120 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 12121 // If the underlying enum type was not explicitly specified as an unsigned 12122 // type and the enum contain only positive values, MSVC++ will cause an 12123 // inconsistency by storing this as a signed type. 12124 if (S.getLangOpts().CPlusPlus11 && 12125 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 12126 BitfieldEnumDecl->getNumPositiveBits() > 0 && 12127 BitfieldEnumDecl->getNumNegativeBits() == 0) { 12128 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 12129 << BitfieldEnumDecl; 12130 } 12131 } 12132 12133 if (Bitfield->getType()->isBooleanType()) 12134 return false; 12135 12136 // Ignore value- or type-dependent expressions. 12137 if (Bitfield->getBitWidth()->isValueDependent() || 12138 Bitfield->getBitWidth()->isTypeDependent() || 12139 Init->isValueDependent() || 12140 Init->isTypeDependent()) 12141 return false; 12142 12143 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 12144 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 12145 12146 Expr::EvalResult Result; 12147 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 12148 Expr::SE_AllowSideEffects)) { 12149 // The RHS is not constant. If the RHS has an enum type, make sure the 12150 // bitfield is wide enough to hold all the values of the enum without 12151 // truncation. 12152 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 12153 EnumDecl *ED = EnumTy->getDecl(); 12154 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 12155 12156 // Enum types are implicitly signed on Windows, so check if there are any 12157 // negative enumerators to see if the enum was intended to be signed or 12158 // not. 12159 bool SignedEnum = ED->getNumNegativeBits() > 0; 12160 12161 // Check for surprising sign changes when assigning enum values to a 12162 // bitfield of different signedness. If the bitfield is signed and we 12163 // have exactly the right number of bits to store this unsigned enum, 12164 // suggest changing the enum to an unsigned type. This typically happens 12165 // on Windows where unfixed enums always use an underlying type of 'int'. 12166 unsigned DiagID = 0; 12167 if (SignedEnum && !SignedBitfield) { 12168 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 12169 } else if (SignedBitfield && !SignedEnum && 12170 ED->getNumPositiveBits() == FieldWidth) { 12171 DiagID = diag::warn_signed_bitfield_enum_conversion; 12172 } 12173 12174 if (DiagID) { 12175 S.Diag(InitLoc, DiagID) << Bitfield << ED; 12176 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 12177 SourceRange TypeRange = 12178 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 12179 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 12180 << SignedEnum << TypeRange; 12181 } 12182 12183 // Compute the required bitwidth. If the enum has negative values, we need 12184 // one more bit than the normal number of positive bits to represent the 12185 // sign bit. 12186 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 12187 ED->getNumNegativeBits()) 12188 : ED->getNumPositiveBits(); 12189 12190 // Check the bitwidth. 12191 if (BitsNeeded > FieldWidth) { 12192 Expr *WidthExpr = Bitfield->getBitWidth(); 12193 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 12194 << Bitfield << ED; 12195 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 12196 << BitsNeeded << ED << WidthExpr->getSourceRange(); 12197 } 12198 } 12199 12200 return false; 12201 } 12202 12203 llvm::APSInt Value = Result.Val.getInt(); 12204 12205 unsigned OriginalWidth = Value.getBitWidth(); 12206 12207 if (!Value.isSigned() || Value.isNegative()) 12208 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 12209 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 12210 OriginalWidth = Value.getMinSignedBits(); 12211 12212 if (OriginalWidth <= FieldWidth) 12213 return false; 12214 12215 // Compute the value which the bitfield will contain. 12216 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 12217 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 12218 12219 // Check whether the stored value is equal to the original value. 12220 TruncatedValue = TruncatedValue.extend(OriginalWidth); 12221 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 12222 return false; 12223 12224 // Special-case bitfields of width 1: booleans are naturally 0/1, and 12225 // therefore don't strictly fit into a signed bitfield of width 1. 12226 if (FieldWidth == 1 && Value == 1) 12227 return false; 12228 12229 std::string PrettyValue = toString(Value, 10); 12230 std::string PrettyTrunc = toString(TruncatedValue, 10); 12231 12232 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 12233 << PrettyValue << PrettyTrunc << OriginalInit->getType() 12234 << Init->getSourceRange(); 12235 12236 return true; 12237 } 12238 12239 /// Analyze the given simple or compound assignment for warning-worthy 12240 /// operations. 12241 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 12242 // Just recurse on the LHS. 12243 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12244 12245 // We want to recurse on the RHS as normal unless we're assigning to 12246 // a bitfield. 12247 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 12248 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 12249 E->getOperatorLoc())) { 12250 // Recurse, ignoring any implicit conversions on the RHS. 12251 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 12252 E->getOperatorLoc()); 12253 } 12254 } 12255 12256 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12257 12258 // Diagnose implicitly sequentially-consistent atomic assignment. 12259 if (E->getLHS()->getType()->isAtomicType()) 12260 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12261 } 12262 12263 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12264 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 12265 SourceLocation CContext, unsigned diag, 12266 bool pruneControlFlow = false) { 12267 if (pruneControlFlow) { 12268 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12269 S.PDiag(diag) 12270 << SourceType << T << E->getSourceRange() 12271 << SourceRange(CContext)); 12272 return; 12273 } 12274 S.Diag(E->getExprLoc(), diag) 12275 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 12276 } 12277 12278 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12279 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 12280 SourceLocation CContext, 12281 unsigned diag, bool pruneControlFlow = false) { 12282 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 12283 } 12284 12285 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 12286 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 12287 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 12288 } 12289 12290 static void adornObjCBoolConversionDiagWithTernaryFixit( 12291 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 12292 Expr *Ignored = SourceExpr->IgnoreImplicit(); 12293 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 12294 Ignored = OVE->getSourceExpr(); 12295 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 12296 isa<BinaryOperator>(Ignored) || 12297 isa<CXXOperatorCallExpr>(Ignored); 12298 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 12299 if (NeedsParens) 12300 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 12301 << FixItHint::CreateInsertion(EndLoc, ")"); 12302 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 12303 } 12304 12305 /// Diagnose an implicit cast from a floating point value to an integer value. 12306 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 12307 SourceLocation CContext) { 12308 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 12309 const bool PruneWarnings = S.inTemplateInstantiation(); 12310 12311 Expr *InnerE = E->IgnoreParenImpCasts(); 12312 // We also want to warn on, e.g., "int i = -1.234" 12313 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 12314 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 12315 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 12316 12317 const bool IsLiteral = 12318 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 12319 12320 llvm::APFloat Value(0.0); 12321 bool IsConstant = 12322 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 12323 if (!IsConstant) { 12324 if (isObjCSignedCharBool(S, T)) { 12325 return adornObjCBoolConversionDiagWithTernaryFixit( 12326 S, E, 12327 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 12328 << E->getType()); 12329 } 12330 12331 return DiagnoseImpCast(S, E, T, CContext, 12332 diag::warn_impcast_float_integer, PruneWarnings); 12333 } 12334 12335 bool isExact = false; 12336 12337 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 12338 T->hasUnsignedIntegerRepresentation()); 12339 llvm::APFloat::opStatus Result = Value.convertToInteger( 12340 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 12341 12342 // FIXME: Force the precision of the source value down so we don't print 12343 // digits which are usually useless (we don't really care here if we 12344 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 12345 // would automatically print the shortest representation, but it's a bit 12346 // tricky to implement. 12347 SmallString<16> PrettySourceValue; 12348 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 12349 precision = (precision * 59 + 195) / 196; 12350 Value.toString(PrettySourceValue, precision); 12351 12352 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 12353 return adornObjCBoolConversionDiagWithTernaryFixit( 12354 S, E, 12355 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 12356 << PrettySourceValue); 12357 } 12358 12359 if (Result == llvm::APFloat::opOK && isExact) { 12360 if (IsLiteral) return; 12361 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 12362 PruneWarnings); 12363 } 12364 12365 // Conversion of a floating-point value to a non-bool integer where the 12366 // integral part cannot be represented by the integer type is undefined. 12367 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 12368 return DiagnoseImpCast( 12369 S, E, T, CContext, 12370 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 12371 : diag::warn_impcast_float_to_integer_out_of_range, 12372 PruneWarnings); 12373 12374 unsigned DiagID = 0; 12375 if (IsLiteral) { 12376 // Warn on floating point literal to integer. 12377 DiagID = diag::warn_impcast_literal_float_to_integer; 12378 } else if (IntegerValue == 0) { 12379 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 12380 return DiagnoseImpCast(S, E, T, CContext, 12381 diag::warn_impcast_float_integer, PruneWarnings); 12382 } 12383 // Warn on non-zero to zero conversion. 12384 DiagID = diag::warn_impcast_float_to_integer_zero; 12385 } else { 12386 if (IntegerValue.isUnsigned()) { 12387 if (!IntegerValue.isMaxValue()) { 12388 return DiagnoseImpCast(S, E, T, CContext, 12389 diag::warn_impcast_float_integer, PruneWarnings); 12390 } 12391 } else { // IntegerValue.isSigned() 12392 if (!IntegerValue.isMaxSignedValue() && 12393 !IntegerValue.isMinSignedValue()) { 12394 return DiagnoseImpCast(S, E, T, CContext, 12395 diag::warn_impcast_float_integer, PruneWarnings); 12396 } 12397 } 12398 // Warn on evaluatable floating point expression to integer conversion. 12399 DiagID = diag::warn_impcast_float_to_integer; 12400 } 12401 12402 SmallString<16> PrettyTargetValue; 12403 if (IsBool) 12404 PrettyTargetValue = Value.isZero() ? "false" : "true"; 12405 else 12406 IntegerValue.toString(PrettyTargetValue); 12407 12408 if (PruneWarnings) { 12409 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12410 S.PDiag(DiagID) 12411 << E->getType() << T.getUnqualifiedType() 12412 << PrettySourceValue << PrettyTargetValue 12413 << E->getSourceRange() << SourceRange(CContext)); 12414 } else { 12415 S.Diag(E->getExprLoc(), DiagID) 12416 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 12417 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 12418 } 12419 } 12420 12421 /// Analyze the given compound assignment for the possible losing of 12422 /// floating-point precision. 12423 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 12424 assert(isa<CompoundAssignOperator>(E) && 12425 "Must be compound assignment operation"); 12426 // Recurse on the LHS and RHS in here 12427 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12428 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12429 12430 if (E->getLHS()->getType()->isAtomicType()) 12431 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 12432 12433 // Now check the outermost expression 12434 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 12435 const auto *RBT = cast<CompoundAssignOperator>(E) 12436 ->getComputationResultType() 12437 ->getAs<BuiltinType>(); 12438 12439 // The below checks assume source is floating point. 12440 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 12441 12442 // If source is floating point but target is an integer. 12443 if (ResultBT->isInteger()) 12444 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 12445 E->getExprLoc(), diag::warn_impcast_float_integer); 12446 12447 if (!ResultBT->isFloatingPoint()) 12448 return; 12449 12450 // If both source and target are floating points, warn about losing precision. 12451 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12452 QualType(ResultBT, 0), QualType(RBT, 0)); 12453 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 12454 // warn about dropping FP rank. 12455 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 12456 diag::warn_impcast_float_result_precision); 12457 } 12458 12459 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 12460 IntRange Range) { 12461 if (!Range.Width) return "0"; 12462 12463 llvm::APSInt ValueInRange = Value; 12464 ValueInRange.setIsSigned(!Range.NonNegative); 12465 ValueInRange = ValueInRange.trunc(Range.Width); 12466 return toString(ValueInRange, 10); 12467 } 12468 12469 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 12470 if (!isa<ImplicitCastExpr>(Ex)) 12471 return false; 12472 12473 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12474 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12475 const Type *Source = 12476 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12477 if (Target->isDependentType()) 12478 return false; 12479 12480 const BuiltinType *FloatCandidateBT = 12481 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12482 const Type *BoolCandidateType = ToBool ? Target : Source; 12483 12484 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12485 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12486 } 12487 12488 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12489 SourceLocation CC) { 12490 unsigned NumArgs = TheCall->getNumArgs(); 12491 for (unsigned i = 0; i < NumArgs; ++i) { 12492 Expr *CurrA = TheCall->getArg(i); 12493 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12494 continue; 12495 12496 bool IsSwapped = ((i > 0) && 12497 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12498 IsSwapped |= ((i < (NumArgs - 1)) && 12499 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12500 if (IsSwapped) { 12501 // Warn on this floating-point to bool conversion. 12502 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12503 CurrA->getType(), CC, 12504 diag::warn_impcast_floating_point_to_bool); 12505 } 12506 } 12507 } 12508 12509 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12510 SourceLocation CC) { 12511 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12512 E->getExprLoc())) 12513 return; 12514 12515 // Don't warn on functions which have return type nullptr_t. 12516 if (isa<CallExpr>(E)) 12517 return; 12518 12519 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12520 const Expr::NullPointerConstantKind NullKind = 12521 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12522 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12523 return; 12524 12525 // Return if target type is a safe conversion. 12526 if (T->isAnyPointerType() || T->isBlockPointerType() || 12527 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12528 return; 12529 12530 SourceLocation Loc = E->getSourceRange().getBegin(); 12531 12532 // Venture through the macro stacks to get to the source of macro arguments. 12533 // The new location is a better location than the complete location that was 12534 // passed in. 12535 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12536 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12537 12538 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12539 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12540 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12541 Loc, S.SourceMgr, S.getLangOpts()); 12542 if (MacroName == "NULL") 12543 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12544 } 12545 12546 // Only warn if the null and context location are in the same macro expansion. 12547 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12548 return; 12549 12550 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12551 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12552 << FixItHint::CreateReplacement(Loc, 12553 S.getFixItZeroLiteralForType(T, Loc)); 12554 } 12555 12556 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12557 ObjCArrayLiteral *ArrayLiteral); 12558 12559 static void 12560 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12561 ObjCDictionaryLiteral *DictionaryLiteral); 12562 12563 /// Check a single element within a collection literal against the 12564 /// target element type. 12565 static void checkObjCCollectionLiteralElement(Sema &S, 12566 QualType TargetElementType, 12567 Expr *Element, 12568 unsigned ElementKind) { 12569 // Skip a bitcast to 'id' or qualified 'id'. 12570 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12571 if (ICE->getCastKind() == CK_BitCast && 12572 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12573 Element = ICE->getSubExpr(); 12574 } 12575 12576 QualType ElementType = Element->getType(); 12577 ExprResult ElementResult(Element); 12578 if (ElementType->getAs<ObjCObjectPointerType>() && 12579 S.CheckSingleAssignmentConstraints(TargetElementType, 12580 ElementResult, 12581 false, false) 12582 != Sema::Compatible) { 12583 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12584 << ElementType << ElementKind << TargetElementType 12585 << Element->getSourceRange(); 12586 } 12587 12588 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12589 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12590 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12591 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12592 } 12593 12594 /// Check an Objective-C array literal being converted to the given 12595 /// target type. 12596 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12597 ObjCArrayLiteral *ArrayLiteral) { 12598 if (!S.NSArrayDecl) 12599 return; 12600 12601 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12602 if (!TargetObjCPtr) 12603 return; 12604 12605 if (TargetObjCPtr->isUnspecialized() || 12606 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12607 != S.NSArrayDecl->getCanonicalDecl()) 12608 return; 12609 12610 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12611 if (TypeArgs.size() != 1) 12612 return; 12613 12614 QualType TargetElementType = TypeArgs[0]; 12615 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12616 checkObjCCollectionLiteralElement(S, TargetElementType, 12617 ArrayLiteral->getElement(I), 12618 0); 12619 } 12620 } 12621 12622 /// Check an Objective-C dictionary literal being converted to the given 12623 /// target type. 12624 static void 12625 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12626 ObjCDictionaryLiteral *DictionaryLiteral) { 12627 if (!S.NSDictionaryDecl) 12628 return; 12629 12630 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12631 if (!TargetObjCPtr) 12632 return; 12633 12634 if (TargetObjCPtr->isUnspecialized() || 12635 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12636 != S.NSDictionaryDecl->getCanonicalDecl()) 12637 return; 12638 12639 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12640 if (TypeArgs.size() != 2) 12641 return; 12642 12643 QualType TargetKeyType = TypeArgs[0]; 12644 QualType TargetObjectType = TypeArgs[1]; 12645 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12646 auto Element = DictionaryLiteral->getKeyValueElement(I); 12647 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12648 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12649 } 12650 } 12651 12652 // Helper function to filter out cases for constant width constant conversion. 12653 // Don't warn on char array initialization or for non-decimal values. 12654 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12655 SourceLocation CC) { 12656 // If initializing from a constant, and the constant starts with '0', 12657 // then it is a binary, octal, or hexadecimal. Allow these constants 12658 // to fill all the bits, even if there is a sign change. 12659 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12660 const char FirstLiteralCharacter = 12661 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12662 if (FirstLiteralCharacter == '0') 12663 return false; 12664 } 12665 12666 // If the CC location points to a '{', and the type is char, then assume 12667 // assume it is an array initialization. 12668 if (CC.isValid() && T->isCharType()) { 12669 const char FirstContextCharacter = 12670 S.getSourceManager().getCharacterData(CC)[0]; 12671 if (FirstContextCharacter == '{') 12672 return false; 12673 } 12674 12675 return true; 12676 } 12677 12678 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12679 const auto *IL = dyn_cast<IntegerLiteral>(E); 12680 if (!IL) { 12681 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12682 if (UO->getOpcode() == UO_Minus) 12683 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12684 } 12685 } 12686 12687 return IL; 12688 } 12689 12690 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12691 E = E->IgnoreParenImpCasts(); 12692 SourceLocation ExprLoc = E->getExprLoc(); 12693 12694 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12695 BinaryOperator::Opcode Opc = BO->getOpcode(); 12696 Expr::EvalResult Result; 12697 // Do not diagnose unsigned shifts. 12698 if (Opc == BO_Shl) { 12699 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12700 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12701 if (LHS && LHS->getValue() == 0) 12702 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12703 else if (!E->isValueDependent() && LHS && RHS && 12704 RHS->getValue().isNonNegative() && 12705 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12706 S.Diag(ExprLoc, diag::warn_left_shift_always) 12707 << (Result.Val.getInt() != 0); 12708 else if (E->getType()->isSignedIntegerType()) 12709 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12710 } 12711 } 12712 12713 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12714 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12715 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12716 if (!LHS || !RHS) 12717 return; 12718 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12719 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12720 // Do not diagnose common idioms. 12721 return; 12722 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12723 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12724 } 12725 } 12726 12727 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12728 SourceLocation CC, 12729 bool *ICContext = nullptr, 12730 bool IsListInit = false) { 12731 if (E->isTypeDependent() || E->isValueDependent()) return; 12732 12733 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12734 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12735 if (Source == Target) return; 12736 if (Target->isDependentType()) return; 12737 12738 // If the conversion context location is invalid don't complain. We also 12739 // don't want to emit a warning if the issue occurs from the expansion of 12740 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12741 // delay this check as long as possible. Once we detect we are in that 12742 // scenario, we just return. 12743 if (CC.isInvalid()) 12744 return; 12745 12746 if (Source->isAtomicType()) 12747 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12748 12749 // Diagnose implicit casts to bool. 12750 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12751 if (isa<StringLiteral>(E)) 12752 // Warn on string literal to bool. Checks for string literals in logical 12753 // and expressions, for instance, assert(0 && "error here"), are 12754 // prevented by a check in AnalyzeImplicitConversions(). 12755 return DiagnoseImpCast(S, E, T, CC, 12756 diag::warn_impcast_string_literal_to_bool); 12757 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12758 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12759 // This covers the literal expressions that evaluate to Objective-C 12760 // objects. 12761 return DiagnoseImpCast(S, E, T, CC, 12762 diag::warn_impcast_objective_c_literal_to_bool); 12763 } 12764 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12765 // Warn on pointer to bool conversion that is always true. 12766 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12767 SourceRange(CC)); 12768 } 12769 } 12770 12771 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12772 // is a typedef for signed char (macOS), then that constant value has to be 1 12773 // or 0. 12774 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12775 Expr::EvalResult Result; 12776 if (E->EvaluateAsInt(Result, S.getASTContext(), 12777 Expr::SE_AllowSideEffects)) { 12778 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12779 adornObjCBoolConversionDiagWithTernaryFixit( 12780 S, E, 12781 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12782 << toString(Result.Val.getInt(), 10)); 12783 } 12784 return; 12785 } 12786 } 12787 12788 // Check implicit casts from Objective-C collection literals to specialized 12789 // collection types, e.g., NSArray<NSString *> *. 12790 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12791 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12792 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12793 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12794 12795 // Strip vector types. 12796 if (isa<VectorType>(Source)) { 12797 if (Target->isVLSTBuiltinType() && 12798 (S.Context.areCompatibleSveTypes(QualType(Target, 0), 12799 QualType(Source, 0)) || 12800 S.Context.areLaxCompatibleSveTypes(QualType(Target, 0), 12801 QualType(Source, 0)))) 12802 return; 12803 12804 if (!isa<VectorType>(Target)) { 12805 if (S.SourceMgr.isInSystemMacro(CC)) 12806 return; 12807 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12808 } 12809 12810 // If the vector cast is cast between two vectors of the same size, it is 12811 // a bitcast, not a conversion. 12812 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12813 return; 12814 12815 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12816 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12817 } 12818 if (auto VecTy = dyn_cast<VectorType>(Target)) 12819 Target = VecTy->getElementType().getTypePtr(); 12820 12821 // Strip complex types. 12822 if (isa<ComplexType>(Source)) { 12823 if (!isa<ComplexType>(Target)) { 12824 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12825 return; 12826 12827 return DiagnoseImpCast(S, E, T, CC, 12828 S.getLangOpts().CPlusPlus 12829 ? diag::err_impcast_complex_scalar 12830 : diag::warn_impcast_complex_scalar); 12831 } 12832 12833 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12834 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12835 } 12836 12837 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12838 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12839 12840 // If the source is floating point... 12841 if (SourceBT && SourceBT->isFloatingPoint()) { 12842 // ...and the target is floating point... 12843 if (TargetBT && TargetBT->isFloatingPoint()) { 12844 // ...then warn if we're dropping FP rank. 12845 12846 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12847 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12848 if (Order > 0) { 12849 // Don't warn about float constants that are precisely 12850 // representable in the target type. 12851 Expr::EvalResult result; 12852 if (E->EvaluateAsRValue(result, S.Context)) { 12853 // Value might be a float, a float vector, or a float complex. 12854 if (IsSameFloatAfterCast(result.Val, 12855 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12856 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12857 return; 12858 } 12859 12860 if (S.SourceMgr.isInSystemMacro(CC)) 12861 return; 12862 12863 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12864 } 12865 // ... or possibly if we're increasing rank, too 12866 else if (Order < 0) { 12867 if (S.SourceMgr.isInSystemMacro(CC)) 12868 return; 12869 12870 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12871 } 12872 return; 12873 } 12874 12875 // If the target is integral, always warn. 12876 if (TargetBT && TargetBT->isInteger()) { 12877 if (S.SourceMgr.isInSystemMacro(CC)) 12878 return; 12879 12880 DiagnoseFloatingImpCast(S, E, T, CC); 12881 } 12882 12883 // Detect the case where a call result is converted from floating-point to 12884 // to bool, and the final argument to the call is converted from bool, to 12885 // discover this typo: 12886 // 12887 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12888 // 12889 // FIXME: This is an incredibly special case; is there some more general 12890 // way to detect this class of misplaced-parentheses bug? 12891 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12892 // Check last argument of function call to see if it is an 12893 // implicit cast from a type matching the type the result 12894 // is being cast to. 12895 CallExpr *CEx = cast<CallExpr>(E); 12896 if (unsigned NumArgs = CEx->getNumArgs()) { 12897 Expr *LastA = CEx->getArg(NumArgs - 1); 12898 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12899 if (isa<ImplicitCastExpr>(LastA) && 12900 InnerE->getType()->isBooleanType()) { 12901 // Warn on this floating-point to bool conversion 12902 DiagnoseImpCast(S, E, T, CC, 12903 diag::warn_impcast_floating_point_to_bool); 12904 } 12905 } 12906 } 12907 return; 12908 } 12909 12910 // Valid casts involving fixed point types should be accounted for here. 12911 if (Source->isFixedPointType()) { 12912 if (Target->isUnsaturatedFixedPointType()) { 12913 Expr::EvalResult Result; 12914 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12915 S.isConstantEvaluated())) { 12916 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12917 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12918 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12919 if (Value > MaxVal || Value < MinVal) { 12920 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12921 S.PDiag(diag::warn_impcast_fixed_point_range) 12922 << Value.toString() << T 12923 << E->getSourceRange() 12924 << clang::SourceRange(CC)); 12925 return; 12926 } 12927 } 12928 } else if (Target->isIntegerType()) { 12929 Expr::EvalResult Result; 12930 if (!S.isConstantEvaluated() && 12931 E->EvaluateAsFixedPoint(Result, S.Context, 12932 Expr::SE_AllowSideEffects)) { 12933 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12934 12935 bool Overflowed; 12936 llvm::APSInt IntResult = FXResult.convertToInt( 12937 S.Context.getIntWidth(T), 12938 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12939 12940 if (Overflowed) { 12941 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12942 S.PDiag(diag::warn_impcast_fixed_point_range) 12943 << FXResult.toString() << T 12944 << E->getSourceRange() 12945 << clang::SourceRange(CC)); 12946 return; 12947 } 12948 } 12949 } 12950 } else if (Target->isUnsaturatedFixedPointType()) { 12951 if (Source->isIntegerType()) { 12952 Expr::EvalResult Result; 12953 if (!S.isConstantEvaluated() && 12954 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12955 llvm::APSInt Value = Result.Val.getInt(); 12956 12957 bool Overflowed; 12958 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12959 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12960 12961 if (Overflowed) { 12962 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12963 S.PDiag(diag::warn_impcast_fixed_point_range) 12964 << toString(Value, /*Radix=*/10) << T 12965 << E->getSourceRange() 12966 << clang::SourceRange(CC)); 12967 return; 12968 } 12969 } 12970 } 12971 } 12972 12973 // If we are casting an integer type to a floating point type without 12974 // initialization-list syntax, we might lose accuracy if the floating 12975 // point type has a narrower significand than the integer type. 12976 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12977 TargetBT->isFloatingType() && !IsListInit) { 12978 // Determine the number of precision bits in the source integer type. 12979 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12980 /*Approximate*/ true); 12981 unsigned int SourcePrecision = SourceRange.Width; 12982 12983 // Determine the number of precision bits in the 12984 // target floating point type. 12985 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12986 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12987 12988 if (SourcePrecision > 0 && TargetPrecision > 0 && 12989 SourcePrecision > TargetPrecision) { 12990 12991 if (Optional<llvm::APSInt> SourceInt = 12992 E->getIntegerConstantExpr(S.Context)) { 12993 // If the source integer is a constant, convert it to the target 12994 // floating point type. Issue a warning if the value changes 12995 // during the whole conversion. 12996 llvm::APFloat TargetFloatValue( 12997 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12998 llvm::APFloat::opStatus ConversionStatus = 12999 TargetFloatValue.convertFromAPInt( 13000 *SourceInt, SourceBT->isSignedInteger(), 13001 llvm::APFloat::rmNearestTiesToEven); 13002 13003 if (ConversionStatus != llvm::APFloat::opOK) { 13004 SmallString<32> PrettySourceValue; 13005 SourceInt->toString(PrettySourceValue, 10); 13006 SmallString<32> PrettyTargetValue; 13007 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 13008 13009 S.DiagRuntimeBehavior( 13010 E->getExprLoc(), E, 13011 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 13012 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13013 << E->getSourceRange() << clang::SourceRange(CC)); 13014 } 13015 } else { 13016 // Otherwise, the implicit conversion may lose precision. 13017 DiagnoseImpCast(S, E, T, CC, 13018 diag::warn_impcast_integer_float_precision); 13019 } 13020 } 13021 } 13022 13023 DiagnoseNullConversion(S, E, T, CC); 13024 13025 S.DiscardMisalignedMemberAddress(Target, E); 13026 13027 if (Target->isBooleanType()) 13028 DiagnoseIntInBoolContext(S, E); 13029 13030 if (!Source->isIntegerType() || !Target->isIntegerType()) 13031 return; 13032 13033 // TODO: remove this early return once the false positives for constant->bool 13034 // in templates, macros, etc, are reduced or removed. 13035 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 13036 return; 13037 13038 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 13039 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 13040 return adornObjCBoolConversionDiagWithTernaryFixit( 13041 S, E, 13042 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 13043 << E->getType()); 13044 } 13045 13046 IntRange SourceTypeRange = 13047 IntRange::forTargetOfCanonicalType(S.Context, Source); 13048 IntRange LikelySourceRange = 13049 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 13050 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 13051 13052 if (LikelySourceRange.Width > TargetRange.Width) { 13053 // If the source is a constant, use a default-on diagnostic. 13054 // TODO: this should happen for bitfield stores, too. 13055 Expr::EvalResult Result; 13056 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 13057 S.isConstantEvaluated())) { 13058 llvm::APSInt Value(32); 13059 Value = Result.Val.getInt(); 13060 13061 if (S.SourceMgr.isInSystemMacro(CC)) 13062 return; 13063 13064 std::string PrettySourceValue = toString(Value, 10); 13065 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13066 13067 S.DiagRuntimeBehavior( 13068 E->getExprLoc(), E, 13069 S.PDiag(diag::warn_impcast_integer_precision_constant) 13070 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13071 << E->getSourceRange() << SourceRange(CC)); 13072 return; 13073 } 13074 13075 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 13076 if (S.SourceMgr.isInSystemMacro(CC)) 13077 return; 13078 13079 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 13080 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 13081 /* pruneControlFlow */ true); 13082 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 13083 } 13084 13085 if (TargetRange.Width > SourceTypeRange.Width) { 13086 if (auto *UO = dyn_cast<UnaryOperator>(E)) 13087 if (UO->getOpcode() == UO_Minus) 13088 if (Source->isUnsignedIntegerType()) { 13089 if (Target->isUnsignedIntegerType()) 13090 return DiagnoseImpCast(S, E, T, CC, 13091 diag::warn_impcast_high_order_zero_bits); 13092 if (Target->isSignedIntegerType()) 13093 return DiagnoseImpCast(S, E, T, CC, 13094 diag::warn_impcast_nonnegative_result); 13095 } 13096 } 13097 13098 if (TargetRange.Width == LikelySourceRange.Width && 13099 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 13100 Source->isSignedIntegerType()) { 13101 // Warn when doing a signed to signed conversion, warn if the positive 13102 // source value is exactly the width of the target type, which will 13103 // cause a negative value to be stored. 13104 13105 Expr::EvalResult Result; 13106 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 13107 !S.SourceMgr.isInSystemMacro(CC)) { 13108 llvm::APSInt Value = Result.Val.getInt(); 13109 if (isSameWidthConstantConversion(S, E, T, CC)) { 13110 std::string PrettySourceValue = toString(Value, 10); 13111 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13112 13113 S.DiagRuntimeBehavior( 13114 E->getExprLoc(), E, 13115 S.PDiag(diag::warn_impcast_integer_precision_constant) 13116 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13117 << E->getSourceRange() << SourceRange(CC)); 13118 return; 13119 } 13120 } 13121 13122 // Fall through for non-constants to give a sign conversion warning. 13123 } 13124 13125 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 13126 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 13127 LikelySourceRange.Width == TargetRange.Width)) { 13128 if (S.SourceMgr.isInSystemMacro(CC)) 13129 return; 13130 13131 unsigned DiagID = diag::warn_impcast_integer_sign; 13132 13133 // Traditionally, gcc has warned about this under -Wsign-compare. 13134 // We also want to warn about it in -Wconversion. 13135 // So if -Wconversion is off, use a completely identical diagnostic 13136 // in the sign-compare group. 13137 // The conditional-checking code will 13138 if (ICContext) { 13139 DiagID = diag::warn_impcast_integer_sign_conditional; 13140 *ICContext = true; 13141 } 13142 13143 return DiagnoseImpCast(S, E, T, CC, DiagID); 13144 } 13145 13146 // Diagnose conversions between different enumeration types. 13147 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 13148 // type, to give us better diagnostics. 13149 QualType SourceType = E->getType(); 13150 if (!S.getLangOpts().CPlusPlus) { 13151 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13152 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 13153 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 13154 SourceType = S.Context.getTypeDeclType(Enum); 13155 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 13156 } 13157 } 13158 13159 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 13160 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 13161 if (SourceEnum->getDecl()->hasNameForLinkage() && 13162 TargetEnum->getDecl()->hasNameForLinkage() && 13163 SourceEnum != TargetEnum) { 13164 if (S.SourceMgr.isInSystemMacro(CC)) 13165 return; 13166 13167 return DiagnoseImpCast(S, E, SourceType, T, CC, 13168 diag::warn_impcast_different_enum_types); 13169 } 13170 } 13171 13172 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13173 SourceLocation CC, QualType T); 13174 13175 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 13176 SourceLocation CC, bool &ICContext) { 13177 E = E->IgnoreParenImpCasts(); 13178 13179 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 13180 return CheckConditionalOperator(S, CO, CC, T); 13181 13182 AnalyzeImplicitConversions(S, E, CC); 13183 if (E->getType() != T) 13184 return CheckImplicitConversion(S, E, T, CC, &ICContext); 13185 } 13186 13187 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13188 SourceLocation CC, QualType T) { 13189 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 13190 13191 Expr *TrueExpr = E->getTrueExpr(); 13192 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 13193 TrueExpr = BCO->getCommon(); 13194 13195 bool Suspicious = false; 13196 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 13197 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 13198 13199 if (T->isBooleanType()) 13200 DiagnoseIntInBoolContext(S, E); 13201 13202 // If -Wconversion would have warned about either of the candidates 13203 // for a signedness conversion to the context type... 13204 if (!Suspicious) return; 13205 13206 // ...but it's currently ignored... 13207 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 13208 return; 13209 13210 // ...then check whether it would have warned about either of the 13211 // candidates for a signedness conversion to the condition type. 13212 if (E->getType() == T) return; 13213 13214 Suspicious = false; 13215 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 13216 E->getType(), CC, &Suspicious); 13217 if (!Suspicious) 13218 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 13219 E->getType(), CC, &Suspicious); 13220 } 13221 13222 /// Check conversion of given expression to boolean. 13223 /// Input argument E is a logical expression. 13224 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 13225 if (S.getLangOpts().Bool) 13226 return; 13227 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 13228 return; 13229 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 13230 } 13231 13232 namespace { 13233 struct AnalyzeImplicitConversionsWorkItem { 13234 Expr *E; 13235 SourceLocation CC; 13236 bool IsListInit; 13237 }; 13238 } 13239 13240 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 13241 /// that should be visited are added to WorkList. 13242 static void AnalyzeImplicitConversions( 13243 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 13244 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 13245 Expr *OrigE = Item.E; 13246 SourceLocation CC = Item.CC; 13247 13248 QualType T = OrigE->getType(); 13249 Expr *E = OrigE->IgnoreParenImpCasts(); 13250 13251 // Propagate whether we are in a C++ list initialization expression. 13252 // If so, we do not issue warnings for implicit int-float conversion 13253 // precision loss, because C++11 narrowing already handles it. 13254 bool IsListInit = Item.IsListInit || 13255 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 13256 13257 if (E->isTypeDependent() || E->isValueDependent()) 13258 return; 13259 13260 Expr *SourceExpr = E; 13261 // Examine, but don't traverse into the source expression of an 13262 // OpaqueValueExpr, since it may have multiple parents and we don't want to 13263 // emit duplicate diagnostics. Its fine to examine the form or attempt to 13264 // evaluate it in the context of checking the specific conversion to T though. 13265 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 13266 if (auto *Src = OVE->getSourceExpr()) 13267 SourceExpr = Src; 13268 13269 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 13270 if (UO->getOpcode() == UO_Not && 13271 UO->getSubExpr()->isKnownToHaveBooleanValue()) 13272 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 13273 << OrigE->getSourceRange() << T->isBooleanType() 13274 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 13275 13276 if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) 13277 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) && 13278 BO->getLHS()->isKnownToHaveBooleanValue() && 13279 BO->getRHS()->isKnownToHaveBooleanValue() && 13280 BO->getLHS()->HasSideEffects(S.Context) && 13281 BO->getRHS()->HasSideEffects(S.Context)) { 13282 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical) 13283 << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange() 13284 << FixItHint::CreateReplacement( 13285 BO->getOperatorLoc(), 13286 (BO->getOpcode() == BO_And ? "&&" : "||")); 13287 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int); 13288 } 13289 13290 // For conditional operators, we analyze the arguments as if they 13291 // were being fed directly into the output. 13292 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 13293 CheckConditionalOperator(S, CO, CC, T); 13294 return; 13295 } 13296 13297 // Check implicit argument conversions for function calls. 13298 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 13299 CheckImplicitArgumentConversions(S, Call, CC); 13300 13301 // Go ahead and check any implicit conversions we might have skipped. 13302 // The non-canonical typecheck is just an optimization; 13303 // CheckImplicitConversion will filter out dead implicit conversions. 13304 if (SourceExpr->getType() != T) 13305 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 13306 13307 // Now continue drilling into this expression. 13308 13309 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 13310 // The bound subexpressions in a PseudoObjectExpr are not reachable 13311 // as transitive children. 13312 // FIXME: Use a more uniform representation for this. 13313 for (auto *SE : POE->semantics()) 13314 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 13315 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 13316 } 13317 13318 // Skip past explicit casts. 13319 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 13320 E = CE->getSubExpr()->IgnoreParenImpCasts(); 13321 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 13322 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 13323 WorkList.push_back({E, CC, IsListInit}); 13324 return; 13325 } 13326 13327 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13328 // Do a somewhat different check with comparison operators. 13329 if (BO->isComparisonOp()) 13330 return AnalyzeComparison(S, BO); 13331 13332 // And with simple assignments. 13333 if (BO->getOpcode() == BO_Assign) 13334 return AnalyzeAssignment(S, BO); 13335 // And with compound assignments. 13336 if (BO->isAssignmentOp()) 13337 return AnalyzeCompoundAssignment(S, BO); 13338 } 13339 13340 // These break the otherwise-useful invariant below. Fortunately, 13341 // we don't really need to recurse into them, because any internal 13342 // expressions should have been analyzed already when they were 13343 // built into statements. 13344 if (isa<StmtExpr>(E)) return; 13345 13346 // Don't descend into unevaluated contexts. 13347 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 13348 13349 // Now just recurse over the expression's children. 13350 CC = E->getExprLoc(); 13351 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 13352 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 13353 for (Stmt *SubStmt : E->children()) { 13354 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 13355 if (!ChildExpr) 13356 continue; 13357 13358 if (IsLogicalAndOperator && 13359 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 13360 // Ignore checking string literals that are in logical and operators. 13361 // This is a common pattern for asserts. 13362 continue; 13363 WorkList.push_back({ChildExpr, CC, IsListInit}); 13364 } 13365 13366 if (BO && BO->isLogicalOp()) { 13367 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 13368 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13369 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13370 13371 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 13372 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13373 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13374 } 13375 13376 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 13377 if (U->getOpcode() == UO_LNot) { 13378 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 13379 } else if (U->getOpcode() != UO_AddrOf) { 13380 if (U->getSubExpr()->getType()->isAtomicType()) 13381 S.Diag(U->getSubExpr()->getBeginLoc(), 13382 diag::warn_atomic_implicit_seq_cst); 13383 } 13384 } 13385 } 13386 13387 /// AnalyzeImplicitConversions - Find and report any interesting 13388 /// implicit conversions in the given expression. There are a couple 13389 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 13390 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 13391 bool IsListInit/*= false*/) { 13392 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 13393 WorkList.push_back({OrigE, CC, IsListInit}); 13394 while (!WorkList.empty()) 13395 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 13396 } 13397 13398 /// Diagnose integer type and any valid implicit conversion to it. 13399 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 13400 // Taking into account implicit conversions, 13401 // allow any integer. 13402 if (!E->getType()->isIntegerType()) { 13403 S.Diag(E->getBeginLoc(), 13404 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 13405 return true; 13406 } 13407 // Potentially emit standard warnings for implicit conversions if enabled 13408 // using -Wconversion. 13409 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 13410 return false; 13411 } 13412 13413 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 13414 // Returns true when emitting a warning about taking the address of a reference. 13415 static bool CheckForReference(Sema &SemaRef, const Expr *E, 13416 const PartialDiagnostic &PD) { 13417 E = E->IgnoreParenImpCasts(); 13418 13419 const FunctionDecl *FD = nullptr; 13420 13421 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13422 if (!DRE->getDecl()->getType()->isReferenceType()) 13423 return false; 13424 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13425 if (!M->getMemberDecl()->getType()->isReferenceType()) 13426 return false; 13427 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 13428 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 13429 return false; 13430 FD = Call->getDirectCallee(); 13431 } else { 13432 return false; 13433 } 13434 13435 SemaRef.Diag(E->getExprLoc(), PD); 13436 13437 // If possible, point to location of function. 13438 if (FD) { 13439 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 13440 } 13441 13442 return true; 13443 } 13444 13445 // Returns true if the SourceLocation is expanded from any macro body. 13446 // Returns false if the SourceLocation is invalid, is from not in a macro 13447 // expansion, or is from expanded from a top-level macro argument. 13448 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 13449 if (Loc.isInvalid()) 13450 return false; 13451 13452 while (Loc.isMacroID()) { 13453 if (SM.isMacroBodyExpansion(Loc)) 13454 return true; 13455 Loc = SM.getImmediateMacroCallerLoc(Loc); 13456 } 13457 13458 return false; 13459 } 13460 13461 /// Diagnose pointers that are always non-null. 13462 /// \param E the expression containing the pointer 13463 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 13464 /// compared to a null pointer 13465 /// \param IsEqual True when the comparison is equal to a null pointer 13466 /// \param Range Extra SourceRange to highlight in the diagnostic 13467 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 13468 Expr::NullPointerConstantKind NullKind, 13469 bool IsEqual, SourceRange Range) { 13470 if (!E) 13471 return; 13472 13473 // Don't warn inside macros. 13474 if (E->getExprLoc().isMacroID()) { 13475 const SourceManager &SM = getSourceManager(); 13476 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 13477 IsInAnyMacroBody(SM, Range.getBegin())) 13478 return; 13479 } 13480 E = E->IgnoreImpCasts(); 13481 13482 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 13483 13484 if (isa<CXXThisExpr>(E)) { 13485 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13486 : diag::warn_this_bool_conversion; 13487 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13488 return; 13489 } 13490 13491 bool IsAddressOf = false; 13492 13493 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13494 if (UO->getOpcode() != UO_AddrOf) 13495 return; 13496 IsAddressOf = true; 13497 E = UO->getSubExpr(); 13498 } 13499 13500 if (IsAddressOf) { 13501 unsigned DiagID = IsCompare 13502 ? diag::warn_address_of_reference_null_compare 13503 : diag::warn_address_of_reference_bool_conversion; 13504 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13505 << IsEqual; 13506 if (CheckForReference(*this, E, PD)) { 13507 return; 13508 } 13509 } 13510 13511 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13512 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13513 std::string Str; 13514 llvm::raw_string_ostream S(Str); 13515 E->printPretty(S, nullptr, getPrintingPolicy()); 13516 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13517 : diag::warn_cast_nonnull_to_bool; 13518 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13519 << E->getSourceRange() << Range << IsEqual; 13520 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13521 }; 13522 13523 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13524 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13525 if (auto *Callee = Call->getDirectCallee()) { 13526 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13527 ComplainAboutNonnullParamOrCall(A); 13528 return; 13529 } 13530 } 13531 } 13532 13533 // Expect to find a single Decl. Skip anything more complicated. 13534 ValueDecl *D = nullptr; 13535 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13536 D = R->getDecl(); 13537 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13538 D = M->getMemberDecl(); 13539 } 13540 13541 // Weak Decls can be null. 13542 if (!D || D->isWeak()) 13543 return; 13544 13545 // Check for parameter decl with nonnull attribute 13546 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13547 if (getCurFunction() && 13548 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13549 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13550 ComplainAboutNonnullParamOrCall(A); 13551 return; 13552 } 13553 13554 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13555 // Skip function template not specialized yet. 13556 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13557 return; 13558 auto ParamIter = llvm::find(FD->parameters(), PV); 13559 assert(ParamIter != FD->param_end()); 13560 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13561 13562 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13563 if (!NonNull->args_size()) { 13564 ComplainAboutNonnullParamOrCall(NonNull); 13565 return; 13566 } 13567 13568 for (const ParamIdx &ArgNo : NonNull->args()) { 13569 if (ArgNo.getASTIndex() == ParamNo) { 13570 ComplainAboutNonnullParamOrCall(NonNull); 13571 return; 13572 } 13573 } 13574 } 13575 } 13576 } 13577 } 13578 13579 QualType T = D->getType(); 13580 const bool IsArray = T->isArrayType(); 13581 const bool IsFunction = T->isFunctionType(); 13582 13583 // Address of function is used to silence the function warning. 13584 if (IsAddressOf && IsFunction) { 13585 return; 13586 } 13587 13588 // Found nothing. 13589 if (!IsAddressOf && !IsFunction && !IsArray) 13590 return; 13591 13592 // Pretty print the expression for the diagnostic. 13593 std::string Str; 13594 llvm::raw_string_ostream S(Str); 13595 E->printPretty(S, nullptr, getPrintingPolicy()); 13596 13597 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13598 : diag::warn_impcast_pointer_to_bool; 13599 enum { 13600 AddressOf, 13601 FunctionPointer, 13602 ArrayPointer 13603 } DiagType; 13604 if (IsAddressOf) 13605 DiagType = AddressOf; 13606 else if (IsFunction) 13607 DiagType = FunctionPointer; 13608 else if (IsArray) 13609 DiagType = ArrayPointer; 13610 else 13611 llvm_unreachable("Could not determine diagnostic."); 13612 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13613 << Range << IsEqual; 13614 13615 if (!IsFunction) 13616 return; 13617 13618 // Suggest '&' to silence the function warning. 13619 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13620 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13621 13622 // Check to see if '()' fixit should be emitted. 13623 QualType ReturnType; 13624 UnresolvedSet<4> NonTemplateOverloads; 13625 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13626 if (ReturnType.isNull()) 13627 return; 13628 13629 if (IsCompare) { 13630 // There are two cases here. If there is null constant, the only suggest 13631 // for a pointer return type. If the null is 0, then suggest if the return 13632 // type is a pointer or an integer type. 13633 if (!ReturnType->isPointerType()) { 13634 if (NullKind == Expr::NPCK_ZeroExpression || 13635 NullKind == Expr::NPCK_ZeroLiteral) { 13636 if (!ReturnType->isIntegerType()) 13637 return; 13638 } else { 13639 return; 13640 } 13641 } 13642 } else { // !IsCompare 13643 // For function to bool, only suggest if the function pointer has bool 13644 // return type. 13645 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13646 return; 13647 } 13648 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13649 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13650 } 13651 13652 /// Diagnoses "dangerous" implicit conversions within the given 13653 /// expression (which is a full expression). Implements -Wconversion 13654 /// and -Wsign-compare. 13655 /// 13656 /// \param CC the "context" location of the implicit conversion, i.e. 13657 /// the most location of the syntactic entity requiring the implicit 13658 /// conversion 13659 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13660 // Don't diagnose in unevaluated contexts. 13661 if (isUnevaluatedContext()) 13662 return; 13663 13664 // Don't diagnose for value- or type-dependent expressions. 13665 if (E->isTypeDependent() || E->isValueDependent()) 13666 return; 13667 13668 // Check for array bounds violations in cases where the check isn't triggered 13669 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13670 // ArraySubscriptExpr is on the RHS of a variable initialization. 13671 CheckArrayAccess(E); 13672 13673 // This is not the right CC for (e.g.) a variable initialization. 13674 AnalyzeImplicitConversions(*this, E, CC); 13675 } 13676 13677 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13678 /// Input argument E is a logical expression. 13679 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13680 ::CheckBoolLikeConversion(*this, E, CC); 13681 } 13682 13683 /// Diagnose when expression is an integer constant expression and its evaluation 13684 /// results in integer overflow 13685 void Sema::CheckForIntOverflow (Expr *E) { 13686 // Use a work list to deal with nested struct initializers. 13687 SmallVector<Expr *, 2> Exprs(1, E); 13688 13689 do { 13690 Expr *OriginalE = Exprs.pop_back_val(); 13691 Expr *E = OriginalE->IgnoreParenCasts(); 13692 13693 if (isa<BinaryOperator>(E)) { 13694 E->EvaluateForOverflow(Context); 13695 continue; 13696 } 13697 13698 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13699 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13700 else if (isa<ObjCBoxedExpr>(OriginalE)) 13701 E->EvaluateForOverflow(Context); 13702 else if (auto Call = dyn_cast<CallExpr>(E)) 13703 Exprs.append(Call->arg_begin(), Call->arg_end()); 13704 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13705 Exprs.append(Message->arg_begin(), Message->arg_end()); 13706 } while (!Exprs.empty()); 13707 } 13708 13709 namespace { 13710 13711 /// Visitor for expressions which looks for unsequenced operations on the 13712 /// same object. 13713 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13714 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13715 13716 /// A tree of sequenced regions within an expression. Two regions are 13717 /// unsequenced if one is an ancestor or a descendent of the other. When we 13718 /// finish processing an expression with sequencing, such as a comma 13719 /// expression, we fold its tree nodes into its parent, since they are 13720 /// unsequenced with respect to nodes we will visit later. 13721 class SequenceTree { 13722 struct Value { 13723 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13724 unsigned Parent : 31; 13725 unsigned Merged : 1; 13726 }; 13727 SmallVector<Value, 8> Values; 13728 13729 public: 13730 /// A region within an expression which may be sequenced with respect 13731 /// to some other region. 13732 class Seq { 13733 friend class SequenceTree; 13734 13735 unsigned Index; 13736 13737 explicit Seq(unsigned N) : Index(N) {} 13738 13739 public: 13740 Seq() : Index(0) {} 13741 }; 13742 13743 SequenceTree() { Values.push_back(Value(0)); } 13744 Seq root() const { return Seq(0); } 13745 13746 /// Create a new sequence of operations, which is an unsequenced 13747 /// subset of \p Parent. This sequence of operations is sequenced with 13748 /// respect to other children of \p Parent. 13749 Seq allocate(Seq Parent) { 13750 Values.push_back(Value(Parent.Index)); 13751 return Seq(Values.size() - 1); 13752 } 13753 13754 /// Merge a sequence of operations into its parent. 13755 void merge(Seq S) { 13756 Values[S.Index].Merged = true; 13757 } 13758 13759 /// Determine whether two operations are unsequenced. This operation 13760 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13761 /// should have been merged into its parent as appropriate. 13762 bool isUnsequenced(Seq Cur, Seq Old) { 13763 unsigned C = representative(Cur.Index); 13764 unsigned Target = representative(Old.Index); 13765 while (C >= Target) { 13766 if (C == Target) 13767 return true; 13768 C = Values[C].Parent; 13769 } 13770 return false; 13771 } 13772 13773 private: 13774 /// Pick a representative for a sequence. 13775 unsigned representative(unsigned K) { 13776 if (Values[K].Merged) 13777 // Perform path compression as we go. 13778 return Values[K].Parent = representative(Values[K].Parent); 13779 return K; 13780 } 13781 }; 13782 13783 /// An object for which we can track unsequenced uses. 13784 using Object = const NamedDecl *; 13785 13786 /// Different flavors of object usage which we track. We only track the 13787 /// least-sequenced usage of each kind. 13788 enum UsageKind { 13789 /// A read of an object. Multiple unsequenced reads are OK. 13790 UK_Use, 13791 13792 /// A modification of an object which is sequenced before the value 13793 /// computation of the expression, such as ++n in C++. 13794 UK_ModAsValue, 13795 13796 /// A modification of an object which is not sequenced before the value 13797 /// computation of the expression, such as n++. 13798 UK_ModAsSideEffect, 13799 13800 UK_Count = UK_ModAsSideEffect + 1 13801 }; 13802 13803 /// Bundle together a sequencing region and the expression corresponding 13804 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13805 struct Usage { 13806 const Expr *UsageExpr; 13807 SequenceTree::Seq Seq; 13808 13809 Usage() : UsageExpr(nullptr), Seq() {} 13810 }; 13811 13812 struct UsageInfo { 13813 Usage Uses[UK_Count]; 13814 13815 /// Have we issued a diagnostic for this object already? 13816 bool Diagnosed; 13817 13818 UsageInfo() : Uses(), Diagnosed(false) {} 13819 }; 13820 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13821 13822 Sema &SemaRef; 13823 13824 /// Sequenced regions within the expression. 13825 SequenceTree Tree; 13826 13827 /// Declaration modifications and references which we have seen. 13828 UsageInfoMap UsageMap; 13829 13830 /// The region we are currently within. 13831 SequenceTree::Seq Region; 13832 13833 /// Filled in with declarations which were modified as a side-effect 13834 /// (that is, post-increment operations). 13835 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13836 13837 /// Expressions to check later. We defer checking these to reduce 13838 /// stack usage. 13839 SmallVectorImpl<const Expr *> &WorkList; 13840 13841 /// RAII object wrapping the visitation of a sequenced subexpression of an 13842 /// expression. At the end of this process, the side-effects of the evaluation 13843 /// become sequenced with respect to the value computation of the result, so 13844 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13845 /// UK_ModAsValue. 13846 struct SequencedSubexpression { 13847 SequencedSubexpression(SequenceChecker &Self) 13848 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13849 Self.ModAsSideEffect = &ModAsSideEffect; 13850 } 13851 13852 ~SequencedSubexpression() { 13853 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13854 // Add a new usage with usage kind UK_ModAsValue, and then restore 13855 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13856 // the previous one was empty). 13857 UsageInfo &UI = Self.UsageMap[M.first]; 13858 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13859 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13860 SideEffectUsage = M.second; 13861 } 13862 Self.ModAsSideEffect = OldModAsSideEffect; 13863 } 13864 13865 SequenceChecker &Self; 13866 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13867 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13868 }; 13869 13870 /// RAII object wrapping the visitation of a subexpression which we might 13871 /// choose to evaluate as a constant. If any subexpression is evaluated and 13872 /// found to be non-constant, this allows us to suppress the evaluation of 13873 /// the outer expression. 13874 class EvaluationTracker { 13875 public: 13876 EvaluationTracker(SequenceChecker &Self) 13877 : Self(Self), Prev(Self.EvalTracker) { 13878 Self.EvalTracker = this; 13879 } 13880 13881 ~EvaluationTracker() { 13882 Self.EvalTracker = Prev; 13883 if (Prev) 13884 Prev->EvalOK &= EvalOK; 13885 } 13886 13887 bool evaluate(const Expr *E, bool &Result) { 13888 if (!EvalOK || E->isValueDependent()) 13889 return false; 13890 EvalOK = E->EvaluateAsBooleanCondition( 13891 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13892 return EvalOK; 13893 } 13894 13895 private: 13896 SequenceChecker &Self; 13897 EvaluationTracker *Prev; 13898 bool EvalOK = true; 13899 } *EvalTracker = nullptr; 13900 13901 /// Find the object which is produced by the specified expression, 13902 /// if any. 13903 Object getObject(const Expr *E, bool Mod) const { 13904 E = E->IgnoreParenCasts(); 13905 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13906 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13907 return getObject(UO->getSubExpr(), Mod); 13908 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13909 if (BO->getOpcode() == BO_Comma) 13910 return getObject(BO->getRHS(), Mod); 13911 if (Mod && BO->isAssignmentOp()) 13912 return getObject(BO->getLHS(), Mod); 13913 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13914 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13915 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13916 return ME->getMemberDecl(); 13917 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13918 // FIXME: If this is a reference, map through to its value. 13919 return DRE->getDecl(); 13920 return nullptr; 13921 } 13922 13923 /// Note that an object \p O was modified or used by an expression 13924 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13925 /// the object \p O as obtained via the \p UsageMap. 13926 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13927 // Get the old usage for the given object and usage kind. 13928 Usage &U = UI.Uses[UK]; 13929 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13930 // If we have a modification as side effect and are in a sequenced 13931 // subexpression, save the old Usage so that we can restore it later 13932 // in SequencedSubexpression::~SequencedSubexpression. 13933 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13934 ModAsSideEffect->push_back(std::make_pair(O, U)); 13935 // Then record the new usage with the current sequencing region. 13936 U.UsageExpr = UsageExpr; 13937 U.Seq = Region; 13938 } 13939 } 13940 13941 /// Check whether a modification or use of an object \p O in an expression 13942 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13943 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13944 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13945 /// usage and false we are checking for a mod-use unsequenced usage. 13946 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13947 UsageKind OtherKind, bool IsModMod) { 13948 if (UI.Diagnosed) 13949 return; 13950 13951 const Usage &U = UI.Uses[OtherKind]; 13952 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13953 return; 13954 13955 const Expr *Mod = U.UsageExpr; 13956 const Expr *ModOrUse = UsageExpr; 13957 if (OtherKind == UK_Use) 13958 std::swap(Mod, ModOrUse); 13959 13960 SemaRef.DiagRuntimeBehavior( 13961 Mod->getExprLoc(), {Mod, ModOrUse}, 13962 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13963 : diag::warn_unsequenced_mod_use) 13964 << O << SourceRange(ModOrUse->getExprLoc())); 13965 UI.Diagnosed = true; 13966 } 13967 13968 // A note on note{Pre, Post}{Use, Mod}: 13969 // 13970 // (It helps to follow the algorithm with an expression such as 13971 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13972 // operations before C++17 and both are well-defined in C++17). 13973 // 13974 // When visiting a node which uses/modify an object we first call notePreUse 13975 // or notePreMod before visiting its sub-expression(s). At this point the 13976 // children of the current node have not yet been visited and so the eventual 13977 // uses/modifications resulting from the children of the current node have not 13978 // been recorded yet. 13979 // 13980 // We then visit the children of the current node. After that notePostUse or 13981 // notePostMod is called. These will 1) detect an unsequenced modification 13982 // as side effect (as in "k++ + k") and 2) add a new usage with the 13983 // appropriate usage kind. 13984 // 13985 // We also have to be careful that some operation sequences modification as 13986 // side effect as well (for example: || or ,). To account for this we wrap 13987 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13988 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13989 // which record usages which are modifications as side effect, and then 13990 // downgrade them (or more accurately restore the previous usage which was a 13991 // modification as side effect) when exiting the scope of the sequenced 13992 // subexpression. 13993 13994 void notePreUse(Object O, const Expr *UseExpr) { 13995 UsageInfo &UI = UsageMap[O]; 13996 // Uses conflict with other modifications. 13997 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 13998 } 13999 14000 void notePostUse(Object O, const Expr *UseExpr) { 14001 UsageInfo &UI = UsageMap[O]; 14002 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 14003 /*IsModMod=*/false); 14004 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 14005 } 14006 14007 void notePreMod(Object O, const Expr *ModExpr) { 14008 UsageInfo &UI = UsageMap[O]; 14009 // Modifications conflict with other modifications and with uses. 14010 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 14011 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 14012 } 14013 14014 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 14015 UsageInfo &UI = UsageMap[O]; 14016 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 14017 /*IsModMod=*/true); 14018 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 14019 } 14020 14021 public: 14022 SequenceChecker(Sema &S, const Expr *E, 14023 SmallVectorImpl<const Expr *> &WorkList) 14024 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 14025 Visit(E); 14026 // Silence a -Wunused-private-field since WorkList is now unused. 14027 // TODO: Evaluate if it can be used, and if not remove it. 14028 (void)this->WorkList; 14029 } 14030 14031 void VisitStmt(const Stmt *S) { 14032 // Skip all statements which aren't expressions for now. 14033 } 14034 14035 void VisitExpr(const Expr *E) { 14036 // By default, just recurse to evaluated subexpressions. 14037 Base::VisitStmt(E); 14038 } 14039 14040 void VisitCastExpr(const CastExpr *E) { 14041 Object O = Object(); 14042 if (E->getCastKind() == CK_LValueToRValue) 14043 O = getObject(E->getSubExpr(), false); 14044 14045 if (O) 14046 notePreUse(O, E); 14047 VisitExpr(E); 14048 if (O) 14049 notePostUse(O, E); 14050 } 14051 14052 void VisitSequencedExpressions(const Expr *SequencedBefore, 14053 const Expr *SequencedAfter) { 14054 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 14055 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 14056 SequenceTree::Seq OldRegion = Region; 14057 14058 { 14059 SequencedSubexpression SeqBefore(*this); 14060 Region = BeforeRegion; 14061 Visit(SequencedBefore); 14062 } 14063 14064 Region = AfterRegion; 14065 Visit(SequencedAfter); 14066 14067 Region = OldRegion; 14068 14069 Tree.merge(BeforeRegion); 14070 Tree.merge(AfterRegion); 14071 } 14072 14073 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 14074 // C++17 [expr.sub]p1: 14075 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 14076 // expression E1 is sequenced before the expression E2. 14077 if (SemaRef.getLangOpts().CPlusPlus17) 14078 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 14079 else { 14080 Visit(ASE->getLHS()); 14081 Visit(ASE->getRHS()); 14082 } 14083 } 14084 14085 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14086 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14087 void VisitBinPtrMem(const BinaryOperator *BO) { 14088 // C++17 [expr.mptr.oper]p4: 14089 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 14090 // the expression E1 is sequenced before the expression E2. 14091 if (SemaRef.getLangOpts().CPlusPlus17) 14092 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14093 else { 14094 Visit(BO->getLHS()); 14095 Visit(BO->getRHS()); 14096 } 14097 } 14098 14099 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14100 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14101 void VisitBinShlShr(const BinaryOperator *BO) { 14102 // C++17 [expr.shift]p4: 14103 // The expression E1 is sequenced before the expression E2. 14104 if (SemaRef.getLangOpts().CPlusPlus17) 14105 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14106 else { 14107 Visit(BO->getLHS()); 14108 Visit(BO->getRHS()); 14109 } 14110 } 14111 14112 void VisitBinComma(const BinaryOperator *BO) { 14113 // C++11 [expr.comma]p1: 14114 // Every value computation and side effect associated with the left 14115 // expression is sequenced before every value computation and side 14116 // effect associated with the right expression. 14117 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14118 } 14119 14120 void VisitBinAssign(const BinaryOperator *BO) { 14121 SequenceTree::Seq RHSRegion; 14122 SequenceTree::Seq LHSRegion; 14123 if (SemaRef.getLangOpts().CPlusPlus17) { 14124 RHSRegion = Tree.allocate(Region); 14125 LHSRegion = Tree.allocate(Region); 14126 } else { 14127 RHSRegion = Region; 14128 LHSRegion = Region; 14129 } 14130 SequenceTree::Seq OldRegion = Region; 14131 14132 // C++11 [expr.ass]p1: 14133 // [...] the assignment is sequenced after the value computation 14134 // of the right and left operands, [...] 14135 // 14136 // so check it before inspecting the operands and update the 14137 // map afterwards. 14138 Object O = getObject(BO->getLHS(), /*Mod=*/true); 14139 if (O) 14140 notePreMod(O, BO); 14141 14142 if (SemaRef.getLangOpts().CPlusPlus17) { 14143 // C++17 [expr.ass]p1: 14144 // [...] The right operand is sequenced before the left operand. [...] 14145 { 14146 SequencedSubexpression SeqBefore(*this); 14147 Region = RHSRegion; 14148 Visit(BO->getRHS()); 14149 } 14150 14151 Region = LHSRegion; 14152 Visit(BO->getLHS()); 14153 14154 if (O && isa<CompoundAssignOperator>(BO)) 14155 notePostUse(O, BO); 14156 14157 } else { 14158 // C++11 does not specify any sequencing between the LHS and RHS. 14159 Region = LHSRegion; 14160 Visit(BO->getLHS()); 14161 14162 if (O && isa<CompoundAssignOperator>(BO)) 14163 notePostUse(O, BO); 14164 14165 Region = RHSRegion; 14166 Visit(BO->getRHS()); 14167 } 14168 14169 // C++11 [expr.ass]p1: 14170 // the assignment is sequenced [...] before the value computation of the 14171 // assignment expression. 14172 // C11 6.5.16/3 has no such rule. 14173 Region = OldRegion; 14174 if (O) 14175 notePostMod(O, BO, 14176 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14177 : UK_ModAsSideEffect); 14178 if (SemaRef.getLangOpts().CPlusPlus17) { 14179 Tree.merge(RHSRegion); 14180 Tree.merge(LHSRegion); 14181 } 14182 } 14183 14184 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 14185 VisitBinAssign(CAO); 14186 } 14187 14188 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14189 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14190 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 14191 Object O = getObject(UO->getSubExpr(), true); 14192 if (!O) 14193 return VisitExpr(UO); 14194 14195 notePreMod(O, UO); 14196 Visit(UO->getSubExpr()); 14197 // C++11 [expr.pre.incr]p1: 14198 // the expression ++x is equivalent to x+=1 14199 notePostMod(O, UO, 14200 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14201 : UK_ModAsSideEffect); 14202 } 14203 14204 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14205 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14206 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 14207 Object O = getObject(UO->getSubExpr(), true); 14208 if (!O) 14209 return VisitExpr(UO); 14210 14211 notePreMod(O, UO); 14212 Visit(UO->getSubExpr()); 14213 notePostMod(O, UO, UK_ModAsSideEffect); 14214 } 14215 14216 void VisitBinLOr(const BinaryOperator *BO) { 14217 // C++11 [expr.log.or]p2: 14218 // If the second expression is evaluated, every value computation and 14219 // side effect associated with the first expression is sequenced before 14220 // every value computation and side effect associated with the 14221 // second expression. 14222 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14223 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14224 SequenceTree::Seq OldRegion = Region; 14225 14226 EvaluationTracker Eval(*this); 14227 { 14228 SequencedSubexpression Sequenced(*this); 14229 Region = LHSRegion; 14230 Visit(BO->getLHS()); 14231 } 14232 14233 // C++11 [expr.log.or]p1: 14234 // [...] the second operand is not evaluated if the first operand 14235 // evaluates to true. 14236 bool EvalResult = false; 14237 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14238 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 14239 if (ShouldVisitRHS) { 14240 Region = RHSRegion; 14241 Visit(BO->getRHS()); 14242 } 14243 14244 Region = OldRegion; 14245 Tree.merge(LHSRegion); 14246 Tree.merge(RHSRegion); 14247 } 14248 14249 void VisitBinLAnd(const BinaryOperator *BO) { 14250 // C++11 [expr.log.and]p2: 14251 // If the second expression is evaluated, every value computation and 14252 // side effect associated with the first expression is sequenced before 14253 // every value computation and side effect associated with the 14254 // second expression. 14255 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14256 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14257 SequenceTree::Seq OldRegion = Region; 14258 14259 EvaluationTracker Eval(*this); 14260 { 14261 SequencedSubexpression Sequenced(*this); 14262 Region = LHSRegion; 14263 Visit(BO->getLHS()); 14264 } 14265 14266 // C++11 [expr.log.and]p1: 14267 // [...] the second operand is not evaluated if the first operand is false. 14268 bool EvalResult = false; 14269 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14270 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 14271 if (ShouldVisitRHS) { 14272 Region = RHSRegion; 14273 Visit(BO->getRHS()); 14274 } 14275 14276 Region = OldRegion; 14277 Tree.merge(LHSRegion); 14278 Tree.merge(RHSRegion); 14279 } 14280 14281 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 14282 // C++11 [expr.cond]p1: 14283 // [...] Every value computation and side effect associated with the first 14284 // expression is sequenced before every value computation and side effect 14285 // associated with the second or third expression. 14286 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 14287 14288 // No sequencing is specified between the true and false expression. 14289 // However since exactly one of both is going to be evaluated we can 14290 // consider them to be sequenced. This is needed to avoid warning on 14291 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 14292 // both the true and false expressions because we can't evaluate x. 14293 // This will still allow us to detect an expression like (pre C++17) 14294 // "(x ? y += 1 : y += 2) = y". 14295 // 14296 // We don't wrap the visitation of the true and false expression with 14297 // SequencedSubexpression because we don't want to downgrade modifications 14298 // as side effect in the true and false expressions after the visition 14299 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 14300 // not warn between the two "y++", but we should warn between the "y++" 14301 // and the "y". 14302 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 14303 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 14304 SequenceTree::Seq OldRegion = Region; 14305 14306 EvaluationTracker Eval(*this); 14307 { 14308 SequencedSubexpression Sequenced(*this); 14309 Region = ConditionRegion; 14310 Visit(CO->getCond()); 14311 } 14312 14313 // C++11 [expr.cond]p1: 14314 // [...] The first expression is contextually converted to bool (Clause 4). 14315 // It is evaluated and if it is true, the result of the conditional 14316 // expression is the value of the second expression, otherwise that of the 14317 // third expression. Only one of the second and third expressions is 14318 // evaluated. [...] 14319 bool EvalResult = false; 14320 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 14321 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 14322 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 14323 if (ShouldVisitTrueExpr) { 14324 Region = TrueRegion; 14325 Visit(CO->getTrueExpr()); 14326 } 14327 if (ShouldVisitFalseExpr) { 14328 Region = FalseRegion; 14329 Visit(CO->getFalseExpr()); 14330 } 14331 14332 Region = OldRegion; 14333 Tree.merge(ConditionRegion); 14334 Tree.merge(TrueRegion); 14335 Tree.merge(FalseRegion); 14336 } 14337 14338 void VisitCallExpr(const CallExpr *CE) { 14339 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 14340 14341 if (CE->isUnevaluatedBuiltinCall(Context)) 14342 return; 14343 14344 // C++11 [intro.execution]p15: 14345 // When calling a function [...], every value computation and side effect 14346 // associated with any argument expression, or with the postfix expression 14347 // designating the called function, is sequenced before execution of every 14348 // expression or statement in the body of the function [and thus before 14349 // the value computation of its result]. 14350 SequencedSubexpression Sequenced(*this); 14351 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 14352 // C++17 [expr.call]p5 14353 // The postfix-expression is sequenced before each expression in the 14354 // expression-list and any default argument. [...] 14355 SequenceTree::Seq CalleeRegion; 14356 SequenceTree::Seq OtherRegion; 14357 if (SemaRef.getLangOpts().CPlusPlus17) { 14358 CalleeRegion = Tree.allocate(Region); 14359 OtherRegion = Tree.allocate(Region); 14360 } else { 14361 CalleeRegion = Region; 14362 OtherRegion = Region; 14363 } 14364 SequenceTree::Seq OldRegion = Region; 14365 14366 // Visit the callee expression first. 14367 Region = CalleeRegion; 14368 if (SemaRef.getLangOpts().CPlusPlus17) { 14369 SequencedSubexpression Sequenced(*this); 14370 Visit(CE->getCallee()); 14371 } else { 14372 Visit(CE->getCallee()); 14373 } 14374 14375 // Then visit the argument expressions. 14376 Region = OtherRegion; 14377 for (const Expr *Argument : CE->arguments()) 14378 Visit(Argument); 14379 14380 Region = OldRegion; 14381 if (SemaRef.getLangOpts().CPlusPlus17) { 14382 Tree.merge(CalleeRegion); 14383 Tree.merge(OtherRegion); 14384 } 14385 }); 14386 } 14387 14388 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 14389 // C++17 [over.match.oper]p2: 14390 // [...] the operator notation is first transformed to the equivalent 14391 // function-call notation as summarized in Table 12 (where @ denotes one 14392 // of the operators covered in the specified subclause). However, the 14393 // operands are sequenced in the order prescribed for the built-in 14394 // operator (Clause 8). 14395 // 14396 // From the above only overloaded binary operators and overloaded call 14397 // operators have sequencing rules in C++17 that we need to handle 14398 // separately. 14399 if (!SemaRef.getLangOpts().CPlusPlus17 || 14400 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 14401 return VisitCallExpr(CXXOCE); 14402 14403 enum { 14404 NoSequencing, 14405 LHSBeforeRHS, 14406 RHSBeforeLHS, 14407 LHSBeforeRest 14408 } SequencingKind; 14409 switch (CXXOCE->getOperator()) { 14410 case OO_Equal: 14411 case OO_PlusEqual: 14412 case OO_MinusEqual: 14413 case OO_StarEqual: 14414 case OO_SlashEqual: 14415 case OO_PercentEqual: 14416 case OO_CaretEqual: 14417 case OO_AmpEqual: 14418 case OO_PipeEqual: 14419 case OO_LessLessEqual: 14420 case OO_GreaterGreaterEqual: 14421 SequencingKind = RHSBeforeLHS; 14422 break; 14423 14424 case OO_LessLess: 14425 case OO_GreaterGreater: 14426 case OO_AmpAmp: 14427 case OO_PipePipe: 14428 case OO_Comma: 14429 case OO_ArrowStar: 14430 case OO_Subscript: 14431 SequencingKind = LHSBeforeRHS; 14432 break; 14433 14434 case OO_Call: 14435 SequencingKind = LHSBeforeRest; 14436 break; 14437 14438 default: 14439 SequencingKind = NoSequencing; 14440 break; 14441 } 14442 14443 if (SequencingKind == NoSequencing) 14444 return VisitCallExpr(CXXOCE); 14445 14446 // This is a call, so all subexpressions are sequenced before the result. 14447 SequencedSubexpression Sequenced(*this); 14448 14449 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 14450 assert(SemaRef.getLangOpts().CPlusPlus17 && 14451 "Should only get there with C++17 and above!"); 14452 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 14453 "Should only get there with an overloaded binary operator" 14454 " or an overloaded call operator!"); 14455 14456 if (SequencingKind == LHSBeforeRest) { 14457 assert(CXXOCE->getOperator() == OO_Call && 14458 "We should only have an overloaded call operator here!"); 14459 14460 // This is very similar to VisitCallExpr, except that we only have the 14461 // C++17 case. The postfix-expression is the first argument of the 14462 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 14463 // are in the following arguments. 14464 // 14465 // Note that we intentionally do not visit the callee expression since 14466 // it is just a decayed reference to a function. 14467 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 14468 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 14469 SequenceTree::Seq OldRegion = Region; 14470 14471 assert(CXXOCE->getNumArgs() >= 1 && 14472 "An overloaded call operator must have at least one argument" 14473 " for the postfix-expression!"); 14474 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 14475 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 14476 CXXOCE->getNumArgs() - 1); 14477 14478 // Visit the postfix-expression first. 14479 { 14480 Region = PostfixExprRegion; 14481 SequencedSubexpression Sequenced(*this); 14482 Visit(PostfixExpr); 14483 } 14484 14485 // Then visit the argument expressions. 14486 Region = ArgsRegion; 14487 for (const Expr *Arg : Args) 14488 Visit(Arg); 14489 14490 Region = OldRegion; 14491 Tree.merge(PostfixExprRegion); 14492 Tree.merge(ArgsRegion); 14493 } else { 14494 assert(CXXOCE->getNumArgs() == 2 && 14495 "Should only have two arguments here!"); 14496 assert((SequencingKind == LHSBeforeRHS || 14497 SequencingKind == RHSBeforeLHS) && 14498 "Unexpected sequencing kind!"); 14499 14500 // We do not visit the callee expression since it is just a decayed 14501 // reference to a function. 14502 const Expr *E1 = CXXOCE->getArg(0); 14503 const Expr *E2 = CXXOCE->getArg(1); 14504 if (SequencingKind == RHSBeforeLHS) 14505 std::swap(E1, E2); 14506 14507 return VisitSequencedExpressions(E1, E2); 14508 } 14509 }); 14510 } 14511 14512 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14513 // This is a call, so all subexpressions are sequenced before the result. 14514 SequencedSubexpression Sequenced(*this); 14515 14516 if (!CCE->isListInitialization()) 14517 return VisitExpr(CCE); 14518 14519 // In C++11, list initializations are sequenced. 14520 SmallVector<SequenceTree::Seq, 32> Elts; 14521 SequenceTree::Seq Parent = Region; 14522 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14523 E = CCE->arg_end(); 14524 I != E; ++I) { 14525 Region = Tree.allocate(Parent); 14526 Elts.push_back(Region); 14527 Visit(*I); 14528 } 14529 14530 // Forget that the initializers are sequenced. 14531 Region = Parent; 14532 for (unsigned I = 0; I < Elts.size(); ++I) 14533 Tree.merge(Elts[I]); 14534 } 14535 14536 void VisitInitListExpr(const InitListExpr *ILE) { 14537 if (!SemaRef.getLangOpts().CPlusPlus11) 14538 return VisitExpr(ILE); 14539 14540 // In C++11, list initializations are sequenced. 14541 SmallVector<SequenceTree::Seq, 32> Elts; 14542 SequenceTree::Seq Parent = Region; 14543 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14544 const Expr *E = ILE->getInit(I); 14545 if (!E) 14546 continue; 14547 Region = Tree.allocate(Parent); 14548 Elts.push_back(Region); 14549 Visit(E); 14550 } 14551 14552 // Forget that the initializers are sequenced. 14553 Region = Parent; 14554 for (unsigned I = 0; I < Elts.size(); ++I) 14555 Tree.merge(Elts[I]); 14556 } 14557 }; 14558 14559 } // namespace 14560 14561 void Sema::CheckUnsequencedOperations(const Expr *E) { 14562 SmallVector<const Expr *, 8> WorkList; 14563 WorkList.push_back(E); 14564 while (!WorkList.empty()) { 14565 const Expr *Item = WorkList.pop_back_val(); 14566 SequenceChecker(*this, Item, WorkList); 14567 } 14568 } 14569 14570 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14571 bool IsConstexpr) { 14572 llvm::SaveAndRestore<bool> ConstantContext( 14573 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14574 CheckImplicitConversions(E, CheckLoc); 14575 if (!E->isInstantiationDependent()) 14576 CheckUnsequencedOperations(E); 14577 if (!IsConstexpr && !E->isValueDependent()) 14578 CheckForIntOverflow(E); 14579 DiagnoseMisalignedMembers(); 14580 } 14581 14582 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14583 FieldDecl *BitField, 14584 Expr *Init) { 14585 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14586 } 14587 14588 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14589 SourceLocation Loc) { 14590 if (!PType->isVariablyModifiedType()) 14591 return; 14592 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14593 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14594 return; 14595 } 14596 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14597 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14598 return; 14599 } 14600 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14601 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14602 return; 14603 } 14604 14605 const ArrayType *AT = S.Context.getAsArrayType(PType); 14606 if (!AT) 14607 return; 14608 14609 if (AT->getSizeModifier() != ArrayType::Star) { 14610 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14611 return; 14612 } 14613 14614 S.Diag(Loc, diag::err_array_star_in_function_definition); 14615 } 14616 14617 /// CheckParmsForFunctionDef - Check that the parameters of the given 14618 /// function are appropriate for the definition of a function. This 14619 /// takes care of any checks that cannot be performed on the 14620 /// declaration itself, e.g., that the types of each of the function 14621 /// parameters are complete. 14622 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14623 bool CheckParameterNames) { 14624 bool HasInvalidParm = false; 14625 for (ParmVarDecl *Param : Parameters) { 14626 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14627 // function declarator that is part of a function definition of 14628 // that function shall not have incomplete type. 14629 // 14630 // This is also C++ [dcl.fct]p6. 14631 if (!Param->isInvalidDecl() && 14632 RequireCompleteType(Param->getLocation(), Param->getType(), 14633 diag::err_typecheck_decl_incomplete_type)) { 14634 Param->setInvalidDecl(); 14635 HasInvalidParm = true; 14636 } 14637 14638 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14639 // declaration of each parameter shall include an identifier. 14640 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14641 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14642 // Diagnose this as an extension in C17 and earlier. 14643 if (!getLangOpts().C2x) 14644 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14645 } 14646 14647 // C99 6.7.5.3p12: 14648 // If the function declarator is not part of a definition of that 14649 // function, parameters may have incomplete type and may use the [*] 14650 // notation in their sequences of declarator specifiers to specify 14651 // variable length array types. 14652 QualType PType = Param->getOriginalType(); 14653 // FIXME: This diagnostic should point the '[*]' if source-location 14654 // information is added for it. 14655 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14656 14657 // If the parameter is a c++ class type and it has to be destructed in the 14658 // callee function, declare the destructor so that it can be called by the 14659 // callee function. Do not perform any direct access check on the dtor here. 14660 if (!Param->isInvalidDecl()) { 14661 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14662 if (!ClassDecl->isInvalidDecl() && 14663 !ClassDecl->hasIrrelevantDestructor() && 14664 !ClassDecl->isDependentContext() && 14665 ClassDecl->isParamDestroyedInCallee()) { 14666 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14667 MarkFunctionReferenced(Param->getLocation(), Destructor); 14668 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14669 } 14670 } 14671 } 14672 14673 // Parameters with the pass_object_size attribute only need to be marked 14674 // constant at function definitions. Because we lack information about 14675 // whether we're on a declaration or definition when we're instantiating the 14676 // attribute, we need to check for constness here. 14677 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14678 if (!Param->getType().isConstQualified()) 14679 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14680 << Attr->getSpelling() << 1; 14681 14682 // Check for parameter names shadowing fields from the class. 14683 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14684 // The owning context for the parameter should be the function, but we 14685 // want to see if this function's declaration context is a record. 14686 DeclContext *DC = Param->getDeclContext(); 14687 if (DC && DC->isFunctionOrMethod()) { 14688 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14689 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14690 RD, /*DeclIsField*/ false); 14691 } 14692 } 14693 } 14694 14695 return HasInvalidParm; 14696 } 14697 14698 Optional<std::pair<CharUnits, CharUnits>> 14699 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14700 14701 /// Compute the alignment and offset of the base class object given the 14702 /// derived-to-base cast expression and the alignment and offset of the derived 14703 /// class object. 14704 static std::pair<CharUnits, CharUnits> 14705 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14706 CharUnits BaseAlignment, CharUnits Offset, 14707 ASTContext &Ctx) { 14708 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14709 ++PathI) { 14710 const CXXBaseSpecifier *Base = *PathI; 14711 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14712 if (Base->isVirtual()) { 14713 // The complete object may have a lower alignment than the non-virtual 14714 // alignment of the base, in which case the base may be misaligned. Choose 14715 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14716 // conservative lower bound of the complete object alignment. 14717 CharUnits NonVirtualAlignment = 14718 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14719 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14720 Offset = CharUnits::Zero(); 14721 } else { 14722 const ASTRecordLayout &RL = 14723 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14724 Offset += RL.getBaseClassOffset(BaseDecl); 14725 } 14726 DerivedType = Base->getType(); 14727 } 14728 14729 return std::make_pair(BaseAlignment, Offset); 14730 } 14731 14732 /// Compute the alignment and offset of a binary additive operator. 14733 static Optional<std::pair<CharUnits, CharUnits>> 14734 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14735 bool IsSub, ASTContext &Ctx) { 14736 QualType PointeeType = PtrE->getType()->getPointeeType(); 14737 14738 if (!PointeeType->isConstantSizeType()) 14739 return llvm::None; 14740 14741 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14742 14743 if (!P) 14744 return llvm::None; 14745 14746 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14747 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14748 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14749 if (IsSub) 14750 Offset = -Offset; 14751 return std::make_pair(P->first, P->second + Offset); 14752 } 14753 14754 // If the integer expression isn't a constant expression, compute the lower 14755 // bound of the alignment using the alignment and offset of the pointer 14756 // expression and the element size. 14757 return std::make_pair( 14758 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14759 CharUnits::Zero()); 14760 } 14761 14762 /// This helper function takes an lvalue expression and returns the alignment of 14763 /// a VarDecl and a constant offset from the VarDecl. 14764 Optional<std::pair<CharUnits, CharUnits>> 14765 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14766 E = E->IgnoreParens(); 14767 switch (E->getStmtClass()) { 14768 default: 14769 break; 14770 case Stmt::CStyleCastExprClass: 14771 case Stmt::CXXStaticCastExprClass: 14772 case Stmt::ImplicitCastExprClass: { 14773 auto *CE = cast<CastExpr>(E); 14774 const Expr *From = CE->getSubExpr(); 14775 switch (CE->getCastKind()) { 14776 default: 14777 break; 14778 case CK_NoOp: 14779 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14780 case CK_UncheckedDerivedToBase: 14781 case CK_DerivedToBase: { 14782 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14783 if (!P) 14784 break; 14785 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14786 P->second, Ctx); 14787 } 14788 } 14789 break; 14790 } 14791 case Stmt::ArraySubscriptExprClass: { 14792 auto *ASE = cast<ArraySubscriptExpr>(E); 14793 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14794 false, Ctx); 14795 } 14796 case Stmt::DeclRefExprClass: { 14797 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14798 // FIXME: If VD is captured by copy or is an escaping __block variable, 14799 // use the alignment of VD's type. 14800 if (!VD->getType()->isReferenceType()) 14801 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14802 if (VD->hasInit()) 14803 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14804 } 14805 break; 14806 } 14807 case Stmt::MemberExprClass: { 14808 auto *ME = cast<MemberExpr>(E); 14809 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14810 if (!FD || FD->getType()->isReferenceType() || 14811 FD->getParent()->isInvalidDecl()) 14812 break; 14813 Optional<std::pair<CharUnits, CharUnits>> P; 14814 if (ME->isArrow()) 14815 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14816 else 14817 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14818 if (!P) 14819 break; 14820 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14821 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14822 return std::make_pair(P->first, 14823 P->second + CharUnits::fromQuantity(Offset)); 14824 } 14825 case Stmt::UnaryOperatorClass: { 14826 auto *UO = cast<UnaryOperator>(E); 14827 switch (UO->getOpcode()) { 14828 default: 14829 break; 14830 case UO_Deref: 14831 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14832 } 14833 break; 14834 } 14835 case Stmt::BinaryOperatorClass: { 14836 auto *BO = cast<BinaryOperator>(E); 14837 auto Opcode = BO->getOpcode(); 14838 switch (Opcode) { 14839 default: 14840 break; 14841 case BO_Comma: 14842 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14843 } 14844 break; 14845 } 14846 } 14847 return llvm::None; 14848 } 14849 14850 /// This helper function takes a pointer expression and returns the alignment of 14851 /// a VarDecl and a constant offset from the VarDecl. 14852 Optional<std::pair<CharUnits, CharUnits>> 14853 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14854 E = E->IgnoreParens(); 14855 switch (E->getStmtClass()) { 14856 default: 14857 break; 14858 case Stmt::CStyleCastExprClass: 14859 case Stmt::CXXStaticCastExprClass: 14860 case Stmt::ImplicitCastExprClass: { 14861 auto *CE = cast<CastExpr>(E); 14862 const Expr *From = CE->getSubExpr(); 14863 switch (CE->getCastKind()) { 14864 default: 14865 break; 14866 case CK_NoOp: 14867 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14868 case CK_ArrayToPointerDecay: 14869 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14870 case CK_UncheckedDerivedToBase: 14871 case CK_DerivedToBase: { 14872 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14873 if (!P) 14874 break; 14875 return getDerivedToBaseAlignmentAndOffset( 14876 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14877 } 14878 } 14879 break; 14880 } 14881 case Stmt::CXXThisExprClass: { 14882 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14883 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14884 return std::make_pair(Alignment, CharUnits::Zero()); 14885 } 14886 case Stmt::UnaryOperatorClass: { 14887 auto *UO = cast<UnaryOperator>(E); 14888 if (UO->getOpcode() == UO_AddrOf) 14889 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14890 break; 14891 } 14892 case Stmt::BinaryOperatorClass: { 14893 auto *BO = cast<BinaryOperator>(E); 14894 auto Opcode = BO->getOpcode(); 14895 switch (Opcode) { 14896 default: 14897 break; 14898 case BO_Add: 14899 case BO_Sub: { 14900 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14901 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14902 std::swap(LHS, RHS); 14903 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14904 Ctx); 14905 } 14906 case BO_Comma: 14907 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14908 } 14909 break; 14910 } 14911 } 14912 return llvm::None; 14913 } 14914 14915 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14916 // See if we can compute the alignment of a VarDecl and an offset from it. 14917 Optional<std::pair<CharUnits, CharUnits>> P = 14918 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14919 14920 if (P) 14921 return P->first.alignmentAtOffset(P->second); 14922 14923 // If that failed, return the type's alignment. 14924 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14925 } 14926 14927 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14928 /// pointer cast increases the alignment requirements. 14929 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14930 // This is actually a lot of work to potentially be doing on every 14931 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14932 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14933 return; 14934 14935 // Ignore dependent types. 14936 if (T->isDependentType() || Op->getType()->isDependentType()) 14937 return; 14938 14939 // Require that the destination be a pointer type. 14940 const PointerType *DestPtr = T->getAs<PointerType>(); 14941 if (!DestPtr) return; 14942 14943 // If the destination has alignment 1, we're done. 14944 QualType DestPointee = DestPtr->getPointeeType(); 14945 if (DestPointee->isIncompleteType()) return; 14946 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14947 if (DestAlign.isOne()) return; 14948 14949 // Require that the source be a pointer type. 14950 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14951 if (!SrcPtr) return; 14952 QualType SrcPointee = SrcPtr->getPointeeType(); 14953 14954 // Explicitly allow casts from cv void*. We already implicitly 14955 // allowed casts to cv void*, since they have alignment 1. 14956 // Also allow casts involving incomplete types, which implicitly 14957 // includes 'void'. 14958 if (SrcPointee->isIncompleteType()) return; 14959 14960 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14961 14962 if (SrcAlign >= DestAlign) return; 14963 14964 Diag(TRange.getBegin(), diag::warn_cast_align) 14965 << Op->getType() << T 14966 << static_cast<unsigned>(SrcAlign.getQuantity()) 14967 << static_cast<unsigned>(DestAlign.getQuantity()) 14968 << TRange << Op->getSourceRange(); 14969 } 14970 14971 /// Check whether this array fits the idiom of a size-one tail padded 14972 /// array member of a struct. 14973 /// 14974 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14975 /// commonly used to emulate flexible arrays in C89 code. 14976 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14977 const NamedDecl *ND) { 14978 if (Size != 1 || !ND) return false; 14979 14980 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14981 if (!FD) return false; 14982 14983 // Don't consider sizes resulting from macro expansions or template argument 14984 // substitution to form C89 tail-padded arrays. 14985 14986 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14987 while (TInfo) { 14988 TypeLoc TL = TInfo->getTypeLoc(); 14989 // Look through typedefs. 14990 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14991 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 14992 TInfo = TDL->getTypeSourceInfo(); 14993 continue; 14994 } 14995 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 14996 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 14997 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 14998 return false; 14999 } 15000 break; 15001 } 15002 15003 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 15004 if (!RD) return false; 15005 if (RD->isUnion()) return false; 15006 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15007 if (!CRD->isStandardLayout()) return false; 15008 } 15009 15010 // See if this is the last field decl in the record. 15011 const Decl *D = FD; 15012 while ((D = D->getNextDeclInContext())) 15013 if (isa<FieldDecl>(D)) 15014 return false; 15015 return true; 15016 } 15017 15018 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 15019 const ArraySubscriptExpr *ASE, 15020 bool AllowOnePastEnd, bool IndexNegated) { 15021 // Already diagnosed by the constant evaluator. 15022 if (isConstantEvaluated()) 15023 return; 15024 15025 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 15026 if (IndexExpr->isValueDependent()) 15027 return; 15028 15029 const Type *EffectiveType = 15030 BaseExpr->getType()->getPointeeOrArrayElementType(); 15031 BaseExpr = BaseExpr->IgnoreParenCasts(); 15032 const ConstantArrayType *ArrayTy = 15033 Context.getAsConstantArrayType(BaseExpr->getType()); 15034 15035 const Type *BaseType = 15036 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 15037 bool IsUnboundedArray = (BaseType == nullptr); 15038 if (EffectiveType->isDependentType() || 15039 (!IsUnboundedArray && BaseType->isDependentType())) 15040 return; 15041 15042 Expr::EvalResult Result; 15043 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 15044 return; 15045 15046 llvm::APSInt index = Result.Val.getInt(); 15047 if (IndexNegated) { 15048 index.setIsUnsigned(false); 15049 index = -index; 15050 } 15051 15052 const NamedDecl *ND = nullptr; 15053 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15054 ND = DRE->getDecl(); 15055 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 15056 ND = ME->getMemberDecl(); 15057 15058 if (IsUnboundedArray) { 15059 if (index.isUnsigned() || !index.isNegative()) { 15060 const auto &ASTC = getASTContext(); 15061 unsigned AddrBits = 15062 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 15063 EffectiveType->getCanonicalTypeInternal())); 15064 if (index.getBitWidth() < AddrBits) 15065 index = index.zext(AddrBits); 15066 Optional<CharUnits> ElemCharUnits = 15067 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 15068 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 15069 // pointer) bounds-checking isn't meaningful. 15070 if (!ElemCharUnits) 15071 return; 15072 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 15073 // If index has more active bits than address space, we already know 15074 // we have a bounds violation to warn about. Otherwise, compute 15075 // address of (index + 1)th element, and warn about bounds violation 15076 // only if that address exceeds address space. 15077 if (index.getActiveBits() <= AddrBits) { 15078 bool Overflow; 15079 llvm::APInt Product(index); 15080 Product += 1; 15081 Product = Product.umul_ov(ElemBytes, Overflow); 15082 if (!Overflow && Product.getActiveBits() <= AddrBits) 15083 return; 15084 } 15085 15086 // Need to compute max possible elements in address space, since that 15087 // is included in diag message. 15088 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 15089 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 15090 MaxElems += 1; 15091 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 15092 MaxElems = MaxElems.udiv(ElemBytes); 15093 15094 unsigned DiagID = 15095 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 15096 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 15097 15098 // Diag message shows element size in bits and in "bytes" (platform- 15099 // dependent CharUnits) 15100 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15101 PDiag(DiagID) 15102 << toString(index, 10, true) << AddrBits 15103 << (unsigned)ASTC.toBits(*ElemCharUnits) 15104 << toString(ElemBytes, 10, false) 15105 << toString(MaxElems, 10, false) 15106 << (unsigned)MaxElems.getLimitedValue(~0U) 15107 << IndexExpr->getSourceRange()); 15108 15109 if (!ND) { 15110 // Try harder to find a NamedDecl to point at in the note. 15111 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15112 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15113 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15114 ND = DRE->getDecl(); 15115 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15116 ND = ME->getMemberDecl(); 15117 } 15118 15119 if (ND) 15120 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15121 PDiag(diag::note_array_declared_here) << ND); 15122 } 15123 return; 15124 } 15125 15126 if (index.isUnsigned() || !index.isNegative()) { 15127 // It is possible that the type of the base expression after 15128 // IgnoreParenCasts is incomplete, even though the type of the base 15129 // expression before IgnoreParenCasts is complete (see PR39746 for an 15130 // example). In this case we have no information about whether the array 15131 // access exceeds the array bounds. However we can still diagnose an array 15132 // access which precedes the array bounds. 15133 if (BaseType->isIncompleteType()) 15134 return; 15135 15136 llvm::APInt size = ArrayTy->getSize(); 15137 if (!size.isStrictlyPositive()) 15138 return; 15139 15140 if (BaseType != EffectiveType) { 15141 // Make sure we're comparing apples to apples when comparing index to size 15142 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 15143 uint64_t array_typesize = Context.getTypeSize(BaseType); 15144 // Handle ptrarith_typesize being zero, such as when casting to void* 15145 if (!ptrarith_typesize) ptrarith_typesize = 1; 15146 if (ptrarith_typesize != array_typesize) { 15147 // There's a cast to a different size type involved 15148 uint64_t ratio = array_typesize / ptrarith_typesize; 15149 // TODO: Be smarter about handling cases where array_typesize is not a 15150 // multiple of ptrarith_typesize 15151 if (ptrarith_typesize * ratio == array_typesize) 15152 size *= llvm::APInt(size.getBitWidth(), ratio); 15153 } 15154 } 15155 15156 if (size.getBitWidth() > index.getBitWidth()) 15157 index = index.zext(size.getBitWidth()); 15158 else if (size.getBitWidth() < index.getBitWidth()) 15159 size = size.zext(index.getBitWidth()); 15160 15161 // For array subscripting the index must be less than size, but for pointer 15162 // arithmetic also allow the index (offset) to be equal to size since 15163 // computing the next address after the end of the array is legal and 15164 // commonly done e.g. in C++ iterators and range-based for loops. 15165 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 15166 return; 15167 15168 // Also don't warn for arrays of size 1 which are members of some 15169 // structure. These are often used to approximate flexible arrays in C89 15170 // code. 15171 if (IsTailPaddedMemberArray(*this, size, ND)) 15172 return; 15173 15174 // Suppress the warning if the subscript expression (as identified by the 15175 // ']' location) and the index expression are both from macro expansions 15176 // within a system header. 15177 if (ASE) { 15178 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 15179 ASE->getRBracketLoc()); 15180 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 15181 SourceLocation IndexLoc = 15182 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 15183 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 15184 return; 15185 } 15186 } 15187 15188 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 15189 : diag::warn_ptr_arith_exceeds_bounds; 15190 15191 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15192 PDiag(DiagID) << toString(index, 10, true) 15193 << toString(size, 10, true) 15194 << (unsigned)size.getLimitedValue(~0U) 15195 << IndexExpr->getSourceRange()); 15196 } else { 15197 unsigned DiagID = diag::warn_array_index_precedes_bounds; 15198 if (!ASE) { 15199 DiagID = diag::warn_ptr_arith_precedes_bounds; 15200 if (index.isNegative()) index = -index; 15201 } 15202 15203 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15204 PDiag(DiagID) << toString(index, 10, true) 15205 << IndexExpr->getSourceRange()); 15206 } 15207 15208 if (!ND) { 15209 // Try harder to find a NamedDecl to point at in the note. 15210 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15211 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15212 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15213 ND = DRE->getDecl(); 15214 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15215 ND = ME->getMemberDecl(); 15216 } 15217 15218 if (ND) 15219 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15220 PDiag(diag::note_array_declared_here) << ND); 15221 } 15222 15223 void Sema::CheckArrayAccess(const Expr *expr) { 15224 int AllowOnePastEnd = 0; 15225 while (expr) { 15226 expr = expr->IgnoreParenImpCasts(); 15227 switch (expr->getStmtClass()) { 15228 case Stmt::ArraySubscriptExprClass: { 15229 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 15230 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 15231 AllowOnePastEnd > 0); 15232 expr = ASE->getBase(); 15233 break; 15234 } 15235 case Stmt::MemberExprClass: { 15236 expr = cast<MemberExpr>(expr)->getBase(); 15237 break; 15238 } 15239 case Stmt::OMPArraySectionExprClass: { 15240 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 15241 if (ASE->getLowerBound()) 15242 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 15243 /*ASE=*/nullptr, AllowOnePastEnd > 0); 15244 return; 15245 } 15246 case Stmt::UnaryOperatorClass: { 15247 // Only unwrap the * and & unary operators 15248 const UnaryOperator *UO = cast<UnaryOperator>(expr); 15249 expr = UO->getSubExpr(); 15250 switch (UO->getOpcode()) { 15251 case UO_AddrOf: 15252 AllowOnePastEnd++; 15253 break; 15254 case UO_Deref: 15255 AllowOnePastEnd--; 15256 break; 15257 default: 15258 return; 15259 } 15260 break; 15261 } 15262 case Stmt::ConditionalOperatorClass: { 15263 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 15264 if (const Expr *lhs = cond->getLHS()) 15265 CheckArrayAccess(lhs); 15266 if (const Expr *rhs = cond->getRHS()) 15267 CheckArrayAccess(rhs); 15268 return; 15269 } 15270 case Stmt::CXXOperatorCallExprClass: { 15271 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 15272 for (const auto *Arg : OCE->arguments()) 15273 CheckArrayAccess(Arg); 15274 return; 15275 } 15276 default: 15277 return; 15278 } 15279 } 15280 } 15281 15282 //===--- CHECK: Objective-C retain cycles ----------------------------------// 15283 15284 namespace { 15285 15286 struct RetainCycleOwner { 15287 VarDecl *Variable = nullptr; 15288 SourceRange Range; 15289 SourceLocation Loc; 15290 bool Indirect = false; 15291 15292 RetainCycleOwner() = default; 15293 15294 void setLocsFrom(Expr *e) { 15295 Loc = e->getExprLoc(); 15296 Range = e->getSourceRange(); 15297 } 15298 }; 15299 15300 } // namespace 15301 15302 /// Consider whether capturing the given variable can possibly lead to 15303 /// a retain cycle. 15304 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 15305 // In ARC, it's captured strongly iff the variable has __strong 15306 // lifetime. In MRR, it's captured strongly if the variable is 15307 // __block and has an appropriate type. 15308 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15309 return false; 15310 15311 owner.Variable = var; 15312 if (ref) 15313 owner.setLocsFrom(ref); 15314 return true; 15315 } 15316 15317 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 15318 while (true) { 15319 e = e->IgnoreParens(); 15320 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 15321 switch (cast->getCastKind()) { 15322 case CK_BitCast: 15323 case CK_LValueBitCast: 15324 case CK_LValueToRValue: 15325 case CK_ARCReclaimReturnedObject: 15326 e = cast->getSubExpr(); 15327 continue; 15328 15329 default: 15330 return false; 15331 } 15332 } 15333 15334 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 15335 ObjCIvarDecl *ivar = ref->getDecl(); 15336 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15337 return false; 15338 15339 // Try to find a retain cycle in the base. 15340 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 15341 return false; 15342 15343 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 15344 owner.Indirect = true; 15345 return true; 15346 } 15347 15348 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 15349 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 15350 if (!var) return false; 15351 return considerVariable(var, ref, owner); 15352 } 15353 15354 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 15355 if (member->isArrow()) return false; 15356 15357 // Don't count this as an indirect ownership. 15358 e = member->getBase(); 15359 continue; 15360 } 15361 15362 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 15363 // Only pay attention to pseudo-objects on property references. 15364 ObjCPropertyRefExpr *pre 15365 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 15366 ->IgnoreParens()); 15367 if (!pre) return false; 15368 if (pre->isImplicitProperty()) return false; 15369 ObjCPropertyDecl *property = pre->getExplicitProperty(); 15370 if (!property->isRetaining() && 15371 !(property->getPropertyIvarDecl() && 15372 property->getPropertyIvarDecl()->getType() 15373 .getObjCLifetime() == Qualifiers::OCL_Strong)) 15374 return false; 15375 15376 owner.Indirect = true; 15377 if (pre->isSuperReceiver()) { 15378 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 15379 if (!owner.Variable) 15380 return false; 15381 owner.Loc = pre->getLocation(); 15382 owner.Range = pre->getSourceRange(); 15383 return true; 15384 } 15385 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 15386 ->getSourceExpr()); 15387 continue; 15388 } 15389 15390 // Array ivars? 15391 15392 return false; 15393 } 15394 } 15395 15396 namespace { 15397 15398 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 15399 ASTContext &Context; 15400 VarDecl *Variable; 15401 Expr *Capturer = nullptr; 15402 bool VarWillBeReased = false; 15403 15404 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 15405 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 15406 Context(Context), Variable(variable) {} 15407 15408 void VisitDeclRefExpr(DeclRefExpr *ref) { 15409 if (ref->getDecl() == Variable && !Capturer) 15410 Capturer = ref; 15411 } 15412 15413 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 15414 if (Capturer) return; 15415 Visit(ref->getBase()); 15416 if (Capturer && ref->isFreeIvar()) 15417 Capturer = ref; 15418 } 15419 15420 void VisitBlockExpr(BlockExpr *block) { 15421 // Look inside nested blocks 15422 if (block->getBlockDecl()->capturesVariable(Variable)) 15423 Visit(block->getBlockDecl()->getBody()); 15424 } 15425 15426 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 15427 if (Capturer) return; 15428 if (OVE->getSourceExpr()) 15429 Visit(OVE->getSourceExpr()); 15430 } 15431 15432 void VisitBinaryOperator(BinaryOperator *BinOp) { 15433 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 15434 return; 15435 Expr *LHS = BinOp->getLHS(); 15436 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 15437 if (DRE->getDecl() != Variable) 15438 return; 15439 if (Expr *RHS = BinOp->getRHS()) { 15440 RHS = RHS->IgnoreParenCasts(); 15441 Optional<llvm::APSInt> Value; 15442 VarWillBeReased = 15443 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 15444 *Value == 0); 15445 } 15446 } 15447 } 15448 }; 15449 15450 } // namespace 15451 15452 /// Check whether the given argument is a block which captures a 15453 /// variable. 15454 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 15455 assert(owner.Variable && owner.Loc.isValid()); 15456 15457 e = e->IgnoreParenCasts(); 15458 15459 // Look through [^{...} copy] and Block_copy(^{...}). 15460 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 15461 Selector Cmd = ME->getSelector(); 15462 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 15463 e = ME->getInstanceReceiver(); 15464 if (!e) 15465 return nullptr; 15466 e = e->IgnoreParenCasts(); 15467 } 15468 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 15469 if (CE->getNumArgs() == 1) { 15470 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 15471 if (Fn) { 15472 const IdentifierInfo *FnI = Fn->getIdentifier(); 15473 if (FnI && FnI->isStr("_Block_copy")) { 15474 e = CE->getArg(0)->IgnoreParenCasts(); 15475 } 15476 } 15477 } 15478 } 15479 15480 BlockExpr *block = dyn_cast<BlockExpr>(e); 15481 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 15482 return nullptr; 15483 15484 FindCaptureVisitor visitor(S.Context, owner.Variable); 15485 visitor.Visit(block->getBlockDecl()->getBody()); 15486 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15487 } 15488 15489 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15490 RetainCycleOwner &owner) { 15491 assert(capturer); 15492 assert(owner.Variable && owner.Loc.isValid()); 15493 15494 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15495 << owner.Variable << capturer->getSourceRange(); 15496 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15497 << owner.Indirect << owner.Range; 15498 } 15499 15500 /// Check for a keyword selector that starts with the word 'add' or 15501 /// 'set'. 15502 static bool isSetterLikeSelector(Selector sel) { 15503 if (sel.isUnarySelector()) return false; 15504 15505 StringRef str = sel.getNameForSlot(0); 15506 while (!str.empty() && str.front() == '_') str = str.substr(1); 15507 if (str.startswith("set")) 15508 str = str.substr(3); 15509 else if (str.startswith("add")) { 15510 // Specially allow 'addOperationWithBlock:'. 15511 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15512 return false; 15513 str = str.substr(3); 15514 } 15515 else 15516 return false; 15517 15518 if (str.empty()) return true; 15519 return !isLowercase(str.front()); 15520 } 15521 15522 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15523 ObjCMessageExpr *Message) { 15524 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15525 Message->getReceiverInterface(), 15526 NSAPI::ClassId_NSMutableArray); 15527 if (!IsMutableArray) { 15528 return None; 15529 } 15530 15531 Selector Sel = Message->getSelector(); 15532 15533 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15534 S.NSAPIObj->getNSArrayMethodKind(Sel); 15535 if (!MKOpt) { 15536 return None; 15537 } 15538 15539 NSAPI::NSArrayMethodKind MK = *MKOpt; 15540 15541 switch (MK) { 15542 case NSAPI::NSMutableArr_addObject: 15543 case NSAPI::NSMutableArr_insertObjectAtIndex: 15544 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15545 return 0; 15546 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15547 return 1; 15548 15549 default: 15550 return None; 15551 } 15552 15553 return None; 15554 } 15555 15556 static 15557 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15558 ObjCMessageExpr *Message) { 15559 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15560 Message->getReceiverInterface(), 15561 NSAPI::ClassId_NSMutableDictionary); 15562 if (!IsMutableDictionary) { 15563 return None; 15564 } 15565 15566 Selector Sel = Message->getSelector(); 15567 15568 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 15569 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 15570 if (!MKOpt) { 15571 return None; 15572 } 15573 15574 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 15575 15576 switch (MK) { 15577 case NSAPI::NSMutableDict_setObjectForKey: 15578 case NSAPI::NSMutableDict_setValueForKey: 15579 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 15580 return 0; 15581 15582 default: 15583 return None; 15584 } 15585 15586 return None; 15587 } 15588 15589 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 15590 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 15591 Message->getReceiverInterface(), 15592 NSAPI::ClassId_NSMutableSet); 15593 15594 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 15595 Message->getReceiverInterface(), 15596 NSAPI::ClassId_NSMutableOrderedSet); 15597 if (!IsMutableSet && !IsMutableOrderedSet) { 15598 return None; 15599 } 15600 15601 Selector Sel = Message->getSelector(); 15602 15603 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15604 if (!MKOpt) { 15605 return None; 15606 } 15607 15608 NSAPI::NSSetMethodKind MK = *MKOpt; 15609 15610 switch (MK) { 15611 case NSAPI::NSMutableSet_addObject: 15612 case NSAPI::NSOrderedSet_setObjectAtIndex: 15613 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15614 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15615 return 0; 15616 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 15617 return 1; 15618 } 15619 15620 return None; 15621 } 15622 15623 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 15624 if (!Message->isInstanceMessage()) { 15625 return; 15626 } 15627 15628 Optional<int> ArgOpt; 15629 15630 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 15631 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 15632 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 15633 return; 15634 } 15635 15636 int ArgIndex = *ArgOpt; 15637 15638 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 15639 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 15640 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 15641 } 15642 15643 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 15644 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15645 if (ArgRE->isObjCSelfExpr()) { 15646 Diag(Message->getSourceRange().getBegin(), 15647 diag::warn_objc_circular_container) 15648 << ArgRE->getDecl() << StringRef("'super'"); 15649 } 15650 } 15651 } else { 15652 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 15653 15654 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 15655 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 15656 } 15657 15658 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 15659 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15660 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 15661 ValueDecl *Decl = ReceiverRE->getDecl(); 15662 Diag(Message->getSourceRange().getBegin(), 15663 diag::warn_objc_circular_container) 15664 << Decl << Decl; 15665 if (!ArgRE->isObjCSelfExpr()) { 15666 Diag(Decl->getLocation(), 15667 diag::note_objc_circular_container_declared_here) 15668 << Decl; 15669 } 15670 } 15671 } 15672 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15673 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15674 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15675 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15676 Diag(Message->getSourceRange().getBegin(), 15677 diag::warn_objc_circular_container) 15678 << Decl << Decl; 15679 Diag(Decl->getLocation(), 15680 diag::note_objc_circular_container_declared_here) 15681 << Decl; 15682 } 15683 } 15684 } 15685 } 15686 } 15687 15688 /// Check a message send to see if it's likely to cause a retain cycle. 15689 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15690 // Only check instance methods whose selector looks like a setter. 15691 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15692 return; 15693 15694 // Try to find a variable that the receiver is strongly owned by. 15695 RetainCycleOwner owner; 15696 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15697 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15698 return; 15699 } else { 15700 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15701 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15702 owner.Loc = msg->getSuperLoc(); 15703 owner.Range = msg->getSuperLoc(); 15704 } 15705 15706 // Check whether the receiver is captured by any of the arguments. 15707 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15708 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15709 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15710 // noescape blocks should not be retained by the method. 15711 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15712 continue; 15713 return diagnoseRetainCycle(*this, capturer, owner); 15714 } 15715 } 15716 } 15717 15718 /// Check a property assign to see if it's likely to cause a retain cycle. 15719 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15720 RetainCycleOwner owner; 15721 if (!findRetainCycleOwner(*this, receiver, owner)) 15722 return; 15723 15724 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15725 diagnoseRetainCycle(*this, capturer, owner); 15726 } 15727 15728 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15729 RetainCycleOwner Owner; 15730 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15731 return; 15732 15733 // Because we don't have an expression for the variable, we have to set the 15734 // location explicitly here. 15735 Owner.Loc = Var->getLocation(); 15736 Owner.Range = Var->getSourceRange(); 15737 15738 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15739 diagnoseRetainCycle(*this, Capturer, Owner); 15740 } 15741 15742 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15743 Expr *RHS, bool isProperty) { 15744 // Check if RHS is an Objective-C object literal, which also can get 15745 // immediately zapped in a weak reference. Note that we explicitly 15746 // allow ObjCStringLiterals, since those are designed to never really die. 15747 RHS = RHS->IgnoreParenImpCasts(); 15748 15749 // This enum needs to match with the 'select' in 15750 // warn_objc_arc_literal_assign (off-by-1). 15751 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15752 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15753 return false; 15754 15755 S.Diag(Loc, diag::warn_arc_literal_assign) 15756 << (unsigned) Kind 15757 << (isProperty ? 0 : 1) 15758 << RHS->getSourceRange(); 15759 15760 return true; 15761 } 15762 15763 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15764 Qualifiers::ObjCLifetime LT, 15765 Expr *RHS, bool isProperty) { 15766 // Strip off any implicit cast added to get to the one ARC-specific. 15767 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15768 if (cast->getCastKind() == CK_ARCConsumeObject) { 15769 S.Diag(Loc, diag::warn_arc_retained_assign) 15770 << (LT == Qualifiers::OCL_ExplicitNone) 15771 << (isProperty ? 0 : 1) 15772 << RHS->getSourceRange(); 15773 return true; 15774 } 15775 RHS = cast->getSubExpr(); 15776 } 15777 15778 if (LT == Qualifiers::OCL_Weak && 15779 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15780 return true; 15781 15782 return false; 15783 } 15784 15785 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15786 QualType LHS, Expr *RHS) { 15787 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15788 15789 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15790 return false; 15791 15792 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15793 return true; 15794 15795 return false; 15796 } 15797 15798 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15799 Expr *LHS, Expr *RHS) { 15800 QualType LHSType; 15801 // PropertyRef on LHS type need be directly obtained from 15802 // its declaration as it has a PseudoType. 15803 ObjCPropertyRefExpr *PRE 15804 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15805 if (PRE && !PRE->isImplicitProperty()) { 15806 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15807 if (PD) 15808 LHSType = PD->getType(); 15809 } 15810 15811 if (LHSType.isNull()) 15812 LHSType = LHS->getType(); 15813 15814 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15815 15816 if (LT == Qualifiers::OCL_Weak) { 15817 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15818 getCurFunction()->markSafeWeakUse(LHS); 15819 } 15820 15821 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15822 return; 15823 15824 // FIXME. Check for other life times. 15825 if (LT != Qualifiers::OCL_None) 15826 return; 15827 15828 if (PRE) { 15829 if (PRE->isImplicitProperty()) 15830 return; 15831 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15832 if (!PD) 15833 return; 15834 15835 unsigned Attributes = PD->getPropertyAttributes(); 15836 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15837 // when 'assign' attribute was not explicitly specified 15838 // by user, ignore it and rely on property type itself 15839 // for lifetime info. 15840 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15841 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15842 LHSType->isObjCRetainableType()) 15843 return; 15844 15845 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15846 if (cast->getCastKind() == CK_ARCConsumeObject) { 15847 Diag(Loc, diag::warn_arc_retained_property_assign) 15848 << RHS->getSourceRange(); 15849 return; 15850 } 15851 RHS = cast->getSubExpr(); 15852 } 15853 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15854 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15855 return; 15856 } 15857 } 15858 } 15859 15860 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15861 15862 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15863 SourceLocation StmtLoc, 15864 const NullStmt *Body) { 15865 // Do not warn if the body is a macro that expands to nothing, e.g: 15866 // 15867 // #define CALL(x) 15868 // if (condition) 15869 // CALL(0); 15870 if (Body->hasLeadingEmptyMacro()) 15871 return false; 15872 15873 // Get line numbers of statement and body. 15874 bool StmtLineInvalid; 15875 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15876 &StmtLineInvalid); 15877 if (StmtLineInvalid) 15878 return false; 15879 15880 bool BodyLineInvalid; 15881 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15882 &BodyLineInvalid); 15883 if (BodyLineInvalid) 15884 return false; 15885 15886 // Warn if null statement and body are on the same line. 15887 if (StmtLine != BodyLine) 15888 return false; 15889 15890 return true; 15891 } 15892 15893 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15894 const Stmt *Body, 15895 unsigned DiagID) { 15896 // Since this is a syntactic check, don't emit diagnostic for template 15897 // instantiations, this just adds noise. 15898 if (CurrentInstantiationScope) 15899 return; 15900 15901 // The body should be a null statement. 15902 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15903 if (!NBody) 15904 return; 15905 15906 // Do the usual checks. 15907 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15908 return; 15909 15910 Diag(NBody->getSemiLoc(), DiagID); 15911 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15912 } 15913 15914 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15915 const Stmt *PossibleBody) { 15916 assert(!CurrentInstantiationScope); // Ensured by caller 15917 15918 SourceLocation StmtLoc; 15919 const Stmt *Body; 15920 unsigned DiagID; 15921 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15922 StmtLoc = FS->getRParenLoc(); 15923 Body = FS->getBody(); 15924 DiagID = diag::warn_empty_for_body; 15925 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15926 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15927 Body = WS->getBody(); 15928 DiagID = diag::warn_empty_while_body; 15929 } else 15930 return; // Neither `for' nor `while'. 15931 15932 // The body should be a null statement. 15933 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15934 if (!NBody) 15935 return; 15936 15937 // Skip expensive checks if diagnostic is disabled. 15938 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15939 return; 15940 15941 // Do the usual checks. 15942 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15943 return; 15944 15945 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15946 // noise level low, emit diagnostics only if for/while is followed by a 15947 // CompoundStmt, e.g.: 15948 // for (int i = 0; i < n; i++); 15949 // { 15950 // a(i); 15951 // } 15952 // or if for/while is followed by a statement with more indentation 15953 // than for/while itself: 15954 // for (int i = 0; i < n; i++); 15955 // a(i); 15956 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15957 if (!ProbableTypo) { 15958 bool BodyColInvalid; 15959 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15960 PossibleBody->getBeginLoc(), &BodyColInvalid); 15961 if (BodyColInvalid) 15962 return; 15963 15964 bool StmtColInvalid; 15965 unsigned StmtCol = 15966 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15967 if (StmtColInvalid) 15968 return; 15969 15970 if (BodyCol > StmtCol) 15971 ProbableTypo = true; 15972 } 15973 15974 if (ProbableTypo) { 15975 Diag(NBody->getSemiLoc(), DiagID); 15976 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15977 } 15978 } 15979 15980 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15981 15982 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15983 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15984 SourceLocation OpLoc) { 15985 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15986 return; 15987 15988 if (inTemplateInstantiation()) 15989 return; 15990 15991 // Strip parens and casts away. 15992 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 15993 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 15994 15995 // Check for a call expression 15996 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 15997 if (!CE || CE->getNumArgs() != 1) 15998 return; 15999 16000 // Check for a call to std::move 16001 if (!CE->isCallToStdMove()) 16002 return; 16003 16004 // Get argument from std::move 16005 RHSExpr = CE->getArg(0); 16006 16007 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 16008 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 16009 16010 // Two DeclRefExpr's, check that the decls are the same. 16011 if (LHSDeclRef && RHSDeclRef) { 16012 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16013 return; 16014 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16015 RHSDeclRef->getDecl()->getCanonicalDecl()) 16016 return; 16017 16018 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16019 << LHSExpr->getSourceRange() 16020 << RHSExpr->getSourceRange(); 16021 return; 16022 } 16023 16024 // Member variables require a different approach to check for self moves. 16025 // MemberExpr's are the same if every nested MemberExpr refers to the same 16026 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 16027 // the base Expr's are CXXThisExpr's. 16028 const Expr *LHSBase = LHSExpr; 16029 const Expr *RHSBase = RHSExpr; 16030 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 16031 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 16032 if (!LHSME || !RHSME) 16033 return; 16034 16035 while (LHSME && RHSME) { 16036 if (LHSME->getMemberDecl()->getCanonicalDecl() != 16037 RHSME->getMemberDecl()->getCanonicalDecl()) 16038 return; 16039 16040 LHSBase = LHSME->getBase(); 16041 RHSBase = RHSME->getBase(); 16042 LHSME = dyn_cast<MemberExpr>(LHSBase); 16043 RHSME = dyn_cast<MemberExpr>(RHSBase); 16044 } 16045 16046 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 16047 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 16048 if (LHSDeclRef && RHSDeclRef) { 16049 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16050 return; 16051 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16052 RHSDeclRef->getDecl()->getCanonicalDecl()) 16053 return; 16054 16055 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16056 << LHSExpr->getSourceRange() 16057 << RHSExpr->getSourceRange(); 16058 return; 16059 } 16060 16061 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 16062 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16063 << LHSExpr->getSourceRange() 16064 << RHSExpr->getSourceRange(); 16065 } 16066 16067 //===--- Layout compatibility ----------------------------------------------// 16068 16069 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 16070 16071 /// Check if two enumeration types are layout-compatible. 16072 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 16073 // C++11 [dcl.enum] p8: 16074 // Two enumeration types are layout-compatible if they have the same 16075 // underlying type. 16076 return ED1->isComplete() && ED2->isComplete() && 16077 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 16078 } 16079 16080 /// Check if two fields are layout-compatible. 16081 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 16082 FieldDecl *Field2) { 16083 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 16084 return false; 16085 16086 if (Field1->isBitField() != Field2->isBitField()) 16087 return false; 16088 16089 if (Field1->isBitField()) { 16090 // Make sure that the bit-fields are the same length. 16091 unsigned Bits1 = Field1->getBitWidthValue(C); 16092 unsigned Bits2 = Field2->getBitWidthValue(C); 16093 16094 if (Bits1 != Bits2) 16095 return false; 16096 } 16097 16098 return true; 16099 } 16100 16101 /// Check if two standard-layout structs are layout-compatible. 16102 /// (C++11 [class.mem] p17) 16103 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 16104 RecordDecl *RD2) { 16105 // If both records are C++ classes, check that base classes match. 16106 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 16107 // If one of records is a CXXRecordDecl we are in C++ mode, 16108 // thus the other one is a CXXRecordDecl, too. 16109 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 16110 // Check number of base classes. 16111 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 16112 return false; 16113 16114 // Check the base classes. 16115 for (CXXRecordDecl::base_class_const_iterator 16116 Base1 = D1CXX->bases_begin(), 16117 BaseEnd1 = D1CXX->bases_end(), 16118 Base2 = D2CXX->bases_begin(); 16119 Base1 != BaseEnd1; 16120 ++Base1, ++Base2) { 16121 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 16122 return false; 16123 } 16124 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 16125 // If only RD2 is a C++ class, it should have zero base classes. 16126 if (D2CXX->getNumBases() > 0) 16127 return false; 16128 } 16129 16130 // Check the fields. 16131 RecordDecl::field_iterator Field2 = RD2->field_begin(), 16132 Field2End = RD2->field_end(), 16133 Field1 = RD1->field_begin(), 16134 Field1End = RD1->field_end(); 16135 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 16136 if (!isLayoutCompatible(C, *Field1, *Field2)) 16137 return false; 16138 } 16139 if (Field1 != Field1End || Field2 != Field2End) 16140 return false; 16141 16142 return true; 16143 } 16144 16145 /// Check if two standard-layout unions are layout-compatible. 16146 /// (C++11 [class.mem] p18) 16147 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 16148 RecordDecl *RD2) { 16149 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 16150 for (auto *Field2 : RD2->fields()) 16151 UnmatchedFields.insert(Field2); 16152 16153 for (auto *Field1 : RD1->fields()) { 16154 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 16155 I = UnmatchedFields.begin(), 16156 E = UnmatchedFields.end(); 16157 16158 for ( ; I != E; ++I) { 16159 if (isLayoutCompatible(C, Field1, *I)) { 16160 bool Result = UnmatchedFields.erase(*I); 16161 (void) Result; 16162 assert(Result); 16163 break; 16164 } 16165 } 16166 if (I == E) 16167 return false; 16168 } 16169 16170 return UnmatchedFields.empty(); 16171 } 16172 16173 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 16174 RecordDecl *RD2) { 16175 if (RD1->isUnion() != RD2->isUnion()) 16176 return false; 16177 16178 if (RD1->isUnion()) 16179 return isLayoutCompatibleUnion(C, RD1, RD2); 16180 else 16181 return isLayoutCompatibleStruct(C, RD1, RD2); 16182 } 16183 16184 /// Check if two types are layout-compatible in C++11 sense. 16185 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 16186 if (T1.isNull() || T2.isNull()) 16187 return false; 16188 16189 // C++11 [basic.types] p11: 16190 // If two types T1 and T2 are the same type, then T1 and T2 are 16191 // layout-compatible types. 16192 if (C.hasSameType(T1, T2)) 16193 return true; 16194 16195 T1 = T1.getCanonicalType().getUnqualifiedType(); 16196 T2 = T2.getCanonicalType().getUnqualifiedType(); 16197 16198 const Type::TypeClass TC1 = T1->getTypeClass(); 16199 const Type::TypeClass TC2 = T2->getTypeClass(); 16200 16201 if (TC1 != TC2) 16202 return false; 16203 16204 if (TC1 == Type::Enum) { 16205 return isLayoutCompatible(C, 16206 cast<EnumType>(T1)->getDecl(), 16207 cast<EnumType>(T2)->getDecl()); 16208 } else if (TC1 == Type::Record) { 16209 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 16210 return false; 16211 16212 return isLayoutCompatible(C, 16213 cast<RecordType>(T1)->getDecl(), 16214 cast<RecordType>(T2)->getDecl()); 16215 } 16216 16217 return false; 16218 } 16219 16220 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 16221 16222 /// Given a type tag expression find the type tag itself. 16223 /// 16224 /// \param TypeExpr Type tag expression, as it appears in user's code. 16225 /// 16226 /// \param VD Declaration of an identifier that appears in a type tag. 16227 /// 16228 /// \param MagicValue Type tag magic value. 16229 /// 16230 /// \param isConstantEvaluated whether the evalaution should be performed in 16231 16232 /// constant context. 16233 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 16234 const ValueDecl **VD, uint64_t *MagicValue, 16235 bool isConstantEvaluated) { 16236 while(true) { 16237 if (!TypeExpr) 16238 return false; 16239 16240 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 16241 16242 switch (TypeExpr->getStmtClass()) { 16243 case Stmt::UnaryOperatorClass: { 16244 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 16245 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 16246 TypeExpr = UO->getSubExpr(); 16247 continue; 16248 } 16249 return false; 16250 } 16251 16252 case Stmt::DeclRefExprClass: { 16253 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 16254 *VD = DRE->getDecl(); 16255 return true; 16256 } 16257 16258 case Stmt::IntegerLiteralClass: { 16259 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 16260 llvm::APInt MagicValueAPInt = IL->getValue(); 16261 if (MagicValueAPInt.getActiveBits() <= 64) { 16262 *MagicValue = MagicValueAPInt.getZExtValue(); 16263 return true; 16264 } else 16265 return false; 16266 } 16267 16268 case Stmt::BinaryConditionalOperatorClass: 16269 case Stmt::ConditionalOperatorClass: { 16270 const AbstractConditionalOperator *ACO = 16271 cast<AbstractConditionalOperator>(TypeExpr); 16272 bool Result; 16273 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 16274 isConstantEvaluated)) { 16275 if (Result) 16276 TypeExpr = ACO->getTrueExpr(); 16277 else 16278 TypeExpr = ACO->getFalseExpr(); 16279 continue; 16280 } 16281 return false; 16282 } 16283 16284 case Stmt::BinaryOperatorClass: { 16285 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 16286 if (BO->getOpcode() == BO_Comma) { 16287 TypeExpr = BO->getRHS(); 16288 continue; 16289 } 16290 return false; 16291 } 16292 16293 default: 16294 return false; 16295 } 16296 } 16297 } 16298 16299 /// Retrieve the C type corresponding to type tag TypeExpr. 16300 /// 16301 /// \param TypeExpr Expression that specifies a type tag. 16302 /// 16303 /// \param MagicValues Registered magic values. 16304 /// 16305 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 16306 /// kind. 16307 /// 16308 /// \param TypeInfo Information about the corresponding C type. 16309 /// 16310 /// \param isConstantEvaluated whether the evalaution should be performed in 16311 /// constant context. 16312 /// 16313 /// \returns true if the corresponding C type was found. 16314 static bool GetMatchingCType( 16315 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 16316 const ASTContext &Ctx, 16317 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 16318 *MagicValues, 16319 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 16320 bool isConstantEvaluated) { 16321 FoundWrongKind = false; 16322 16323 // Variable declaration that has type_tag_for_datatype attribute. 16324 const ValueDecl *VD = nullptr; 16325 16326 uint64_t MagicValue; 16327 16328 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 16329 return false; 16330 16331 if (VD) { 16332 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 16333 if (I->getArgumentKind() != ArgumentKind) { 16334 FoundWrongKind = true; 16335 return false; 16336 } 16337 TypeInfo.Type = I->getMatchingCType(); 16338 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 16339 TypeInfo.MustBeNull = I->getMustBeNull(); 16340 return true; 16341 } 16342 return false; 16343 } 16344 16345 if (!MagicValues) 16346 return false; 16347 16348 llvm::DenseMap<Sema::TypeTagMagicValue, 16349 Sema::TypeTagData>::const_iterator I = 16350 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 16351 if (I == MagicValues->end()) 16352 return false; 16353 16354 TypeInfo = I->second; 16355 return true; 16356 } 16357 16358 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 16359 uint64_t MagicValue, QualType Type, 16360 bool LayoutCompatible, 16361 bool MustBeNull) { 16362 if (!TypeTagForDatatypeMagicValues) 16363 TypeTagForDatatypeMagicValues.reset( 16364 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 16365 16366 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 16367 (*TypeTagForDatatypeMagicValues)[Magic] = 16368 TypeTagData(Type, LayoutCompatible, MustBeNull); 16369 } 16370 16371 static bool IsSameCharType(QualType T1, QualType T2) { 16372 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 16373 if (!BT1) 16374 return false; 16375 16376 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 16377 if (!BT2) 16378 return false; 16379 16380 BuiltinType::Kind T1Kind = BT1->getKind(); 16381 BuiltinType::Kind T2Kind = BT2->getKind(); 16382 16383 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 16384 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 16385 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 16386 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 16387 } 16388 16389 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 16390 const ArrayRef<const Expr *> ExprArgs, 16391 SourceLocation CallSiteLoc) { 16392 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 16393 bool IsPointerAttr = Attr->getIsPointer(); 16394 16395 // Retrieve the argument representing the 'type_tag'. 16396 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 16397 if (TypeTagIdxAST >= ExprArgs.size()) { 16398 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16399 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 16400 return; 16401 } 16402 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 16403 bool FoundWrongKind; 16404 TypeTagData TypeInfo; 16405 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 16406 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 16407 TypeInfo, isConstantEvaluated())) { 16408 if (FoundWrongKind) 16409 Diag(TypeTagExpr->getExprLoc(), 16410 diag::warn_type_tag_for_datatype_wrong_kind) 16411 << TypeTagExpr->getSourceRange(); 16412 return; 16413 } 16414 16415 // Retrieve the argument representing the 'arg_idx'. 16416 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 16417 if (ArgumentIdxAST >= ExprArgs.size()) { 16418 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16419 << 1 << Attr->getArgumentIdx().getSourceIndex(); 16420 return; 16421 } 16422 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 16423 if (IsPointerAttr) { 16424 // Skip implicit cast of pointer to `void *' (as a function argument). 16425 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 16426 if (ICE->getType()->isVoidPointerType() && 16427 ICE->getCastKind() == CK_BitCast) 16428 ArgumentExpr = ICE->getSubExpr(); 16429 } 16430 QualType ArgumentType = ArgumentExpr->getType(); 16431 16432 // Passing a `void*' pointer shouldn't trigger a warning. 16433 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 16434 return; 16435 16436 if (TypeInfo.MustBeNull) { 16437 // Type tag with matching void type requires a null pointer. 16438 if (!ArgumentExpr->isNullPointerConstant(Context, 16439 Expr::NPC_ValueDependentIsNotNull)) { 16440 Diag(ArgumentExpr->getExprLoc(), 16441 diag::warn_type_safety_null_pointer_required) 16442 << ArgumentKind->getName() 16443 << ArgumentExpr->getSourceRange() 16444 << TypeTagExpr->getSourceRange(); 16445 } 16446 return; 16447 } 16448 16449 QualType RequiredType = TypeInfo.Type; 16450 if (IsPointerAttr) 16451 RequiredType = Context.getPointerType(RequiredType); 16452 16453 bool mismatch = false; 16454 if (!TypeInfo.LayoutCompatible) { 16455 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 16456 16457 // C++11 [basic.fundamental] p1: 16458 // Plain char, signed char, and unsigned char are three distinct types. 16459 // 16460 // But we treat plain `char' as equivalent to `signed char' or `unsigned 16461 // char' depending on the current char signedness mode. 16462 if (mismatch) 16463 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 16464 RequiredType->getPointeeType())) || 16465 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 16466 mismatch = false; 16467 } else 16468 if (IsPointerAttr) 16469 mismatch = !isLayoutCompatible(Context, 16470 ArgumentType->getPointeeType(), 16471 RequiredType->getPointeeType()); 16472 else 16473 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 16474 16475 if (mismatch) 16476 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 16477 << ArgumentType << ArgumentKind 16478 << TypeInfo.LayoutCompatible << RequiredType 16479 << ArgumentExpr->getSourceRange() 16480 << TypeTagExpr->getSourceRange(); 16481 } 16482 16483 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 16484 CharUnits Alignment) { 16485 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16486 } 16487 16488 void Sema::DiagnoseMisalignedMembers() { 16489 for (MisalignedMember &m : MisalignedMembers) { 16490 const NamedDecl *ND = m.RD; 16491 if (ND->getName().empty()) { 16492 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16493 ND = TD; 16494 } 16495 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16496 << m.MD << ND << m.E->getSourceRange(); 16497 } 16498 MisalignedMembers.clear(); 16499 } 16500 16501 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16502 E = E->IgnoreParens(); 16503 if (!T->isPointerType() && !T->isIntegerType()) 16504 return; 16505 if (isa<UnaryOperator>(E) && 16506 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16507 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16508 if (isa<MemberExpr>(Op)) { 16509 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16510 if (MA != MisalignedMembers.end() && 16511 (T->isIntegerType() || 16512 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16513 Context.getTypeAlignInChars( 16514 T->getPointeeType()) <= MA->Alignment)))) 16515 MisalignedMembers.erase(MA); 16516 } 16517 } 16518 } 16519 16520 void Sema::RefersToMemberWithReducedAlignment( 16521 Expr *E, 16522 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16523 Action) { 16524 const auto *ME = dyn_cast<MemberExpr>(E); 16525 if (!ME) 16526 return; 16527 16528 // No need to check expressions with an __unaligned-qualified type. 16529 if (E->getType().getQualifiers().hasUnaligned()) 16530 return; 16531 16532 // For a chain of MemberExpr like "a.b.c.d" this list 16533 // will keep FieldDecl's like [d, c, b]. 16534 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16535 const MemberExpr *TopME = nullptr; 16536 bool AnyIsPacked = false; 16537 do { 16538 QualType BaseType = ME->getBase()->getType(); 16539 if (BaseType->isDependentType()) 16540 return; 16541 if (ME->isArrow()) 16542 BaseType = BaseType->getPointeeType(); 16543 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16544 if (RD->isInvalidDecl()) 16545 return; 16546 16547 ValueDecl *MD = ME->getMemberDecl(); 16548 auto *FD = dyn_cast<FieldDecl>(MD); 16549 // We do not care about non-data members. 16550 if (!FD || FD->isInvalidDecl()) 16551 return; 16552 16553 AnyIsPacked = 16554 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16555 ReverseMemberChain.push_back(FD); 16556 16557 TopME = ME; 16558 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16559 } while (ME); 16560 assert(TopME && "We did not compute a topmost MemberExpr!"); 16561 16562 // Not the scope of this diagnostic. 16563 if (!AnyIsPacked) 16564 return; 16565 16566 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 16567 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 16568 // TODO: The innermost base of the member expression may be too complicated. 16569 // For now, just disregard these cases. This is left for future 16570 // improvement. 16571 if (!DRE && !isa<CXXThisExpr>(TopBase)) 16572 return; 16573 16574 // Alignment expected by the whole expression. 16575 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 16576 16577 // No need to do anything else with this case. 16578 if (ExpectedAlignment.isOne()) 16579 return; 16580 16581 // Synthesize offset of the whole access. 16582 CharUnits Offset; 16583 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 16584 I++) { 16585 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 16586 } 16587 16588 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 16589 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 16590 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 16591 16592 // The base expression of the innermost MemberExpr may give 16593 // stronger guarantees than the class containing the member. 16594 if (DRE && !TopME->isArrow()) { 16595 const ValueDecl *VD = DRE->getDecl(); 16596 if (!VD->getType()->isReferenceType()) 16597 CompleteObjectAlignment = 16598 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 16599 } 16600 16601 // Check if the synthesized offset fulfills the alignment. 16602 if (Offset % ExpectedAlignment != 0 || 16603 // It may fulfill the offset it but the effective alignment may still be 16604 // lower than the expected expression alignment. 16605 CompleteObjectAlignment < ExpectedAlignment) { 16606 // If this happens, we want to determine a sensible culprit of this. 16607 // Intuitively, watching the chain of member expressions from right to 16608 // left, we start with the required alignment (as required by the field 16609 // type) but some packed attribute in that chain has reduced the alignment. 16610 // It may happen that another packed structure increases it again. But if 16611 // we are here such increase has not been enough. So pointing the first 16612 // FieldDecl that either is packed or else its RecordDecl is, 16613 // seems reasonable. 16614 FieldDecl *FD = nullptr; 16615 CharUnits Alignment; 16616 for (FieldDecl *FDI : ReverseMemberChain) { 16617 if (FDI->hasAttr<PackedAttr>() || 16618 FDI->getParent()->hasAttr<PackedAttr>()) { 16619 FD = FDI; 16620 Alignment = std::min( 16621 Context.getTypeAlignInChars(FD->getType()), 16622 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 16623 break; 16624 } 16625 } 16626 assert(FD && "We did not find a packed FieldDecl!"); 16627 Action(E, FD->getParent(), FD, Alignment); 16628 } 16629 } 16630 16631 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 16632 using namespace std::placeholders; 16633 16634 RefersToMemberWithReducedAlignment( 16635 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 16636 _2, _3, _4)); 16637 } 16638 16639 // Check if \p Ty is a valid type for the elementwise math builtins. If it is 16640 // not a valid type, emit an error message and return true. Otherwise return 16641 // false. 16642 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, 16643 QualType Ty) { 16644 if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) { 16645 S.Diag(Loc, diag::err_builtin_invalid_arg_type) 16646 << 1 << /* vector, integer or float ty*/ 0 << Ty; 16647 return true; 16648 } 16649 return false; 16650 } 16651 16652 bool Sema::SemaBuiltinElementwiseMathOneArg(CallExpr *TheCall) { 16653 if (checkArgCount(*this, TheCall, 1)) 16654 return true; 16655 16656 ExprResult A = UsualUnaryConversions(TheCall->getArg(0)); 16657 SourceLocation ArgLoc = TheCall->getArg(0)->getBeginLoc(); 16658 if (A.isInvalid()) 16659 return true; 16660 16661 TheCall->setArg(0, A.get()); 16662 QualType TyA = A.get()->getType(); 16663 if (checkMathBuiltinElementType(*this, ArgLoc, TyA)) 16664 return true; 16665 16666 QualType EltTy = TyA; 16667 if (auto *VecTy = EltTy->getAs<VectorType>()) 16668 EltTy = VecTy->getElementType(); 16669 if (EltTy->isUnsignedIntegerType()) 16670 return Diag(ArgLoc, diag::err_builtin_invalid_arg_type) 16671 << 1 << /*signed integer or float ty*/ 3 << TyA; 16672 16673 TheCall->setType(TyA); 16674 return false; 16675 } 16676 16677 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) { 16678 if (checkArgCount(*this, TheCall, 2)) 16679 return true; 16680 16681 ExprResult A = TheCall->getArg(0); 16682 ExprResult B = TheCall->getArg(1); 16683 // Do standard promotions between the two arguments, returning their common 16684 // type. 16685 QualType Res = 16686 UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison); 16687 if (A.isInvalid() || B.isInvalid()) 16688 return true; 16689 16690 QualType TyA = A.get()->getType(); 16691 QualType TyB = B.get()->getType(); 16692 16693 if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType()) 16694 return Diag(A.get()->getBeginLoc(), 16695 diag::err_typecheck_call_different_arg_types) 16696 << TyA << TyB; 16697 16698 if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA)) 16699 return true; 16700 16701 TheCall->setArg(0, A.get()); 16702 TheCall->setArg(1, B.get()); 16703 TheCall->setType(Res); 16704 return false; 16705 } 16706 16707 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 16708 ExprResult CallResult) { 16709 if (checkArgCount(*this, TheCall, 1)) 16710 return ExprError(); 16711 16712 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 16713 if (MatrixArg.isInvalid()) 16714 return MatrixArg; 16715 Expr *Matrix = MatrixArg.get(); 16716 16717 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 16718 if (!MType) { 16719 Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16720 << 1 << /* matrix ty*/ 1 << Matrix->getType(); 16721 return ExprError(); 16722 } 16723 16724 // Create returned matrix type by swapping rows and columns of the argument 16725 // matrix type. 16726 QualType ResultType = Context.getConstantMatrixType( 16727 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 16728 16729 // Change the return type to the type of the returned matrix. 16730 TheCall->setType(ResultType); 16731 16732 // Update call argument to use the possibly converted matrix argument. 16733 TheCall->setArg(0, Matrix); 16734 return CallResult; 16735 } 16736 16737 // Get and verify the matrix dimensions. 16738 static llvm::Optional<unsigned> 16739 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16740 SourceLocation ErrorPos; 16741 Optional<llvm::APSInt> Value = 16742 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16743 if (!Value) { 16744 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16745 << Name; 16746 return {}; 16747 } 16748 uint64_t Dim = Value->getZExtValue(); 16749 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16750 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16751 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16752 return {}; 16753 } 16754 return Dim; 16755 } 16756 16757 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16758 ExprResult CallResult) { 16759 if (!getLangOpts().MatrixTypes) { 16760 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16761 return ExprError(); 16762 } 16763 16764 if (checkArgCount(*this, TheCall, 4)) 16765 return ExprError(); 16766 16767 unsigned PtrArgIdx = 0; 16768 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16769 Expr *RowsExpr = TheCall->getArg(1); 16770 Expr *ColumnsExpr = TheCall->getArg(2); 16771 Expr *StrideExpr = TheCall->getArg(3); 16772 16773 bool ArgError = false; 16774 16775 // Check pointer argument. 16776 { 16777 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16778 if (PtrConv.isInvalid()) 16779 return PtrConv; 16780 PtrExpr = PtrConv.get(); 16781 TheCall->setArg(0, PtrExpr); 16782 if (PtrExpr->isTypeDependent()) { 16783 TheCall->setType(Context.DependentTy); 16784 return TheCall; 16785 } 16786 } 16787 16788 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16789 QualType ElementTy; 16790 if (!PtrTy) { 16791 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16792 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 16793 ArgError = true; 16794 } else { 16795 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16796 16797 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16798 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16799 << PtrArgIdx + 1 << /* pointer to element ty*/ 2 16800 << PtrExpr->getType(); 16801 ArgError = true; 16802 } 16803 } 16804 16805 // Apply default Lvalue conversions and convert the expression to size_t. 16806 auto ApplyArgumentConversions = [this](Expr *E) { 16807 ExprResult Conv = DefaultLvalueConversion(E); 16808 if (Conv.isInvalid()) 16809 return Conv; 16810 16811 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16812 }; 16813 16814 // Apply conversion to row and column expressions. 16815 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16816 if (!RowsConv.isInvalid()) { 16817 RowsExpr = RowsConv.get(); 16818 TheCall->setArg(1, RowsExpr); 16819 } else 16820 RowsExpr = nullptr; 16821 16822 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16823 if (!ColumnsConv.isInvalid()) { 16824 ColumnsExpr = ColumnsConv.get(); 16825 TheCall->setArg(2, ColumnsExpr); 16826 } else 16827 ColumnsExpr = nullptr; 16828 16829 // If any any part of the result matrix type is still pending, just use 16830 // Context.DependentTy, until all parts are resolved. 16831 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16832 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16833 TheCall->setType(Context.DependentTy); 16834 return CallResult; 16835 } 16836 16837 // Check row and column dimensions. 16838 llvm::Optional<unsigned> MaybeRows; 16839 if (RowsExpr) 16840 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16841 16842 llvm::Optional<unsigned> MaybeColumns; 16843 if (ColumnsExpr) 16844 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16845 16846 // Check stride argument. 16847 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16848 if (StrideConv.isInvalid()) 16849 return ExprError(); 16850 StrideExpr = StrideConv.get(); 16851 TheCall->setArg(3, StrideExpr); 16852 16853 if (MaybeRows) { 16854 if (Optional<llvm::APSInt> Value = 16855 StrideExpr->getIntegerConstantExpr(Context)) { 16856 uint64_t Stride = Value->getZExtValue(); 16857 if (Stride < *MaybeRows) { 16858 Diag(StrideExpr->getBeginLoc(), 16859 diag::err_builtin_matrix_stride_too_small); 16860 ArgError = true; 16861 } 16862 } 16863 } 16864 16865 if (ArgError || !MaybeRows || !MaybeColumns) 16866 return ExprError(); 16867 16868 TheCall->setType( 16869 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16870 return CallResult; 16871 } 16872 16873 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16874 ExprResult CallResult) { 16875 if (checkArgCount(*this, TheCall, 3)) 16876 return ExprError(); 16877 16878 unsigned PtrArgIdx = 1; 16879 Expr *MatrixExpr = TheCall->getArg(0); 16880 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16881 Expr *StrideExpr = TheCall->getArg(2); 16882 16883 bool ArgError = false; 16884 16885 { 16886 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16887 if (MatrixConv.isInvalid()) 16888 return MatrixConv; 16889 MatrixExpr = MatrixConv.get(); 16890 TheCall->setArg(0, MatrixExpr); 16891 } 16892 if (MatrixExpr->isTypeDependent()) { 16893 TheCall->setType(Context.DependentTy); 16894 return TheCall; 16895 } 16896 16897 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16898 if (!MatrixTy) { 16899 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16900 << 1 << /*matrix ty */ 1 << MatrixExpr->getType(); 16901 ArgError = true; 16902 } 16903 16904 { 16905 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16906 if (PtrConv.isInvalid()) 16907 return PtrConv; 16908 PtrExpr = PtrConv.get(); 16909 TheCall->setArg(1, PtrExpr); 16910 if (PtrExpr->isTypeDependent()) { 16911 TheCall->setType(Context.DependentTy); 16912 return TheCall; 16913 } 16914 } 16915 16916 // Check pointer argument. 16917 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16918 if (!PtrTy) { 16919 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type) 16920 << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType(); 16921 ArgError = true; 16922 } else { 16923 QualType ElementTy = PtrTy->getPointeeType(); 16924 if (ElementTy.isConstQualified()) { 16925 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16926 ArgError = true; 16927 } 16928 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16929 if (MatrixTy && 16930 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16931 Diag(PtrExpr->getBeginLoc(), 16932 diag::err_builtin_matrix_pointer_arg_mismatch) 16933 << ElementTy << MatrixTy->getElementType(); 16934 ArgError = true; 16935 } 16936 } 16937 16938 // Apply default Lvalue conversions and convert the stride expression to 16939 // size_t. 16940 { 16941 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16942 if (StrideConv.isInvalid()) 16943 return StrideConv; 16944 16945 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16946 if (StrideConv.isInvalid()) 16947 return StrideConv; 16948 StrideExpr = StrideConv.get(); 16949 TheCall->setArg(2, StrideExpr); 16950 } 16951 16952 // Check stride argument. 16953 if (MatrixTy) { 16954 if (Optional<llvm::APSInt> Value = 16955 StrideExpr->getIntegerConstantExpr(Context)) { 16956 uint64_t Stride = Value->getZExtValue(); 16957 if (Stride < MatrixTy->getNumRows()) { 16958 Diag(StrideExpr->getBeginLoc(), 16959 diag::err_builtin_matrix_stride_too_small); 16960 ArgError = true; 16961 } 16962 } 16963 } 16964 16965 if (ArgError) 16966 return ExprError(); 16967 16968 return CallResult; 16969 } 16970 16971 /// \brief Enforce the bounds of a TCB 16972 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 16973 /// directly calls other functions in the same TCB as marked by the enforce_tcb 16974 /// and enforce_tcb_leaf attributes. 16975 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 16976 const FunctionDecl *Callee) { 16977 const FunctionDecl *Caller = getCurFunctionDecl(); 16978 16979 // Calls to builtins are not enforced. 16980 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 16981 Callee->getBuiltinID() != 0) 16982 return; 16983 16984 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 16985 // all TCBs the callee is a part of. 16986 llvm::StringSet<> CalleeTCBs; 16987 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 16988 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16989 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 16990 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16991 16992 // Go through the TCBs the caller is a part of and emit warnings if Caller 16993 // is in a TCB that the Callee is not. 16994 for_each( 16995 Caller->specific_attrs<EnforceTCBAttr>(), 16996 [&](const auto *A) { 16997 StringRef CallerTCB = A->getTCBName(); 16998 if (CalleeTCBs.count(CallerTCB) == 0) { 16999 this->Diag(TheCall->getExprLoc(), 17000 diag::warn_tcb_enforcement_violation) << Callee 17001 << CallerTCB; 17002 } 17003 }); 17004 } 17005