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 EstimateSizeFormatHandler 412 : public analyze_format_string::FormatStringHandler { 413 size_t Size; 414 415 public: 416 EstimateSizeFormatHandler(StringRef Format) 417 : Size(std::min(Format.find(0), Format.size()) + 418 1 /* null byte always written by sprintf */) {} 419 420 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 421 const char *, unsigned SpecifierLen) override { 422 423 const size_t FieldWidth = computeFieldWidth(FS); 424 const size_t Precision = computePrecision(FS); 425 426 // The actual format. 427 switch (FS.getConversionSpecifier().getKind()) { 428 // Just a char. 429 case analyze_format_string::ConversionSpecifier::cArg: 430 case analyze_format_string::ConversionSpecifier::CArg: 431 Size += std::max(FieldWidth, (size_t)1); 432 break; 433 // Just an integer. 434 case analyze_format_string::ConversionSpecifier::dArg: 435 case analyze_format_string::ConversionSpecifier::DArg: 436 case analyze_format_string::ConversionSpecifier::iArg: 437 case analyze_format_string::ConversionSpecifier::oArg: 438 case analyze_format_string::ConversionSpecifier::OArg: 439 case analyze_format_string::ConversionSpecifier::uArg: 440 case analyze_format_string::ConversionSpecifier::UArg: 441 case analyze_format_string::ConversionSpecifier::xArg: 442 case analyze_format_string::ConversionSpecifier::XArg: 443 Size += std::max(FieldWidth, Precision); 444 break; 445 446 // %g style conversion switches between %f or %e style dynamically. 447 // %f always takes less space, so default to it. 448 case analyze_format_string::ConversionSpecifier::gArg: 449 case analyze_format_string::ConversionSpecifier::GArg: 450 451 // Floating point number in the form '[+]ddd.ddd'. 452 case analyze_format_string::ConversionSpecifier::fArg: 453 case analyze_format_string::ConversionSpecifier::FArg: 454 Size += std::max(FieldWidth, 1 /* integer part */ + 455 (Precision ? 1 + Precision 456 : 0) /* period + decimal */); 457 break; 458 459 // Floating point number in the form '[-]d.ddde[+-]dd'. 460 case analyze_format_string::ConversionSpecifier::eArg: 461 case analyze_format_string::ConversionSpecifier::EArg: 462 Size += 463 std::max(FieldWidth, 464 1 /* integer part */ + 465 (Precision ? 1 + Precision : 0) /* period + decimal */ + 466 1 /* e or E letter */ + 2 /* exponent */); 467 break; 468 469 // Floating point number in the form '[-]0xh.hhhhp±dd'. 470 case analyze_format_string::ConversionSpecifier::aArg: 471 case analyze_format_string::ConversionSpecifier::AArg: 472 Size += 473 std::max(FieldWidth, 474 2 /* 0x */ + 1 /* integer part */ + 475 (Precision ? 1 + Precision : 0) /* period + decimal */ + 476 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 477 break; 478 479 // Just a string. 480 case analyze_format_string::ConversionSpecifier::sArg: 481 case analyze_format_string::ConversionSpecifier::SArg: 482 Size += FieldWidth; 483 break; 484 485 // Just a pointer in the form '0xddd'. 486 case analyze_format_string::ConversionSpecifier::pArg: 487 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 488 break; 489 490 // A plain percent. 491 case analyze_format_string::ConversionSpecifier::PercentArg: 492 Size += 1; 493 break; 494 495 default: 496 break; 497 } 498 499 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 500 501 if (FS.hasAlternativeForm()) { 502 switch (FS.getConversionSpecifier().getKind()) { 503 default: 504 break; 505 // Force a leading '0'. 506 case analyze_format_string::ConversionSpecifier::oArg: 507 Size += 1; 508 break; 509 // Force a leading '0x'. 510 case analyze_format_string::ConversionSpecifier::xArg: 511 case analyze_format_string::ConversionSpecifier::XArg: 512 Size += 2; 513 break; 514 // Force a period '.' before decimal, even if precision is 0. 515 case analyze_format_string::ConversionSpecifier::aArg: 516 case analyze_format_string::ConversionSpecifier::AArg: 517 case analyze_format_string::ConversionSpecifier::eArg: 518 case analyze_format_string::ConversionSpecifier::EArg: 519 case analyze_format_string::ConversionSpecifier::fArg: 520 case analyze_format_string::ConversionSpecifier::FArg: 521 case analyze_format_string::ConversionSpecifier::gArg: 522 case analyze_format_string::ConversionSpecifier::GArg: 523 Size += (Precision ? 0 : 1); 524 break; 525 } 526 } 527 assert(SpecifierLen <= Size && "no underflow"); 528 Size -= SpecifierLen; 529 return true; 530 } 531 532 size_t getSizeLowerBound() const { return Size; } 533 534 private: 535 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 536 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 537 size_t FieldWidth = 0; 538 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 539 FieldWidth = FW.getConstantAmount(); 540 return FieldWidth; 541 } 542 543 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 544 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 545 size_t Precision = 0; 546 547 // See man 3 printf for default precision value based on the specifier. 548 switch (FW.getHowSpecified()) { 549 case analyze_format_string::OptionalAmount::NotSpecified: 550 switch (FS.getConversionSpecifier().getKind()) { 551 default: 552 break; 553 case analyze_format_string::ConversionSpecifier::dArg: // %d 554 case analyze_format_string::ConversionSpecifier::DArg: // %D 555 case analyze_format_string::ConversionSpecifier::iArg: // %i 556 Precision = 1; 557 break; 558 case analyze_format_string::ConversionSpecifier::oArg: // %d 559 case analyze_format_string::ConversionSpecifier::OArg: // %D 560 case analyze_format_string::ConversionSpecifier::uArg: // %d 561 case analyze_format_string::ConversionSpecifier::UArg: // %D 562 case analyze_format_string::ConversionSpecifier::xArg: // %d 563 case analyze_format_string::ConversionSpecifier::XArg: // %D 564 Precision = 1; 565 break; 566 case analyze_format_string::ConversionSpecifier::fArg: // %f 567 case analyze_format_string::ConversionSpecifier::FArg: // %F 568 case analyze_format_string::ConversionSpecifier::eArg: // %e 569 case analyze_format_string::ConversionSpecifier::EArg: // %E 570 case analyze_format_string::ConversionSpecifier::gArg: // %g 571 case analyze_format_string::ConversionSpecifier::GArg: // %G 572 Precision = 6; 573 break; 574 case analyze_format_string::ConversionSpecifier::pArg: // %d 575 Precision = 1; 576 break; 577 } 578 break; 579 case analyze_format_string::OptionalAmount::Constant: 580 Precision = FW.getConstantAmount(); 581 break; 582 default: 583 break; 584 } 585 return Precision; 586 } 587 }; 588 589 } // namespace 590 591 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 592 CallExpr *TheCall) { 593 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 594 isConstantEvaluated()) 595 return; 596 597 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 598 if (!BuiltinID) 599 return; 600 601 const TargetInfo &TI = getASTContext().getTargetInfo(); 602 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 603 604 auto ComputeExplicitObjectSizeArgument = 605 [&](unsigned Index) -> Optional<llvm::APSInt> { 606 Expr::EvalResult Result; 607 Expr *SizeArg = TheCall->getArg(Index); 608 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 609 return llvm::None; 610 return Result.Val.getInt(); 611 }; 612 613 auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 614 // If the parameter has a pass_object_size attribute, then we should use its 615 // (potentially) more strict checking mode. Otherwise, conservatively assume 616 // type 0. 617 int BOSType = 0; 618 if (const auto *POS = 619 FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>()) 620 BOSType = POS->getType(); 621 622 const Expr *ObjArg = TheCall->getArg(Index); 623 uint64_t Result; 624 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 625 return llvm::None; 626 627 // Get the object size in the target's size_t width. 628 return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 629 }; 630 631 auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> { 632 Expr *ObjArg = TheCall->getArg(Index); 633 uint64_t Result; 634 if (!ObjArg->tryEvaluateStrLen(Result, getASTContext())) 635 return llvm::None; 636 // Add 1 for null byte. 637 return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth); 638 }; 639 640 Optional<llvm::APSInt> SourceSize; 641 Optional<llvm::APSInt> DestinationSize; 642 unsigned DiagID = 0; 643 bool IsChkVariant = false; 644 645 switch (BuiltinID) { 646 default: 647 return; 648 case Builtin::BI__builtin_strcpy: 649 case Builtin::BIstrcpy: { 650 DiagID = diag::warn_fortify_strlen_overflow; 651 SourceSize = ComputeStrLenArgument(1); 652 DestinationSize = ComputeSizeArgument(0); 653 break; 654 } 655 656 case Builtin::BI__builtin___strcpy_chk: { 657 DiagID = diag::warn_fortify_strlen_overflow; 658 SourceSize = ComputeStrLenArgument(1); 659 DestinationSize = ComputeExplicitObjectSizeArgument(2); 660 IsChkVariant = true; 661 break; 662 } 663 664 case Builtin::BIsprintf: 665 case Builtin::BI__builtin___sprintf_chk: { 666 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 667 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 668 669 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 670 671 if (!Format->isAscii() && !Format->isUTF8()) 672 return; 673 674 StringRef FormatStrRef = Format->getString(); 675 EstimateSizeFormatHandler H(FormatStrRef); 676 const char *FormatBytes = FormatStrRef.data(); 677 const ConstantArrayType *T = 678 Context.getAsConstantArrayType(Format->getType()); 679 assert(T && "String literal not of constant array type!"); 680 size_t TypeSize = T->getSize().getZExtValue(); 681 682 // In case there's a null byte somewhere. 683 size_t StrLen = 684 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 685 if (!analyze_format_string::ParsePrintfString( 686 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 687 Context.getTargetInfo(), false)) { 688 DiagID = diag::warn_fortify_source_format_overflow; 689 SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 690 .extOrTrunc(SizeTypeWidth); 691 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 692 DestinationSize = ComputeExplicitObjectSizeArgument(2); 693 IsChkVariant = true; 694 } else { 695 DestinationSize = ComputeSizeArgument(0); 696 } 697 break; 698 } 699 } 700 return; 701 } 702 case Builtin::BI__builtin___memcpy_chk: 703 case Builtin::BI__builtin___memmove_chk: 704 case Builtin::BI__builtin___memset_chk: 705 case Builtin::BI__builtin___strlcat_chk: 706 case Builtin::BI__builtin___strlcpy_chk: 707 case Builtin::BI__builtin___strncat_chk: 708 case Builtin::BI__builtin___strncpy_chk: 709 case Builtin::BI__builtin___stpncpy_chk: 710 case Builtin::BI__builtin___memccpy_chk: 711 case Builtin::BI__builtin___mempcpy_chk: { 712 DiagID = diag::warn_builtin_chk_overflow; 713 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2); 714 DestinationSize = 715 ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 716 IsChkVariant = true; 717 break; 718 } 719 720 case Builtin::BI__builtin___snprintf_chk: 721 case Builtin::BI__builtin___vsnprintf_chk: { 722 DiagID = diag::warn_builtin_chk_overflow; 723 SourceSize = ComputeExplicitObjectSizeArgument(1); 724 DestinationSize = ComputeExplicitObjectSizeArgument(3); 725 IsChkVariant = true; 726 break; 727 } 728 729 case Builtin::BIstrncat: 730 case Builtin::BI__builtin_strncat: 731 case Builtin::BIstrncpy: 732 case Builtin::BI__builtin_strncpy: 733 case Builtin::BIstpncpy: 734 case Builtin::BI__builtin_stpncpy: { 735 // Whether these functions overflow depends on the runtime strlen of the 736 // string, not just the buffer size, so emitting the "always overflow" 737 // diagnostic isn't quite right. We should still diagnose passing a buffer 738 // size larger than the destination buffer though; this is a runtime abort 739 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 740 DiagID = diag::warn_fortify_source_size_mismatch; 741 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 742 DestinationSize = ComputeSizeArgument(0); 743 break; 744 } 745 746 case Builtin::BImemcpy: 747 case Builtin::BI__builtin_memcpy: 748 case Builtin::BImemmove: 749 case Builtin::BI__builtin_memmove: 750 case Builtin::BImemset: 751 case Builtin::BI__builtin_memset: 752 case Builtin::BImempcpy: 753 case Builtin::BI__builtin_mempcpy: { 754 DiagID = diag::warn_fortify_source_overflow; 755 SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1); 756 DestinationSize = ComputeSizeArgument(0); 757 break; 758 } 759 case Builtin::BIsnprintf: 760 case Builtin::BI__builtin_snprintf: 761 case Builtin::BIvsnprintf: 762 case Builtin::BI__builtin_vsnprintf: { 763 DiagID = diag::warn_fortify_source_size_mismatch; 764 SourceSize = ComputeExplicitObjectSizeArgument(1); 765 DestinationSize = ComputeSizeArgument(0); 766 break; 767 } 768 } 769 770 if (!SourceSize || !DestinationSize || 771 SourceSize.getValue().ule(DestinationSize.getValue())) 772 return; 773 774 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 775 // Skim off the details of whichever builtin was called to produce a better 776 // diagnostic, as it's unlikely that the user wrote the __builtin explicitly. 777 if (IsChkVariant) { 778 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 779 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 780 } else if (FunctionName.startswith("__builtin_")) { 781 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 782 } 783 784 SmallString<16> DestinationStr; 785 SmallString<16> SourceStr; 786 DestinationSize->toString(DestinationStr, /*Radix=*/10); 787 SourceSize->toString(SourceStr, /*Radix=*/10); 788 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 789 PDiag(DiagID) 790 << FunctionName << DestinationStr << SourceStr); 791 } 792 793 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 794 Scope::ScopeFlags NeededScopeFlags, 795 unsigned DiagID) { 796 // Scopes aren't available during instantiation. Fortunately, builtin 797 // functions cannot be template args so they cannot be formed through template 798 // instantiation. Therefore checking once during the parse is sufficient. 799 if (SemaRef.inTemplateInstantiation()) 800 return false; 801 802 Scope *S = SemaRef.getCurScope(); 803 while (S && !S->isSEHExceptScope()) 804 S = S->getParent(); 805 if (!S || !(S->getFlags() & NeededScopeFlags)) { 806 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 807 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 808 << DRE->getDecl()->getIdentifier(); 809 return true; 810 } 811 812 return false; 813 } 814 815 static inline bool isBlockPointer(Expr *Arg) { 816 return Arg->getType()->isBlockPointerType(); 817 } 818 819 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 820 /// void*, which is a requirement of device side enqueue. 821 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 822 const BlockPointerType *BPT = 823 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 824 ArrayRef<QualType> Params = 825 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 826 unsigned ArgCounter = 0; 827 bool IllegalParams = false; 828 // Iterate through the block parameters until either one is found that is not 829 // a local void*, or the block is valid. 830 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 831 I != E; ++I, ++ArgCounter) { 832 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 833 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 834 LangAS::opencl_local) { 835 // Get the location of the error. If a block literal has been passed 836 // (BlockExpr) then we can point straight to the offending argument, 837 // else we just point to the variable reference. 838 SourceLocation ErrorLoc; 839 if (isa<BlockExpr>(BlockArg)) { 840 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 841 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 842 } else if (isa<DeclRefExpr>(BlockArg)) { 843 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 844 } 845 S.Diag(ErrorLoc, 846 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 847 IllegalParams = true; 848 } 849 } 850 851 return IllegalParams; 852 } 853 854 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 855 if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) { 856 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 857 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 858 return true; 859 } 860 return false; 861 } 862 863 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 864 if (checkArgCount(S, TheCall, 2)) 865 return true; 866 867 if (checkOpenCLSubgroupExt(S, TheCall)) 868 return true; 869 870 // First argument is an ndrange_t type. 871 Expr *NDRangeArg = TheCall->getArg(0); 872 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 873 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 874 << TheCall->getDirectCallee() << "'ndrange_t'"; 875 return true; 876 } 877 878 Expr *BlockArg = TheCall->getArg(1); 879 if (!isBlockPointer(BlockArg)) { 880 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 881 << TheCall->getDirectCallee() << "block"; 882 return true; 883 } 884 return checkOpenCLBlockArgs(S, BlockArg); 885 } 886 887 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 888 /// get_kernel_work_group_size 889 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 890 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 891 if (checkArgCount(S, TheCall, 1)) 892 return true; 893 894 Expr *BlockArg = TheCall->getArg(0); 895 if (!isBlockPointer(BlockArg)) { 896 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 897 << TheCall->getDirectCallee() << "block"; 898 return true; 899 } 900 return checkOpenCLBlockArgs(S, BlockArg); 901 } 902 903 /// Diagnose integer type and any valid implicit conversion to it. 904 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 905 const QualType &IntType); 906 907 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 908 unsigned Start, unsigned End) { 909 bool IllegalParams = false; 910 for (unsigned I = Start; I <= End; ++I) 911 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 912 S.Context.getSizeType()); 913 return IllegalParams; 914 } 915 916 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 917 /// 'local void*' parameter of passed block. 918 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 919 Expr *BlockArg, 920 unsigned NumNonVarArgs) { 921 const BlockPointerType *BPT = 922 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 923 unsigned NumBlockParams = 924 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 925 unsigned TotalNumArgs = TheCall->getNumArgs(); 926 927 // For each argument passed to the block, a corresponding uint needs to 928 // be passed to describe the size of the local memory. 929 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 930 S.Diag(TheCall->getBeginLoc(), 931 diag::err_opencl_enqueue_kernel_local_size_args); 932 return true; 933 } 934 935 // Check that the sizes of the local memory are specified by integers. 936 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 937 TotalNumArgs - 1); 938 } 939 940 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 941 /// overload formats specified in Table 6.13.17.1. 942 /// int enqueue_kernel(queue_t queue, 943 /// kernel_enqueue_flags_t flags, 944 /// const ndrange_t ndrange, 945 /// void (^block)(void)) 946 /// int enqueue_kernel(queue_t queue, 947 /// kernel_enqueue_flags_t flags, 948 /// const ndrange_t ndrange, 949 /// uint num_events_in_wait_list, 950 /// clk_event_t *event_wait_list, 951 /// clk_event_t *event_ret, 952 /// void (^block)(void)) 953 /// int enqueue_kernel(queue_t queue, 954 /// kernel_enqueue_flags_t flags, 955 /// const ndrange_t ndrange, 956 /// void (^block)(local void*, ...), 957 /// uint size0, ...) 958 /// int enqueue_kernel(queue_t queue, 959 /// kernel_enqueue_flags_t flags, 960 /// const ndrange_t ndrange, 961 /// uint num_events_in_wait_list, 962 /// clk_event_t *event_wait_list, 963 /// clk_event_t *event_ret, 964 /// void (^block)(local void*, ...), 965 /// uint size0, ...) 966 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 967 unsigned NumArgs = TheCall->getNumArgs(); 968 969 if (NumArgs < 4) { 970 S.Diag(TheCall->getBeginLoc(), 971 diag::err_typecheck_call_too_few_args_at_least) 972 << 0 << 4 << NumArgs; 973 return true; 974 } 975 976 Expr *Arg0 = TheCall->getArg(0); 977 Expr *Arg1 = TheCall->getArg(1); 978 Expr *Arg2 = TheCall->getArg(2); 979 Expr *Arg3 = TheCall->getArg(3); 980 981 // First argument always needs to be a queue_t type. 982 if (!Arg0->getType()->isQueueT()) { 983 S.Diag(TheCall->getArg(0)->getBeginLoc(), 984 diag::err_opencl_builtin_expected_type) 985 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 986 return true; 987 } 988 989 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 990 if (!Arg1->getType()->isIntegerType()) { 991 S.Diag(TheCall->getArg(1)->getBeginLoc(), 992 diag::err_opencl_builtin_expected_type) 993 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 994 return true; 995 } 996 997 // Third argument is always an ndrange_t type. 998 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 999 S.Diag(TheCall->getArg(2)->getBeginLoc(), 1000 diag::err_opencl_builtin_expected_type) 1001 << TheCall->getDirectCallee() << "'ndrange_t'"; 1002 return true; 1003 } 1004 1005 // With four arguments, there is only one form that the function could be 1006 // called in: no events and no variable arguments. 1007 if (NumArgs == 4) { 1008 // check that the last argument is the right block type. 1009 if (!isBlockPointer(Arg3)) { 1010 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1011 << TheCall->getDirectCallee() << "block"; 1012 return true; 1013 } 1014 // we have a block type, check the prototype 1015 const BlockPointerType *BPT = 1016 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1017 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1018 S.Diag(Arg3->getBeginLoc(), 1019 diag::err_opencl_enqueue_kernel_blocks_no_args); 1020 return true; 1021 } 1022 return false; 1023 } 1024 // we can have block + varargs. 1025 if (isBlockPointer(Arg3)) 1026 return (checkOpenCLBlockArgs(S, Arg3) || 1027 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1028 // last two cases with either exactly 7 args or 7 args and varargs. 1029 if (NumArgs >= 7) { 1030 // check common block argument. 1031 Expr *Arg6 = TheCall->getArg(6); 1032 if (!isBlockPointer(Arg6)) { 1033 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1034 << TheCall->getDirectCallee() << "block"; 1035 return true; 1036 } 1037 if (checkOpenCLBlockArgs(S, Arg6)) 1038 return true; 1039 1040 // Forth argument has to be any integer type. 1041 if (!Arg3->getType()->isIntegerType()) { 1042 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1043 diag::err_opencl_builtin_expected_type) 1044 << TheCall->getDirectCallee() << "integer"; 1045 return true; 1046 } 1047 // check remaining common arguments. 1048 Expr *Arg4 = TheCall->getArg(4); 1049 Expr *Arg5 = TheCall->getArg(5); 1050 1051 // Fifth argument is always passed as a pointer to clk_event_t. 1052 if (!Arg4->isNullPointerConstant(S.Context, 1053 Expr::NPC_ValueDependentIsNotNull) && 1054 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1055 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1056 diag::err_opencl_builtin_expected_type) 1057 << TheCall->getDirectCallee() 1058 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1059 return true; 1060 } 1061 1062 // Sixth argument is always passed as a pointer to clk_event_t. 1063 if (!Arg5->isNullPointerConstant(S.Context, 1064 Expr::NPC_ValueDependentIsNotNull) && 1065 !(Arg5->getType()->isPointerType() && 1066 Arg5->getType()->getPointeeType()->isClkEventT())) { 1067 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1068 diag::err_opencl_builtin_expected_type) 1069 << TheCall->getDirectCallee() 1070 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1071 return true; 1072 } 1073 1074 if (NumArgs == 7) 1075 return false; 1076 1077 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1078 } 1079 1080 // None of the specific case has been detected, give generic error 1081 S.Diag(TheCall->getBeginLoc(), 1082 diag::err_opencl_enqueue_kernel_incorrect_args); 1083 return true; 1084 } 1085 1086 /// Returns OpenCL access qual. 1087 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1088 return D->getAttr<OpenCLAccessAttr>(); 1089 } 1090 1091 /// Returns true if pipe element type is different from the pointer. 1092 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1093 const Expr *Arg0 = Call->getArg(0); 1094 // First argument type should always be pipe. 1095 if (!Arg0->getType()->isPipeType()) { 1096 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1097 << Call->getDirectCallee() << Arg0->getSourceRange(); 1098 return true; 1099 } 1100 OpenCLAccessAttr *AccessQual = 1101 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1102 // Validates the access qualifier is compatible with the call. 1103 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1104 // read_only and write_only, and assumed to be read_only if no qualifier is 1105 // specified. 1106 switch (Call->getDirectCallee()->getBuiltinID()) { 1107 case Builtin::BIread_pipe: 1108 case Builtin::BIreserve_read_pipe: 1109 case Builtin::BIcommit_read_pipe: 1110 case Builtin::BIwork_group_reserve_read_pipe: 1111 case Builtin::BIsub_group_reserve_read_pipe: 1112 case Builtin::BIwork_group_commit_read_pipe: 1113 case Builtin::BIsub_group_commit_read_pipe: 1114 if (!(!AccessQual || AccessQual->isReadOnly())) { 1115 S.Diag(Arg0->getBeginLoc(), 1116 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1117 << "read_only" << Arg0->getSourceRange(); 1118 return true; 1119 } 1120 break; 1121 case Builtin::BIwrite_pipe: 1122 case Builtin::BIreserve_write_pipe: 1123 case Builtin::BIcommit_write_pipe: 1124 case Builtin::BIwork_group_reserve_write_pipe: 1125 case Builtin::BIsub_group_reserve_write_pipe: 1126 case Builtin::BIwork_group_commit_write_pipe: 1127 case Builtin::BIsub_group_commit_write_pipe: 1128 if (!(AccessQual && AccessQual->isWriteOnly())) { 1129 S.Diag(Arg0->getBeginLoc(), 1130 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1131 << "write_only" << Arg0->getSourceRange(); 1132 return true; 1133 } 1134 break; 1135 default: 1136 break; 1137 } 1138 return false; 1139 } 1140 1141 /// Returns true if pipe element type is different from the pointer. 1142 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1143 const Expr *Arg0 = Call->getArg(0); 1144 const Expr *ArgIdx = Call->getArg(Idx); 1145 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1146 const QualType EltTy = PipeTy->getElementType(); 1147 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1148 // The Idx argument should be a pointer and the type of the pointer and 1149 // the type of pipe element should also be the same. 1150 if (!ArgTy || 1151 !S.Context.hasSameType( 1152 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1153 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1154 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1155 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1156 return true; 1157 } 1158 return false; 1159 } 1160 1161 // Performs semantic analysis for the read/write_pipe call. 1162 // \param S Reference to the semantic analyzer. 1163 // \param Call A pointer to the builtin call. 1164 // \return True if a semantic error has been found, false otherwise. 1165 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1166 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1167 // functions have two forms. 1168 switch (Call->getNumArgs()) { 1169 case 2: 1170 if (checkOpenCLPipeArg(S, Call)) 1171 return true; 1172 // The call with 2 arguments should be 1173 // read/write_pipe(pipe T, T*). 1174 // Check packet type T. 1175 if (checkOpenCLPipePacketType(S, Call, 1)) 1176 return true; 1177 break; 1178 1179 case 4: { 1180 if (checkOpenCLPipeArg(S, Call)) 1181 return true; 1182 // The call with 4 arguments should be 1183 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1184 // Check reserve_id_t. 1185 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1186 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1187 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1188 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1189 return true; 1190 } 1191 1192 // Check the index. 1193 const Expr *Arg2 = Call->getArg(2); 1194 if (!Arg2->getType()->isIntegerType() && 1195 !Arg2->getType()->isUnsignedIntegerType()) { 1196 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1197 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1198 << Arg2->getType() << Arg2->getSourceRange(); 1199 return true; 1200 } 1201 1202 // Check packet type T. 1203 if (checkOpenCLPipePacketType(S, Call, 3)) 1204 return true; 1205 } break; 1206 default: 1207 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1208 << Call->getDirectCallee() << Call->getSourceRange(); 1209 return true; 1210 } 1211 1212 return false; 1213 } 1214 1215 // Performs a semantic analysis on the {work_group_/sub_group_ 1216 // /_}reserve_{read/write}_pipe 1217 // \param S Reference to the semantic analyzer. 1218 // \param Call The call to the builtin function to be analyzed. 1219 // \return True if a semantic error was found, false otherwise. 1220 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1221 if (checkArgCount(S, Call, 2)) 1222 return true; 1223 1224 if (checkOpenCLPipeArg(S, Call)) 1225 return true; 1226 1227 // Check the reserve size. 1228 if (!Call->getArg(1)->getType()->isIntegerType() && 1229 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1230 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1231 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1232 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1233 return true; 1234 } 1235 1236 // Since return type of reserve_read/write_pipe built-in function is 1237 // reserve_id_t, which is not defined in the builtin def file , we used int 1238 // as return type and need to override the return type of these functions. 1239 Call->setType(S.Context.OCLReserveIDTy); 1240 1241 return false; 1242 } 1243 1244 // Performs a semantic analysis on {work_group_/sub_group_ 1245 // /_}commit_{read/write}_pipe 1246 // \param S Reference to the semantic analyzer. 1247 // \param Call The call to the builtin function to be analyzed. 1248 // \return True if a semantic error was found, false otherwise. 1249 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1250 if (checkArgCount(S, Call, 2)) 1251 return true; 1252 1253 if (checkOpenCLPipeArg(S, Call)) 1254 return true; 1255 1256 // Check reserve_id_t. 1257 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1258 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1259 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1260 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1261 return true; 1262 } 1263 1264 return false; 1265 } 1266 1267 // Performs a semantic analysis on the call to built-in Pipe 1268 // Query Functions. 1269 // \param S Reference to the semantic analyzer. 1270 // \param Call The call to the builtin function to be analyzed. 1271 // \return True if a semantic error was found, false otherwise. 1272 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1273 if (checkArgCount(S, Call, 1)) 1274 return true; 1275 1276 if (!Call->getArg(0)->getType()->isPipeType()) { 1277 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1278 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1279 return true; 1280 } 1281 1282 return false; 1283 } 1284 1285 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1286 // Performs semantic analysis for the to_global/local/private call. 1287 // \param S Reference to the semantic analyzer. 1288 // \param BuiltinID ID of the builtin function. 1289 // \param Call A pointer to the builtin call. 1290 // \return True if a semantic error has been found, false otherwise. 1291 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1292 CallExpr *Call) { 1293 if (checkArgCount(S, Call, 1)) 1294 return true; 1295 1296 auto RT = Call->getArg(0)->getType(); 1297 if (!RT->isPointerType() || RT->getPointeeType() 1298 .getAddressSpace() == LangAS::opencl_constant) { 1299 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1300 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1301 return true; 1302 } 1303 1304 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1305 S.Diag(Call->getArg(0)->getBeginLoc(), 1306 diag::warn_opencl_generic_address_space_arg) 1307 << Call->getDirectCallee()->getNameInfo().getAsString() 1308 << Call->getArg(0)->getSourceRange(); 1309 } 1310 1311 RT = RT->getPointeeType(); 1312 auto Qual = RT.getQualifiers(); 1313 switch (BuiltinID) { 1314 case Builtin::BIto_global: 1315 Qual.setAddressSpace(LangAS::opencl_global); 1316 break; 1317 case Builtin::BIto_local: 1318 Qual.setAddressSpace(LangAS::opencl_local); 1319 break; 1320 case Builtin::BIto_private: 1321 Qual.setAddressSpace(LangAS::opencl_private); 1322 break; 1323 default: 1324 llvm_unreachable("Invalid builtin function"); 1325 } 1326 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1327 RT.getUnqualifiedType(), Qual))); 1328 1329 return false; 1330 } 1331 1332 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1333 if (checkArgCount(S, TheCall, 1)) 1334 return ExprError(); 1335 1336 // Compute __builtin_launder's parameter type from the argument. 1337 // The parameter type is: 1338 // * The type of the argument if it's not an array or function type, 1339 // Otherwise, 1340 // * The decayed argument type. 1341 QualType ParamTy = [&]() { 1342 QualType ArgTy = TheCall->getArg(0)->getType(); 1343 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1344 return S.Context.getPointerType(Ty->getElementType()); 1345 if (ArgTy->isFunctionType()) { 1346 return S.Context.getPointerType(ArgTy); 1347 } 1348 return ArgTy; 1349 }(); 1350 1351 TheCall->setType(ParamTy); 1352 1353 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1354 if (!ParamTy->isPointerType()) 1355 return 0; 1356 if (ParamTy->isFunctionPointerType()) 1357 return 1; 1358 if (ParamTy->isVoidPointerType()) 1359 return 2; 1360 return llvm::Optional<unsigned>{}; 1361 }(); 1362 if (DiagSelect.hasValue()) { 1363 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1364 << DiagSelect.getValue() << TheCall->getSourceRange(); 1365 return ExprError(); 1366 } 1367 1368 // We either have an incomplete class type, or we have a class template 1369 // whose instantiation has not been forced. Example: 1370 // 1371 // template <class T> struct Foo { T value; }; 1372 // Foo<int> *p = nullptr; 1373 // auto *d = __builtin_launder(p); 1374 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1375 diag::err_incomplete_type)) 1376 return ExprError(); 1377 1378 assert(ParamTy->getPointeeType()->isObjectType() && 1379 "Unhandled non-object pointer case"); 1380 1381 InitializedEntity Entity = 1382 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1383 ExprResult Arg = 1384 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1385 if (Arg.isInvalid()) 1386 return ExprError(); 1387 TheCall->setArg(0, Arg.get()); 1388 1389 return TheCall; 1390 } 1391 1392 // Emit an error and return true if the current architecture is not in the list 1393 // of supported architectures. 1394 static bool 1395 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1396 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1397 llvm::Triple::ArchType CurArch = 1398 S.getASTContext().getTargetInfo().getTriple().getArch(); 1399 if (llvm::is_contained(SupportedArchs, CurArch)) 1400 return false; 1401 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1402 << TheCall->getSourceRange(); 1403 return true; 1404 } 1405 1406 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1407 SourceLocation CallSiteLoc); 1408 1409 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1410 CallExpr *TheCall) { 1411 switch (TI.getTriple().getArch()) { 1412 default: 1413 // Some builtins don't require additional checking, so just consider these 1414 // acceptable. 1415 return false; 1416 case llvm::Triple::arm: 1417 case llvm::Triple::armeb: 1418 case llvm::Triple::thumb: 1419 case llvm::Triple::thumbeb: 1420 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1421 case llvm::Triple::aarch64: 1422 case llvm::Triple::aarch64_32: 1423 case llvm::Triple::aarch64_be: 1424 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1425 case llvm::Triple::bpfeb: 1426 case llvm::Triple::bpfel: 1427 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1428 case llvm::Triple::hexagon: 1429 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1430 case llvm::Triple::mips: 1431 case llvm::Triple::mipsel: 1432 case llvm::Triple::mips64: 1433 case llvm::Triple::mips64el: 1434 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1435 case llvm::Triple::systemz: 1436 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1437 case llvm::Triple::x86: 1438 case llvm::Triple::x86_64: 1439 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1440 case llvm::Triple::ppc: 1441 case llvm::Triple::ppcle: 1442 case llvm::Triple::ppc64: 1443 case llvm::Triple::ppc64le: 1444 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1445 case llvm::Triple::amdgcn: 1446 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1447 case llvm::Triple::riscv32: 1448 case llvm::Triple::riscv64: 1449 return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall); 1450 } 1451 } 1452 1453 ExprResult 1454 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1455 CallExpr *TheCall) { 1456 ExprResult TheCallResult(TheCall); 1457 1458 // Find out if any arguments are required to be integer constant expressions. 1459 unsigned ICEArguments = 0; 1460 ASTContext::GetBuiltinTypeError Error; 1461 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1462 if (Error != ASTContext::GE_None) 1463 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1464 1465 // If any arguments are required to be ICE's, check and diagnose. 1466 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1467 // Skip arguments not required to be ICE's. 1468 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1469 1470 llvm::APSInt Result; 1471 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1472 return true; 1473 ICEArguments &= ~(1 << ArgNo); 1474 } 1475 1476 switch (BuiltinID) { 1477 case Builtin::BI__builtin___CFStringMakeConstantString: 1478 assert(TheCall->getNumArgs() == 1 && 1479 "Wrong # arguments to builtin CFStringMakeConstantString"); 1480 if (CheckObjCString(TheCall->getArg(0))) 1481 return ExprError(); 1482 break; 1483 case Builtin::BI__builtin_ms_va_start: 1484 case Builtin::BI__builtin_stdarg_start: 1485 case Builtin::BI__builtin_va_start: 1486 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1487 return ExprError(); 1488 break; 1489 case Builtin::BI__va_start: { 1490 switch (Context.getTargetInfo().getTriple().getArch()) { 1491 case llvm::Triple::aarch64: 1492 case llvm::Triple::arm: 1493 case llvm::Triple::thumb: 1494 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1495 return ExprError(); 1496 break; 1497 default: 1498 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1499 return ExprError(); 1500 break; 1501 } 1502 break; 1503 } 1504 1505 // The acquire, release, and no fence variants are ARM and AArch64 only. 1506 case Builtin::BI_interlockedbittestandset_acq: 1507 case Builtin::BI_interlockedbittestandset_rel: 1508 case Builtin::BI_interlockedbittestandset_nf: 1509 case Builtin::BI_interlockedbittestandreset_acq: 1510 case Builtin::BI_interlockedbittestandreset_rel: 1511 case Builtin::BI_interlockedbittestandreset_nf: 1512 if (CheckBuiltinTargetSupport( 1513 *this, BuiltinID, TheCall, 1514 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1515 return ExprError(); 1516 break; 1517 1518 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1519 case Builtin::BI_bittest64: 1520 case Builtin::BI_bittestandcomplement64: 1521 case Builtin::BI_bittestandreset64: 1522 case Builtin::BI_bittestandset64: 1523 case Builtin::BI_interlockedbittestandreset64: 1524 case Builtin::BI_interlockedbittestandset64: 1525 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1526 {llvm::Triple::x86_64, llvm::Triple::arm, 1527 llvm::Triple::thumb, llvm::Triple::aarch64})) 1528 return ExprError(); 1529 break; 1530 1531 case Builtin::BI__builtin_isgreater: 1532 case Builtin::BI__builtin_isgreaterequal: 1533 case Builtin::BI__builtin_isless: 1534 case Builtin::BI__builtin_islessequal: 1535 case Builtin::BI__builtin_islessgreater: 1536 case Builtin::BI__builtin_isunordered: 1537 if (SemaBuiltinUnorderedCompare(TheCall)) 1538 return ExprError(); 1539 break; 1540 case Builtin::BI__builtin_fpclassify: 1541 if (SemaBuiltinFPClassification(TheCall, 6)) 1542 return ExprError(); 1543 break; 1544 case Builtin::BI__builtin_isfinite: 1545 case Builtin::BI__builtin_isinf: 1546 case Builtin::BI__builtin_isinf_sign: 1547 case Builtin::BI__builtin_isnan: 1548 case Builtin::BI__builtin_isnormal: 1549 case Builtin::BI__builtin_signbit: 1550 case Builtin::BI__builtin_signbitf: 1551 case Builtin::BI__builtin_signbitl: 1552 if (SemaBuiltinFPClassification(TheCall, 1)) 1553 return ExprError(); 1554 break; 1555 case Builtin::BI__builtin_shufflevector: 1556 return SemaBuiltinShuffleVector(TheCall); 1557 // TheCall will be freed by the smart pointer here, but that's fine, since 1558 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1559 case Builtin::BI__builtin_prefetch: 1560 if (SemaBuiltinPrefetch(TheCall)) 1561 return ExprError(); 1562 break; 1563 case Builtin::BI__builtin_alloca_with_align: 1564 if (SemaBuiltinAllocaWithAlign(TheCall)) 1565 return ExprError(); 1566 LLVM_FALLTHROUGH; 1567 case Builtin::BI__builtin_alloca: 1568 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1569 << TheCall->getDirectCallee(); 1570 break; 1571 case Builtin::BI__arithmetic_fence: 1572 if (SemaBuiltinArithmeticFence(TheCall)) 1573 return ExprError(); 1574 break; 1575 case Builtin::BI__assume: 1576 case Builtin::BI__builtin_assume: 1577 if (SemaBuiltinAssume(TheCall)) 1578 return ExprError(); 1579 break; 1580 case Builtin::BI__builtin_assume_aligned: 1581 if (SemaBuiltinAssumeAligned(TheCall)) 1582 return ExprError(); 1583 break; 1584 case Builtin::BI__builtin_dynamic_object_size: 1585 case Builtin::BI__builtin_object_size: 1586 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1587 return ExprError(); 1588 break; 1589 case Builtin::BI__builtin_longjmp: 1590 if (SemaBuiltinLongjmp(TheCall)) 1591 return ExprError(); 1592 break; 1593 case Builtin::BI__builtin_setjmp: 1594 if (SemaBuiltinSetjmp(TheCall)) 1595 return ExprError(); 1596 break; 1597 case Builtin::BI__builtin_classify_type: 1598 if (checkArgCount(*this, TheCall, 1)) return true; 1599 TheCall->setType(Context.IntTy); 1600 break; 1601 case Builtin::BI__builtin_complex: 1602 if (SemaBuiltinComplex(TheCall)) 1603 return ExprError(); 1604 break; 1605 case Builtin::BI__builtin_constant_p: { 1606 if (checkArgCount(*this, TheCall, 1)) return true; 1607 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1608 if (Arg.isInvalid()) return true; 1609 TheCall->setArg(0, Arg.get()); 1610 TheCall->setType(Context.IntTy); 1611 break; 1612 } 1613 case Builtin::BI__builtin_launder: 1614 return SemaBuiltinLaunder(*this, TheCall); 1615 case Builtin::BI__sync_fetch_and_add: 1616 case Builtin::BI__sync_fetch_and_add_1: 1617 case Builtin::BI__sync_fetch_and_add_2: 1618 case Builtin::BI__sync_fetch_and_add_4: 1619 case Builtin::BI__sync_fetch_and_add_8: 1620 case Builtin::BI__sync_fetch_and_add_16: 1621 case Builtin::BI__sync_fetch_and_sub: 1622 case Builtin::BI__sync_fetch_and_sub_1: 1623 case Builtin::BI__sync_fetch_and_sub_2: 1624 case Builtin::BI__sync_fetch_and_sub_4: 1625 case Builtin::BI__sync_fetch_and_sub_8: 1626 case Builtin::BI__sync_fetch_and_sub_16: 1627 case Builtin::BI__sync_fetch_and_or: 1628 case Builtin::BI__sync_fetch_and_or_1: 1629 case Builtin::BI__sync_fetch_and_or_2: 1630 case Builtin::BI__sync_fetch_and_or_4: 1631 case Builtin::BI__sync_fetch_and_or_8: 1632 case Builtin::BI__sync_fetch_and_or_16: 1633 case Builtin::BI__sync_fetch_and_and: 1634 case Builtin::BI__sync_fetch_and_and_1: 1635 case Builtin::BI__sync_fetch_and_and_2: 1636 case Builtin::BI__sync_fetch_and_and_4: 1637 case Builtin::BI__sync_fetch_and_and_8: 1638 case Builtin::BI__sync_fetch_and_and_16: 1639 case Builtin::BI__sync_fetch_and_xor: 1640 case Builtin::BI__sync_fetch_and_xor_1: 1641 case Builtin::BI__sync_fetch_and_xor_2: 1642 case Builtin::BI__sync_fetch_and_xor_4: 1643 case Builtin::BI__sync_fetch_and_xor_8: 1644 case Builtin::BI__sync_fetch_and_xor_16: 1645 case Builtin::BI__sync_fetch_and_nand: 1646 case Builtin::BI__sync_fetch_and_nand_1: 1647 case Builtin::BI__sync_fetch_and_nand_2: 1648 case Builtin::BI__sync_fetch_and_nand_4: 1649 case Builtin::BI__sync_fetch_and_nand_8: 1650 case Builtin::BI__sync_fetch_and_nand_16: 1651 case Builtin::BI__sync_add_and_fetch: 1652 case Builtin::BI__sync_add_and_fetch_1: 1653 case Builtin::BI__sync_add_and_fetch_2: 1654 case Builtin::BI__sync_add_and_fetch_4: 1655 case Builtin::BI__sync_add_and_fetch_8: 1656 case Builtin::BI__sync_add_and_fetch_16: 1657 case Builtin::BI__sync_sub_and_fetch: 1658 case Builtin::BI__sync_sub_and_fetch_1: 1659 case Builtin::BI__sync_sub_and_fetch_2: 1660 case Builtin::BI__sync_sub_and_fetch_4: 1661 case Builtin::BI__sync_sub_and_fetch_8: 1662 case Builtin::BI__sync_sub_and_fetch_16: 1663 case Builtin::BI__sync_and_and_fetch: 1664 case Builtin::BI__sync_and_and_fetch_1: 1665 case Builtin::BI__sync_and_and_fetch_2: 1666 case Builtin::BI__sync_and_and_fetch_4: 1667 case Builtin::BI__sync_and_and_fetch_8: 1668 case Builtin::BI__sync_and_and_fetch_16: 1669 case Builtin::BI__sync_or_and_fetch: 1670 case Builtin::BI__sync_or_and_fetch_1: 1671 case Builtin::BI__sync_or_and_fetch_2: 1672 case Builtin::BI__sync_or_and_fetch_4: 1673 case Builtin::BI__sync_or_and_fetch_8: 1674 case Builtin::BI__sync_or_and_fetch_16: 1675 case Builtin::BI__sync_xor_and_fetch: 1676 case Builtin::BI__sync_xor_and_fetch_1: 1677 case Builtin::BI__sync_xor_and_fetch_2: 1678 case Builtin::BI__sync_xor_and_fetch_4: 1679 case Builtin::BI__sync_xor_and_fetch_8: 1680 case Builtin::BI__sync_xor_and_fetch_16: 1681 case Builtin::BI__sync_nand_and_fetch: 1682 case Builtin::BI__sync_nand_and_fetch_1: 1683 case Builtin::BI__sync_nand_and_fetch_2: 1684 case Builtin::BI__sync_nand_and_fetch_4: 1685 case Builtin::BI__sync_nand_and_fetch_8: 1686 case Builtin::BI__sync_nand_and_fetch_16: 1687 case Builtin::BI__sync_val_compare_and_swap: 1688 case Builtin::BI__sync_val_compare_and_swap_1: 1689 case Builtin::BI__sync_val_compare_and_swap_2: 1690 case Builtin::BI__sync_val_compare_and_swap_4: 1691 case Builtin::BI__sync_val_compare_and_swap_8: 1692 case Builtin::BI__sync_val_compare_and_swap_16: 1693 case Builtin::BI__sync_bool_compare_and_swap: 1694 case Builtin::BI__sync_bool_compare_and_swap_1: 1695 case Builtin::BI__sync_bool_compare_and_swap_2: 1696 case Builtin::BI__sync_bool_compare_and_swap_4: 1697 case Builtin::BI__sync_bool_compare_and_swap_8: 1698 case Builtin::BI__sync_bool_compare_and_swap_16: 1699 case Builtin::BI__sync_lock_test_and_set: 1700 case Builtin::BI__sync_lock_test_and_set_1: 1701 case Builtin::BI__sync_lock_test_and_set_2: 1702 case Builtin::BI__sync_lock_test_and_set_4: 1703 case Builtin::BI__sync_lock_test_and_set_8: 1704 case Builtin::BI__sync_lock_test_and_set_16: 1705 case Builtin::BI__sync_lock_release: 1706 case Builtin::BI__sync_lock_release_1: 1707 case Builtin::BI__sync_lock_release_2: 1708 case Builtin::BI__sync_lock_release_4: 1709 case Builtin::BI__sync_lock_release_8: 1710 case Builtin::BI__sync_lock_release_16: 1711 case Builtin::BI__sync_swap: 1712 case Builtin::BI__sync_swap_1: 1713 case Builtin::BI__sync_swap_2: 1714 case Builtin::BI__sync_swap_4: 1715 case Builtin::BI__sync_swap_8: 1716 case Builtin::BI__sync_swap_16: 1717 return SemaBuiltinAtomicOverloaded(TheCallResult); 1718 case Builtin::BI__sync_synchronize: 1719 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1720 << TheCall->getCallee()->getSourceRange(); 1721 break; 1722 case Builtin::BI__builtin_nontemporal_load: 1723 case Builtin::BI__builtin_nontemporal_store: 1724 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1725 case Builtin::BI__builtin_memcpy_inline: { 1726 clang::Expr *SizeOp = TheCall->getArg(2); 1727 // We warn about copying to or from `nullptr` pointers when `size` is 1728 // greater than 0. When `size` is value dependent we cannot evaluate its 1729 // value so we bail out. 1730 if (SizeOp->isValueDependent()) 1731 break; 1732 if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) { 1733 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1734 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1735 } 1736 break; 1737 } 1738 #define BUILTIN(ID, TYPE, ATTRS) 1739 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1740 case Builtin::BI##ID: \ 1741 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1742 #include "clang/Basic/Builtins.def" 1743 case Builtin::BI__annotation: 1744 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1745 return ExprError(); 1746 break; 1747 case Builtin::BI__builtin_annotation: 1748 if (SemaBuiltinAnnotation(*this, TheCall)) 1749 return ExprError(); 1750 break; 1751 case Builtin::BI__builtin_addressof: 1752 if (SemaBuiltinAddressof(*this, TheCall)) 1753 return ExprError(); 1754 break; 1755 case Builtin::BI__builtin_is_aligned: 1756 case Builtin::BI__builtin_align_up: 1757 case Builtin::BI__builtin_align_down: 1758 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1759 return ExprError(); 1760 break; 1761 case Builtin::BI__builtin_add_overflow: 1762 case Builtin::BI__builtin_sub_overflow: 1763 case Builtin::BI__builtin_mul_overflow: 1764 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1765 return ExprError(); 1766 break; 1767 case Builtin::BI__builtin_operator_new: 1768 case Builtin::BI__builtin_operator_delete: { 1769 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1770 ExprResult Res = 1771 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1772 if (Res.isInvalid()) 1773 CorrectDelayedTyposInExpr(TheCallResult.get()); 1774 return Res; 1775 } 1776 case Builtin::BI__builtin_dump_struct: { 1777 // We first want to ensure we are called with 2 arguments 1778 if (checkArgCount(*this, TheCall, 2)) 1779 return ExprError(); 1780 // Ensure that the first argument is of type 'struct XX *' 1781 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1782 const QualType PtrArgType = PtrArg->getType(); 1783 if (!PtrArgType->isPointerType() || 1784 !PtrArgType->getPointeeType()->isRecordType()) { 1785 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1786 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1787 << "structure pointer"; 1788 return ExprError(); 1789 } 1790 1791 // Ensure that the second argument is of type 'FunctionType' 1792 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1793 const QualType FnPtrArgType = FnPtrArg->getType(); 1794 if (!FnPtrArgType->isPointerType()) { 1795 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1796 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1797 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1798 return ExprError(); 1799 } 1800 1801 const auto *FuncType = 1802 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1803 1804 if (!FuncType) { 1805 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1806 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1807 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1808 return ExprError(); 1809 } 1810 1811 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1812 if (!FT->getNumParams()) { 1813 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1814 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1815 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1816 return ExprError(); 1817 } 1818 QualType PT = FT->getParamType(0); 1819 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1820 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1821 !PT->getPointeeType().isConstQualified()) { 1822 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1823 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1824 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1825 return ExprError(); 1826 } 1827 } 1828 1829 TheCall->setType(Context.IntTy); 1830 break; 1831 } 1832 case Builtin::BI__builtin_expect_with_probability: { 1833 // We first want to ensure we are called with 3 arguments 1834 if (checkArgCount(*this, TheCall, 3)) 1835 return ExprError(); 1836 // then check probability is constant float in range [0.0, 1.0] 1837 const Expr *ProbArg = TheCall->getArg(2); 1838 SmallVector<PartialDiagnosticAt, 8> Notes; 1839 Expr::EvalResult Eval; 1840 Eval.Diag = &Notes; 1841 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) || 1842 !Eval.Val.isFloat()) { 1843 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1844 << ProbArg->getSourceRange(); 1845 for (const PartialDiagnosticAt &PDiag : Notes) 1846 Diag(PDiag.first, PDiag.second); 1847 return ExprError(); 1848 } 1849 llvm::APFloat Probability = Eval.Val.getFloat(); 1850 bool LoseInfo = false; 1851 Probability.convert(llvm::APFloat::IEEEdouble(), 1852 llvm::RoundingMode::Dynamic, &LoseInfo); 1853 if (!(Probability >= llvm::APFloat(0.0) && 1854 Probability <= llvm::APFloat(1.0))) { 1855 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1856 << ProbArg->getSourceRange(); 1857 return ExprError(); 1858 } 1859 break; 1860 } 1861 case Builtin::BI__builtin_preserve_access_index: 1862 if (SemaBuiltinPreserveAI(*this, TheCall)) 1863 return ExprError(); 1864 break; 1865 case Builtin::BI__builtin_call_with_static_chain: 1866 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1867 return ExprError(); 1868 break; 1869 case Builtin::BI__exception_code: 1870 case Builtin::BI_exception_code: 1871 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1872 diag::err_seh___except_block)) 1873 return ExprError(); 1874 break; 1875 case Builtin::BI__exception_info: 1876 case Builtin::BI_exception_info: 1877 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1878 diag::err_seh___except_filter)) 1879 return ExprError(); 1880 break; 1881 case Builtin::BI__GetExceptionInfo: 1882 if (checkArgCount(*this, TheCall, 1)) 1883 return ExprError(); 1884 1885 if (CheckCXXThrowOperand( 1886 TheCall->getBeginLoc(), 1887 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1888 TheCall)) 1889 return ExprError(); 1890 1891 TheCall->setType(Context.VoidPtrTy); 1892 break; 1893 // OpenCL v2.0, s6.13.16 - Pipe functions 1894 case Builtin::BIread_pipe: 1895 case Builtin::BIwrite_pipe: 1896 // Since those two functions are declared with var args, we need a semantic 1897 // check for the argument. 1898 if (SemaBuiltinRWPipe(*this, TheCall)) 1899 return ExprError(); 1900 break; 1901 case Builtin::BIreserve_read_pipe: 1902 case Builtin::BIreserve_write_pipe: 1903 case Builtin::BIwork_group_reserve_read_pipe: 1904 case Builtin::BIwork_group_reserve_write_pipe: 1905 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1906 return ExprError(); 1907 break; 1908 case Builtin::BIsub_group_reserve_read_pipe: 1909 case Builtin::BIsub_group_reserve_write_pipe: 1910 if (checkOpenCLSubgroupExt(*this, TheCall) || 1911 SemaBuiltinReserveRWPipe(*this, TheCall)) 1912 return ExprError(); 1913 break; 1914 case Builtin::BIcommit_read_pipe: 1915 case Builtin::BIcommit_write_pipe: 1916 case Builtin::BIwork_group_commit_read_pipe: 1917 case Builtin::BIwork_group_commit_write_pipe: 1918 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1919 return ExprError(); 1920 break; 1921 case Builtin::BIsub_group_commit_read_pipe: 1922 case Builtin::BIsub_group_commit_write_pipe: 1923 if (checkOpenCLSubgroupExt(*this, TheCall) || 1924 SemaBuiltinCommitRWPipe(*this, TheCall)) 1925 return ExprError(); 1926 break; 1927 case Builtin::BIget_pipe_num_packets: 1928 case Builtin::BIget_pipe_max_packets: 1929 if (SemaBuiltinPipePackets(*this, TheCall)) 1930 return ExprError(); 1931 break; 1932 case Builtin::BIto_global: 1933 case Builtin::BIto_local: 1934 case Builtin::BIto_private: 1935 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1936 return ExprError(); 1937 break; 1938 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1939 case Builtin::BIenqueue_kernel: 1940 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1941 return ExprError(); 1942 break; 1943 case Builtin::BIget_kernel_work_group_size: 1944 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1945 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1946 return ExprError(); 1947 break; 1948 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1949 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1950 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1951 return ExprError(); 1952 break; 1953 case Builtin::BI__builtin_os_log_format: 1954 Cleanup.setExprNeedsCleanups(true); 1955 LLVM_FALLTHROUGH; 1956 case Builtin::BI__builtin_os_log_format_buffer_size: 1957 if (SemaBuiltinOSLogFormat(TheCall)) 1958 return ExprError(); 1959 break; 1960 case Builtin::BI__builtin_frame_address: 1961 case Builtin::BI__builtin_return_address: { 1962 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1963 return ExprError(); 1964 1965 // -Wframe-address warning if non-zero passed to builtin 1966 // return/frame address. 1967 Expr::EvalResult Result; 1968 if (!TheCall->getArg(0)->isValueDependent() && 1969 TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1970 Result.Val.getInt() != 0) 1971 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1972 << ((BuiltinID == Builtin::BI__builtin_return_address) 1973 ? "__builtin_return_address" 1974 : "__builtin_frame_address") 1975 << TheCall->getSourceRange(); 1976 break; 1977 } 1978 1979 case Builtin::BI__builtin_matrix_transpose: 1980 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1981 1982 case Builtin::BI__builtin_matrix_column_major_load: 1983 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1984 1985 case Builtin::BI__builtin_matrix_column_major_store: 1986 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1987 1988 case Builtin::BI__builtin_get_device_side_mangled_name: { 1989 auto Check = [](CallExpr *TheCall) { 1990 if (TheCall->getNumArgs() != 1) 1991 return false; 1992 auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts()); 1993 if (!DRE) 1994 return false; 1995 auto *D = DRE->getDecl(); 1996 if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D)) 1997 return false; 1998 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() || 1999 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>(); 2000 }; 2001 if (!Check(TheCall)) { 2002 Diag(TheCall->getBeginLoc(), 2003 diag::err_hip_invalid_args_builtin_mangled_name); 2004 return ExprError(); 2005 } 2006 } 2007 } 2008 2009 // Since the target specific builtins for each arch overlap, only check those 2010 // of the arch we are compiling for. 2011 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 2012 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 2013 assert(Context.getAuxTargetInfo() && 2014 "Aux Target Builtin, but not an aux target?"); 2015 2016 if (CheckTSBuiltinFunctionCall( 2017 *Context.getAuxTargetInfo(), 2018 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 2019 return ExprError(); 2020 } else { 2021 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 2022 TheCall)) 2023 return ExprError(); 2024 } 2025 } 2026 2027 return TheCallResult; 2028 } 2029 2030 // Get the valid immediate range for the specified NEON type code. 2031 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 2032 NeonTypeFlags Type(t); 2033 int IsQuad = ForceQuad ? true : Type.isQuad(); 2034 switch (Type.getEltType()) { 2035 case NeonTypeFlags::Int8: 2036 case NeonTypeFlags::Poly8: 2037 return shift ? 7 : (8 << IsQuad) - 1; 2038 case NeonTypeFlags::Int16: 2039 case NeonTypeFlags::Poly16: 2040 return shift ? 15 : (4 << IsQuad) - 1; 2041 case NeonTypeFlags::Int32: 2042 return shift ? 31 : (2 << IsQuad) - 1; 2043 case NeonTypeFlags::Int64: 2044 case NeonTypeFlags::Poly64: 2045 return shift ? 63 : (1 << IsQuad) - 1; 2046 case NeonTypeFlags::Poly128: 2047 return shift ? 127 : (1 << IsQuad) - 1; 2048 case NeonTypeFlags::Float16: 2049 assert(!shift && "cannot shift float types!"); 2050 return (4 << IsQuad) - 1; 2051 case NeonTypeFlags::Float32: 2052 assert(!shift && "cannot shift float types!"); 2053 return (2 << IsQuad) - 1; 2054 case NeonTypeFlags::Float64: 2055 assert(!shift && "cannot shift float types!"); 2056 return (1 << IsQuad) - 1; 2057 case NeonTypeFlags::BFloat16: 2058 assert(!shift && "cannot shift float types!"); 2059 return (4 << IsQuad) - 1; 2060 } 2061 llvm_unreachable("Invalid NeonTypeFlag!"); 2062 } 2063 2064 /// getNeonEltType - Return the QualType corresponding to the elements of 2065 /// the vector type specified by the NeonTypeFlags. This is used to check 2066 /// the pointer arguments for Neon load/store intrinsics. 2067 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2068 bool IsPolyUnsigned, bool IsInt64Long) { 2069 switch (Flags.getEltType()) { 2070 case NeonTypeFlags::Int8: 2071 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2072 case NeonTypeFlags::Int16: 2073 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2074 case NeonTypeFlags::Int32: 2075 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2076 case NeonTypeFlags::Int64: 2077 if (IsInt64Long) 2078 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2079 else 2080 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2081 : Context.LongLongTy; 2082 case NeonTypeFlags::Poly8: 2083 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2084 case NeonTypeFlags::Poly16: 2085 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2086 case NeonTypeFlags::Poly64: 2087 if (IsInt64Long) 2088 return Context.UnsignedLongTy; 2089 else 2090 return Context.UnsignedLongLongTy; 2091 case NeonTypeFlags::Poly128: 2092 break; 2093 case NeonTypeFlags::Float16: 2094 return Context.HalfTy; 2095 case NeonTypeFlags::Float32: 2096 return Context.FloatTy; 2097 case NeonTypeFlags::Float64: 2098 return Context.DoubleTy; 2099 case NeonTypeFlags::BFloat16: 2100 return Context.BFloat16Ty; 2101 } 2102 llvm_unreachable("Invalid NeonTypeFlag!"); 2103 } 2104 2105 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2106 // Range check SVE intrinsics that take immediate values. 2107 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2108 2109 switch (BuiltinID) { 2110 default: 2111 return false; 2112 #define GET_SVE_IMMEDIATE_CHECK 2113 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2114 #undef GET_SVE_IMMEDIATE_CHECK 2115 } 2116 2117 // Perform all the immediate checks for this builtin call. 2118 bool HasError = false; 2119 for (auto &I : ImmChecks) { 2120 int ArgNum, CheckTy, ElementSizeInBits; 2121 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2122 2123 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2124 2125 // Function that checks whether the operand (ArgNum) is an immediate 2126 // that is one of the predefined values. 2127 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2128 int ErrDiag) -> bool { 2129 // We can't check the value of a dependent argument. 2130 Expr *Arg = TheCall->getArg(ArgNum); 2131 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2132 return false; 2133 2134 // Check constant-ness first. 2135 llvm::APSInt Imm; 2136 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2137 return true; 2138 2139 if (!CheckImm(Imm.getSExtValue())) 2140 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2141 return false; 2142 }; 2143 2144 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2145 case SVETypeFlags::ImmCheck0_31: 2146 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2147 HasError = true; 2148 break; 2149 case SVETypeFlags::ImmCheck0_13: 2150 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2151 HasError = true; 2152 break; 2153 case SVETypeFlags::ImmCheck1_16: 2154 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2155 HasError = true; 2156 break; 2157 case SVETypeFlags::ImmCheck0_7: 2158 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2159 HasError = true; 2160 break; 2161 case SVETypeFlags::ImmCheckExtract: 2162 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2163 (2048 / ElementSizeInBits) - 1)) 2164 HasError = true; 2165 break; 2166 case SVETypeFlags::ImmCheckShiftRight: 2167 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2168 HasError = true; 2169 break; 2170 case SVETypeFlags::ImmCheckShiftRightNarrow: 2171 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2172 ElementSizeInBits / 2)) 2173 HasError = true; 2174 break; 2175 case SVETypeFlags::ImmCheckShiftLeft: 2176 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2177 ElementSizeInBits - 1)) 2178 HasError = true; 2179 break; 2180 case SVETypeFlags::ImmCheckLaneIndex: 2181 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2182 (128 / (1 * ElementSizeInBits)) - 1)) 2183 HasError = true; 2184 break; 2185 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2186 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2187 (128 / (2 * ElementSizeInBits)) - 1)) 2188 HasError = true; 2189 break; 2190 case SVETypeFlags::ImmCheckLaneIndexDot: 2191 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2192 (128 / (4 * ElementSizeInBits)) - 1)) 2193 HasError = true; 2194 break; 2195 case SVETypeFlags::ImmCheckComplexRot90_270: 2196 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2197 diag::err_rotation_argument_to_cadd)) 2198 HasError = true; 2199 break; 2200 case SVETypeFlags::ImmCheckComplexRotAll90: 2201 if (CheckImmediateInSet( 2202 [](int64_t V) { 2203 return V == 0 || V == 90 || V == 180 || V == 270; 2204 }, 2205 diag::err_rotation_argument_to_cmla)) 2206 HasError = true; 2207 break; 2208 case SVETypeFlags::ImmCheck0_1: 2209 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2210 HasError = true; 2211 break; 2212 case SVETypeFlags::ImmCheck0_2: 2213 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2214 HasError = true; 2215 break; 2216 case SVETypeFlags::ImmCheck0_3: 2217 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2218 HasError = true; 2219 break; 2220 } 2221 } 2222 2223 return HasError; 2224 } 2225 2226 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2227 unsigned BuiltinID, CallExpr *TheCall) { 2228 llvm::APSInt Result; 2229 uint64_t mask = 0; 2230 unsigned TV = 0; 2231 int PtrArgNum = -1; 2232 bool HasConstPtr = false; 2233 switch (BuiltinID) { 2234 #define GET_NEON_OVERLOAD_CHECK 2235 #include "clang/Basic/arm_neon.inc" 2236 #include "clang/Basic/arm_fp16.inc" 2237 #undef GET_NEON_OVERLOAD_CHECK 2238 } 2239 2240 // For NEON intrinsics which are overloaded on vector element type, validate 2241 // the immediate which specifies which variant to emit. 2242 unsigned ImmArg = TheCall->getNumArgs()-1; 2243 if (mask) { 2244 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2245 return true; 2246 2247 TV = Result.getLimitedValue(64); 2248 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2249 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2250 << TheCall->getArg(ImmArg)->getSourceRange(); 2251 } 2252 2253 if (PtrArgNum >= 0) { 2254 // Check that pointer arguments have the specified type. 2255 Expr *Arg = TheCall->getArg(PtrArgNum); 2256 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2257 Arg = ICE->getSubExpr(); 2258 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2259 QualType RHSTy = RHS.get()->getType(); 2260 2261 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2262 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2263 Arch == llvm::Triple::aarch64_32 || 2264 Arch == llvm::Triple::aarch64_be; 2265 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2266 QualType EltTy = 2267 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2268 if (HasConstPtr) 2269 EltTy = EltTy.withConst(); 2270 QualType LHSTy = Context.getPointerType(EltTy); 2271 AssignConvertType ConvTy; 2272 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2273 if (RHS.isInvalid()) 2274 return true; 2275 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2276 RHS.get(), AA_Assigning)) 2277 return true; 2278 } 2279 2280 // For NEON intrinsics which take an immediate value as part of the 2281 // instruction, range check them here. 2282 unsigned i = 0, l = 0, u = 0; 2283 switch (BuiltinID) { 2284 default: 2285 return false; 2286 #define GET_NEON_IMMEDIATE_CHECK 2287 #include "clang/Basic/arm_neon.inc" 2288 #include "clang/Basic/arm_fp16.inc" 2289 #undef GET_NEON_IMMEDIATE_CHECK 2290 } 2291 2292 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2293 } 2294 2295 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2296 switch (BuiltinID) { 2297 default: 2298 return false; 2299 #include "clang/Basic/arm_mve_builtin_sema.inc" 2300 } 2301 } 2302 2303 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2304 CallExpr *TheCall) { 2305 bool Err = false; 2306 switch (BuiltinID) { 2307 default: 2308 return false; 2309 #include "clang/Basic/arm_cde_builtin_sema.inc" 2310 } 2311 2312 if (Err) 2313 return true; 2314 2315 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2316 } 2317 2318 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2319 const Expr *CoprocArg, bool WantCDE) { 2320 if (isConstantEvaluated()) 2321 return false; 2322 2323 // We can't check the value of a dependent argument. 2324 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2325 return false; 2326 2327 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2328 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2329 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2330 2331 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2332 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2333 2334 if (IsCDECoproc != WantCDE) 2335 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2336 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2337 2338 return false; 2339 } 2340 2341 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2342 unsigned MaxWidth) { 2343 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2344 BuiltinID == ARM::BI__builtin_arm_ldaex || 2345 BuiltinID == ARM::BI__builtin_arm_strex || 2346 BuiltinID == ARM::BI__builtin_arm_stlex || 2347 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2348 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2349 BuiltinID == AArch64::BI__builtin_arm_strex || 2350 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2351 "unexpected ARM builtin"); 2352 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2353 BuiltinID == ARM::BI__builtin_arm_ldaex || 2354 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2355 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2356 2357 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2358 2359 // Ensure that we have the proper number of arguments. 2360 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2361 return true; 2362 2363 // Inspect the pointer argument of the atomic builtin. This should always be 2364 // a pointer type, whose element is an integral scalar or pointer type. 2365 // Because it is a pointer type, we don't have to worry about any implicit 2366 // casts here. 2367 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2368 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2369 if (PointerArgRes.isInvalid()) 2370 return true; 2371 PointerArg = PointerArgRes.get(); 2372 2373 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2374 if (!pointerType) { 2375 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2376 << PointerArg->getType() << PointerArg->getSourceRange(); 2377 return true; 2378 } 2379 2380 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2381 // task is to insert the appropriate casts into the AST. First work out just 2382 // what the appropriate type is. 2383 QualType ValType = pointerType->getPointeeType(); 2384 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2385 if (IsLdrex) 2386 AddrType.addConst(); 2387 2388 // Issue a warning if the cast is dodgy. 2389 CastKind CastNeeded = CK_NoOp; 2390 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2391 CastNeeded = CK_BitCast; 2392 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2393 << PointerArg->getType() << Context.getPointerType(AddrType) 2394 << AA_Passing << PointerArg->getSourceRange(); 2395 } 2396 2397 // Finally, do the cast and replace the argument with the corrected version. 2398 AddrType = Context.getPointerType(AddrType); 2399 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2400 if (PointerArgRes.isInvalid()) 2401 return true; 2402 PointerArg = PointerArgRes.get(); 2403 2404 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2405 2406 // In general, we allow ints, floats and pointers to be loaded and stored. 2407 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2408 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2409 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2410 << PointerArg->getType() << PointerArg->getSourceRange(); 2411 return true; 2412 } 2413 2414 // But ARM doesn't have instructions to deal with 128-bit versions. 2415 if (Context.getTypeSize(ValType) > MaxWidth) { 2416 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2417 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2418 << PointerArg->getType() << PointerArg->getSourceRange(); 2419 return true; 2420 } 2421 2422 switch (ValType.getObjCLifetime()) { 2423 case Qualifiers::OCL_None: 2424 case Qualifiers::OCL_ExplicitNone: 2425 // okay 2426 break; 2427 2428 case Qualifiers::OCL_Weak: 2429 case Qualifiers::OCL_Strong: 2430 case Qualifiers::OCL_Autoreleasing: 2431 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2432 << ValType << PointerArg->getSourceRange(); 2433 return true; 2434 } 2435 2436 if (IsLdrex) { 2437 TheCall->setType(ValType); 2438 return false; 2439 } 2440 2441 // Initialize the argument to be stored. 2442 ExprResult ValArg = TheCall->getArg(0); 2443 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2444 Context, ValType, /*consume*/ false); 2445 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2446 if (ValArg.isInvalid()) 2447 return true; 2448 TheCall->setArg(0, ValArg.get()); 2449 2450 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2451 // but the custom checker bypasses all default analysis. 2452 TheCall->setType(Context.IntTy); 2453 return false; 2454 } 2455 2456 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2457 CallExpr *TheCall) { 2458 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2459 BuiltinID == ARM::BI__builtin_arm_ldaex || 2460 BuiltinID == ARM::BI__builtin_arm_strex || 2461 BuiltinID == ARM::BI__builtin_arm_stlex) { 2462 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2463 } 2464 2465 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2466 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2467 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2468 } 2469 2470 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2471 BuiltinID == ARM::BI__builtin_arm_wsr64) 2472 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2473 2474 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2475 BuiltinID == ARM::BI__builtin_arm_rsrp || 2476 BuiltinID == ARM::BI__builtin_arm_wsr || 2477 BuiltinID == ARM::BI__builtin_arm_wsrp) 2478 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2479 2480 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2481 return true; 2482 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2483 return true; 2484 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2485 return true; 2486 2487 // For intrinsics which take an immediate value as part of the instruction, 2488 // range check them here. 2489 // FIXME: VFP Intrinsics should error if VFP not present. 2490 switch (BuiltinID) { 2491 default: return false; 2492 case ARM::BI__builtin_arm_ssat: 2493 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2494 case ARM::BI__builtin_arm_usat: 2495 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2496 case ARM::BI__builtin_arm_ssat16: 2497 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2498 case ARM::BI__builtin_arm_usat16: 2499 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2500 case ARM::BI__builtin_arm_vcvtr_f: 2501 case ARM::BI__builtin_arm_vcvtr_d: 2502 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2503 case ARM::BI__builtin_arm_dmb: 2504 case ARM::BI__builtin_arm_dsb: 2505 case ARM::BI__builtin_arm_isb: 2506 case ARM::BI__builtin_arm_dbg: 2507 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2508 case ARM::BI__builtin_arm_cdp: 2509 case ARM::BI__builtin_arm_cdp2: 2510 case ARM::BI__builtin_arm_mcr: 2511 case ARM::BI__builtin_arm_mcr2: 2512 case ARM::BI__builtin_arm_mrc: 2513 case ARM::BI__builtin_arm_mrc2: 2514 case ARM::BI__builtin_arm_mcrr: 2515 case ARM::BI__builtin_arm_mcrr2: 2516 case ARM::BI__builtin_arm_mrrc: 2517 case ARM::BI__builtin_arm_mrrc2: 2518 case ARM::BI__builtin_arm_ldc: 2519 case ARM::BI__builtin_arm_ldcl: 2520 case ARM::BI__builtin_arm_ldc2: 2521 case ARM::BI__builtin_arm_ldc2l: 2522 case ARM::BI__builtin_arm_stc: 2523 case ARM::BI__builtin_arm_stcl: 2524 case ARM::BI__builtin_arm_stc2: 2525 case ARM::BI__builtin_arm_stc2l: 2526 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2527 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2528 /*WantCDE*/ false); 2529 } 2530 } 2531 2532 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2533 unsigned BuiltinID, 2534 CallExpr *TheCall) { 2535 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2536 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2537 BuiltinID == AArch64::BI__builtin_arm_strex || 2538 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2539 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2540 } 2541 2542 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2543 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2544 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2545 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2546 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2547 } 2548 2549 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2550 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2551 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2552 2553 // Memory Tagging Extensions (MTE) Intrinsics 2554 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2555 BuiltinID == AArch64::BI__builtin_arm_addg || 2556 BuiltinID == AArch64::BI__builtin_arm_gmi || 2557 BuiltinID == AArch64::BI__builtin_arm_ldg || 2558 BuiltinID == AArch64::BI__builtin_arm_stg || 2559 BuiltinID == AArch64::BI__builtin_arm_subp) { 2560 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2561 } 2562 2563 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2564 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2565 BuiltinID == AArch64::BI__builtin_arm_wsr || 2566 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2567 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2568 2569 // Only check the valid encoding range. Any constant in this range would be 2570 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2571 // an exception for incorrect registers. This matches MSVC behavior. 2572 if (BuiltinID == AArch64::BI_ReadStatusReg || 2573 BuiltinID == AArch64::BI_WriteStatusReg) 2574 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2575 2576 if (BuiltinID == AArch64::BI__getReg) 2577 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2578 2579 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2580 return true; 2581 2582 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2583 return true; 2584 2585 // For intrinsics which take an immediate value as part of the instruction, 2586 // range check them here. 2587 unsigned i = 0, l = 0, u = 0; 2588 switch (BuiltinID) { 2589 default: return false; 2590 case AArch64::BI__builtin_arm_dmb: 2591 case AArch64::BI__builtin_arm_dsb: 2592 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2593 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2594 } 2595 2596 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2597 } 2598 2599 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) { 2600 if (Arg->getType()->getAsPlaceholderType()) 2601 return false; 2602 2603 // The first argument needs to be a record field access. 2604 // If it is an array element access, we delay decision 2605 // to BPF backend to check whether the access is a 2606 // field access or not. 2607 return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || 2608 dyn_cast<MemberExpr>(Arg->IgnoreParens()) || 2609 dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens())); 2610 } 2611 2612 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S, 2613 QualType VectorTy, QualType EltTy) { 2614 QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType(); 2615 if (!Context.hasSameType(VectorEltTy, EltTy)) { 2616 S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types) 2617 << Call->getSourceRange() << VectorEltTy << EltTy; 2618 return false; 2619 } 2620 return true; 2621 } 2622 2623 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) { 2624 QualType ArgType = Arg->getType(); 2625 if (ArgType->getAsPlaceholderType()) 2626 return false; 2627 2628 // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type 2629 // format: 2630 // 1. __builtin_preserve_type_info(*(<type> *)0, flag); 2631 // 2. <type> var; 2632 // __builtin_preserve_type_info(var, flag); 2633 if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) && 2634 !dyn_cast<UnaryOperator>(Arg->IgnoreParens())) 2635 return false; 2636 2637 // Typedef type. 2638 if (ArgType->getAs<TypedefType>()) 2639 return true; 2640 2641 // Record type or Enum type. 2642 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2643 if (const auto *RT = Ty->getAs<RecordType>()) { 2644 if (!RT->getDecl()->getDeclName().isEmpty()) 2645 return true; 2646 } else if (const auto *ET = Ty->getAs<EnumType>()) { 2647 if (!ET->getDecl()->getDeclName().isEmpty()) 2648 return true; 2649 } 2650 2651 return false; 2652 } 2653 2654 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) { 2655 QualType ArgType = Arg->getType(); 2656 if (ArgType->getAsPlaceholderType()) 2657 return false; 2658 2659 // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type 2660 // format: 2661 // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, 2662 // flag); 2663 const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens()); 2664 if (!UO) 2665 return false; 2666 2667 const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr()); 2668 if (!CE) 2669 return false; 2670 if (CE->getCastKind() != CK_IntegralToPointer && 2671 CE->getCastKind() != CK_NullToPointer) 2672 return false; 2673 2674 // The integer must be from an EnumConstantDecl. 2675 const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr()); 2676 if (!DR) 2677 return false; 2678 2679 const EnumConstantDecl *Enumerator = 2680 dyn_cast<EnumConstantDecl>(DR->getDecl()); 2681 if (!Enumerator) 2682 return false; 2683 2684 // The type must be EnumType. 2685 const Type *Ty = ArgType->getUnqualifiedDesugaredType(); 2686 const auto *ET = Ty->getAs<EnumType>(); 2687 if (!ET) 2688 return false; 2689 2690 // The enum value must be supported. 2691 return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator); 2692 } 2693 2694 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2695 CallExpr *TheCall) { 2696 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2697 BuiltinID == BPF::BI__builtin_btf_type_id || 2698 BuiltinID == BPF::BI__builtin_preserve_type_info || 2699 BuiltinID == BPF::BI__builtin_preserve_enum_value) && 2700 "unexpected BPF builtin"); 2701 2702 if (checkArgCount(*this, TheCall, 2)) 2703 return true; 2704 2705 // The second argument needs to be a constant int 2706 Expr *Arg = TheCall->getArg(1); 2707 Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context); 2708 diag::kind kind; 2709 if (!Value) { 2710 if (BuiltinID == BPF::BI__builtin_preserve_field_info) 2711 kind = diag::err_preserve_field_info_not_const; 2712 else if (BuiltinID == BPF::BI__builtin_btf_type_id) 2713 kind = diag::err_btf_type_id_not_const; 2714 else if (BuiltinID == BPF::BI__builtin_preserve_type_info) 2715 kind = diag::err_preserve_type_info_not_const; 2716 else 2717 kind = diag::err_preserve_enum_value_not_const; 2718 Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange(); 2719 return true; 2720 } 2721 2722 // The first argument 2723 Arg = TheCall->getArg(0); 2724 bool InvalidArg = false; 2725 bool ReturnUnsignedInt = true; 2726 if (BuiltinID == BPF::BI__builtin_preserve_field_info) { 2727 if (!isValidBPFPreserveFieldInfoArg(Arg)) { 2728 InvalidArg = true; 2729 kind = diag::err_preserve_field_info_not_field; 2730 } 2731 } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { 2732 if (!isValidBPFPreserveTypeInfoArg(Arg)) { 2733 InvalidArg = true; 2734 kind = diag::err_preserve_type_info_invalid; 2735 } 2736 } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { 2737 if (!isValidBPFPreserveEnumValueArg(Arg)) { 2738 InvalidArg = true; 2739 kind = diag::err_preserve_enum_value_invalid; 2740 } 2741 ReturnUnsignedInt = false; 2742 } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2743 ReturnUnsignedInt = false; 2744 } 2745 2746 if (InvalidArg) { 2747 Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange(); 2748 return true; 2749 } 2750 2751 if (ReturnUnsignedInt) 2752 TheCall->setType(Context.UnsignedIntTy); 2753 else 2754 TheCall->setType(Context.UnsignedLongTy); 2755 return false; 2756 } 2757 2758 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2759 struct ArgInfo { 2760 uint8_t OpNum; 2761 bool IsSigned; 2762 uint8_t BitWidth; 2763 uint8_t Align; 2764 }; 2765 struct BuiltinInfo { 2766 unsigned BuiltinID; 2767 ArgInfo Infos[2]; 2768 }; 2769 2770 static BuiltinInfo Infos[] = { 2771 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2772 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2773 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2774 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2775 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2776 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2777 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2778 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2779 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2780 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2781 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2782 2783 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2794 2795 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2797 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2802 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2807 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2808 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2809 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2810 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2811 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2812 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2813 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2814 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2815 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2816 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2817 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2818 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2819 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2820 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2821 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2822 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2823 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2824 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2825 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2826 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2827 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2828 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2829 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2830 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2831 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2832 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2833 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2834 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2835 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2836 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2837 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2838 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2839 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2840 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2841 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2842 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2843 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2844 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2845 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2846 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2847 {{ 1, false, 6, 0 }} }, 2848 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2849 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2850 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2851 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2852 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2853 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2854 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2855 {{ 1, false, 5, 0 }} }, 2856 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2857 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2858 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2859 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2860 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2861 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2862 { 2, false, 5, 0 }} }, 2863 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2864 { 2, false, 6, 0 }} }, 2865 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2866 { 3, false, 5, 0 }} }, 2867 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2868 { 3, false, 6, 0 }} }, 2869 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2870 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2871 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2872 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2873 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2874 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2875 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2876 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2877 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2878 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2879 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2880 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2881 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2882 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2883 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2884 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2885 {{ 2, false, 4, 0 }, 2886 { 3, false, 5, 0 }} }, 2887 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2888 {{ 2, false, 4, 0 }, 2889 { 3, false, 5, 0 }} }, 2890 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2891 {{ 2, false, 4, 0 }, 2892 { 3, false, 5, 0 }} }, 2893 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2894 {{ 2, false, 4, 0 }, 2895 { 3, false, 5, 0 }} }, 2896 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2897 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2898 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2899 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2900 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2901 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2902 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2903 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2904 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2905 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2906 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2907 { 2, false, 5, 0 }} }, 2908 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2909 { 2, false, 6, 0 }} }, 2910 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2911 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2912 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2913 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2914 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2915 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2916 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2917 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2918 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2919 {{ 1, false, 4, 0 }} }, 2920 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2921 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2922 {{ 1, false, 4, 0 }} }, 2923 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2924 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2925 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2926 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2927 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2928 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2929 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2930 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2931 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2932 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2933 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2934 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2935 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2936 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2937 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2938 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2939 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2940 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2941 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2942 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2943 {{ 3, false, 1, 0 }} }, 2944 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2945 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2946 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2947 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2948 {{ 3, false, 1, 0 }} }, 2949 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2950 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2951 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2952 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2953 {{ 3, false, 1, 0 }} }, 2954 }; 2955 2956 // Use a dynamically initialized static to sort the table exactly once on 2957 // first run. 2958 static const bool SortOnce = 2959 (llvm::sort(Infos, 2960 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2961 return LHS.BuiltinID < RHS.BuiltinID; 2962 }), 2963 true); 2964 (void)SortOnce; 2965 2966 const BuiltinInfo *F = llvm::partition_point( 2967 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2968 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2969 return false; 2970 2971 bool Error = false; 2972 2973 for (const ArgInfo &A : F->Infos) { 2974 // Ignore empty ArgInfo elements. 2975 if (A.BitWidth == 0) 2976 continue; 2977 2978 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2979 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2980 if (!A.Align) { 2981 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2982 } else { 2983 unsigned M = 1 << A.Align; 2984 Min *= M; 2985 Max *= M; 2986 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2987 Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2988 } 2989 } 2990 return Error; 2991 } 2992 2993 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2994 CallExpr *TheCall) { 2995 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2996 } 2997 2998 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2999 unsigned BuiltinID, CallExpr *TheCall) { 3000 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 3001 CheckMipsBuiltinArgument(BuiltinID, TheCall); 3002 } 3003 3004 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 3005 CallExpr *TheCall) { 3006 3007 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 3008 BuiltinID <= Mips::BI__builtin_mips_lwx) { 3009 if (!TI.hasFeature("dsp")) 3010 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 3011 } 3012 3013 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 3014 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 3015 if (!TI.hasFeature("dspr2")) 3016 return Diag(TheCall->getBeginLoc(), 3017 diag::err_mips_builtin_requires_dspr2); 3018 } 3019 3020 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 3021 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 3022 if (!TI.hasFeature("msa")) 3023 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 3024 } 3025 3026 return false; 3027 } 3028 3029 // CheckMipsBuiltinArgument - Checks the constant value passed to the 3030 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 3031 // ordering for DSP is unspecified. MSA is ordered by the data format used 3032 // by the underlying instruction i.e., df/m, df/n and then by size. 3033 // 3034 // FIXME: The size tests here should instead be tablegen'd along with the 3035 // definitions from include/clang/Basic/BuiltinsMips.def. 3036 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 3037 // be too. 3038 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 3039 unsigned i = 0, l = 0, u = 0, m = 0; 3040 switch (BuiltinID) { 3041 default: return false; 3042 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 3043 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 3044 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 3045 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 3046 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 3047 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 3048 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 3049 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 3050 // df/m field. 3051 // These intrinsics take an unsigned 3 bit immediate. 3052 case Mips::BI__builtin_msa_bclri_b: 3053 case Mips::BI__builtin_msa_bnegi_b: 3054 case Mips::BI__builtin_msa_bseti_b: 3055 case Mips::BI__builtin_msa_sat_s_b: 3056 case Mips::BI__builtin_msa_sat_u_b: 3057 case Mips::BI__builtin_msa_slli_b: 3058 case Mips::BI__builtin_msa_srai_b: 3059 case Mips::BI__builtin_msa_srari_b: 3060 case Mips::BI__builtin_msa_srli_b: 3061 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 3062 case Mips::BI__builtin_msa_binsli_b: 3063 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 3064 // These intrinsics take an unsigned 4 bit immediate. 3065 case Mips::BI__builtin_msa_bclri_h: 3066 case Mips::BI__builtin_msa_bnegi_h: 3067 case Mips::BI__builtin_msa_bseti_h: 3068 case Mips::BI__builtin_msa_sat_s_h: 3069 case Mips::BI__builtin_msa_sat_u_h: 3070 case Mips::BI__builtin_msa_slli_h: 3071 case Mips::BI__builtin_msa_srai_h: 3072 case Mips::BI__builtin_msa_srari_h: 3073 case Mips::BI__builtin_msa_srli_h: 3074 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 3075 case Mips::BI__builtin_msa_binsli_h: 3076 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 3077 // These intrinsics take an unsigned 5 bit immediate. 3078 // The first block of intrinsics actually have an unsigned 5 bit field, 3079 // not a df/n field. 3080 case Mips::BI__builtin_msa_cfcmsa: 3081 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 3082 case Mips::BI__builtin_msa_clei_u_b: 3083 case Mips::BI__builtin_msa_clei_u_h: 3084 case Mips::BI__builtin_msa_clei_u_w: 3085 case Mips::BI__builtin_msa_clei_u_d: 3086 case Mips::BI__builtin_msa_clti_u_b: 3087 case Mips::BI__builtin_msa_clti_u_h: 3088 case Mips::BI__builtin_msa_clti_u_w: 3089 case Mips::BI__builtin_msa_clti_u_d: 3090 case Mips::BI__builtin_msa_maxi_u_b: 3091 case Mips::BI__builtin_msa_maxi_u_h: 3092 case Mips::BI__builtin_msa_maxi_u_w: 3093 case Mips::BI__builtin_msa_maxi_u_d: 3094 case Mips::BI__builtin_msa_mini_u_b: 3095 case Mips::BI__builtin_msa_mini_u_h: 3096 case Mips::BI__builtin_msa_mini_u_w: 3097 case Mips::BI__builtin_msa_mini_u_d: 3098 case Mips::BI__builtin_msa_addvi_b: 3099 case Mips::BI__builtin_msa_addvi_h: 3100 case Mips::BI__builtin_msa_addvi_w: 3101 case Mips::BI__builtin_msa_addvi_d: 3102 case Mips::BI__builtin_msa_bclri_w: 3103 case Mips::BI__builtin_msa_bnegi_w: 3104 case Mips::BI__builtin_msa_bseti_w: 3105 case Mips::BI__builtin_msa_sat_s_w: 3106 case Mips::BI__builtin_msa_sat_u_w: 3107 case Mips::BI__builtin_msa_slli_w: 3108 case Mips::BI__builtin_msa_srai_w: 3109 case Mips::BI__builtin_msa_srari_w: 3110 case Mips::BI__builtin_msa_srli_w: 3111 case Mips::BI__builtin_msa_srlri_w: 3112 case Mips::BI__builtin_msa_subvi_b: 3113 case Mips::BI__builtin_msa_subvi_h: 3114 case Mips::BI__builtin_msa_subvi_w: 3115 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 3116 case Mips::BI__builtin_msa_binsli_w: 3117 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 3118 // These intrinsics take an unsigned 6 bit immediate. 3119 case Mips::BI__builtin_msa_bclri_d: 3120 case Mips::BI__builtin_msa_bnegi_d: 3121 case Mips::BI__builtin_msa_bseti_d: 3122 case Mips::BI__builtin_msa_sat_s_d: 3123 case Mips::BI__builtin_msa_sat_u_d: 3124 case Mips::BI__builtin_msa_slli_d: 3125 case Mips::BI__builtin_msa_srai_d: 3126 case Mips::BI__builtin_msa_srari_d: 3127 case Mips::BI__builtin_msa_srli_d: 3128 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 3129 case Mips::BI__builtin_msa_binsli_d: 3130 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 3131 // These intrinsics take a signed 5 bit immediate. 3132 case Mips::BI__builtin_msa_ceqi_b: 3133 case Mips::BI__builtin_msa_ceqi_h: 3134 case Mips::BI__builtin_msa_ceqi_w: 3135 case Mips::BI__builtin_msa_ceqi_d: 3136 case Mips::BI__builtin_msa_clti_s_b: 3137 case Mips::BI__builtin_msa_clti_s_h: 3138 case Mips::BI__builtin_msa_clti_s_w: 3139 case Mips::BI__builtin_msa_clti_s_d: 3140 case Mips::BI__builtin_msa_clei_s_b: 3141 case Mips::BI__builtin_msa_clei_s_h: 3142 case Mips::BI__builtin_msa_clei_s_w: 3143 case Mips::BI__builtin_msa_clei_s_d: 3144 case Mips::BI__builtin_msa_maxi_s_b: 3145 case Mips::BI__builtin_msa_maxi_s_h: 3146 case Mips::BI__builtin_msa_maxi_s_w: 3147 case Mips::BI__builtin_msa_maxi_s_d: 3148 case Mips::BI__builtin_msa_mini_s_b: 3149 case Mips::BI__builtin_msa_mini_s_h: 3150 case Mips::BI__builtin_msa_mini_s_w: 3151 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3152 // These intrinsics take an unsigned 8 bit immediate. 3153 case Mips::BI__builtin_msa_andi_b: 3154 case Mips::BI__builtin_msa_nori_b: 3155 case Mips::BI__builtin_msa_ori_b: 3156 case Mips::BI__builtin_msa_shf_b: 3157 case Mips::BI__builtin_msa_shf_h: 3158 case Mips::BI__builtin_msa_shf_w: 3159 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3160 case Mips::BI__builtin_msa_bseli_b: 3161 case Mips::BI__builtin_msa_bmnzi_b: 3162 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3163 // df/n format 3164 // These intrinsics take an unsigned 4 bit immediate. 3165 case Mips::BI__builtin_msa_copy_s_b: 3166 case Mips::BI__builtin_msa_copy_u_b: 3167 case Mips::BI__builtin_msa_insve_b: 3168 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3169 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3170 // These intrinsics take an unsigned 3 bit immediate. 3171 case Mips::BI__builtin_msa_copy_s_h: 3172 case Mips::BI__builtin_msa_copy_u_h: 3173 case Mips::BI__builtin_msa_insve_h: 3174 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3175 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3176 // These intrinsics take an unsigned 2 bit immediate. 3177 case Mips::BI__builtin_msa_copy_s_w: 3178 case Mips::BI__builtin_msa_copy_u_w: 3179 case Mips::BI__builtin_msa_insve_w: 3180 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3181 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3182 // These intrinsics take an unsigned 1 bit immediate. 3183 case Mips::BI__builtin_msa_copy_s_d: 3184 case Mips::BI__builtin_msa_copy_u_d: 3185 case Mips::BI__builtin_msa_insve_d: 3186 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3187 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3188 // Memory offsets and immediate loads. 3189 // These intrinsics take a signed 10 bit immediate. 3190 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3191 case Mips::BI__builtin_msa_ldi_h: 3192 case Mips::BI__builtin_msa_ldi_w: 3193 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3194 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3195 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3196 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3197 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3198 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3199 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3200 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3201 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3202 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3203 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3204 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3205 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3206 } 3207 3208 if (!m) 3209 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3210 3211 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3212 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3213 } 3214 3215 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str, 3216 /// advancing the pointer over the consumed characters. The decoded type is 3217 /// returned. If the decoded type represents a constant integer with a 3218 /// constraint on its value then Mask is set to that value. The type descriptors 3219 /// used in Str are specific to PPC MMA builtins and are documented in the file 3220 /// defining the PPC builtins. 3221 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str, 3222 unsigned &Mask) { 3223 bool RequireICE = false; 3224 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 3225 switch (*Str++) { 3226 case 'V': 3227 return Context.getVectorType(Context.UnsignedCharTy, 16, 3228 VectorType::VectorKind::AltiVecVector); 3229 case 'i': { 3230 char *End; 3231 unsigned size = strtoul(Str, &End, 10); 3232 assert(End != Str && "Missing constant parameter constraint"); 3233 Str = End; 3234 Mask = size; 3235 return Context.IntTy; 3236 } 3237 case 'W': { 3238 char *End; 3239 unsigned size = strtoul(Str, &End, 10); 3240 assert(End != Str && "Missing PowerPC MMA type size"); 3241 Str = End; 3242 QualType Type; 3243 switch (size) { 3244 #define PPC_VECTOR_TYPE(typeName, Id, size) \ 3245 case size: Type = Context.Id##Ty; break; 3246 #include "clang/Basic/PPCTypes.def" 3247 default: llvm_unreachable("Invalid PowerPC MMA vector type"); 3248 } 3249 bool CheckVectorArgs = false; 3250 while (!CheckVectorArgs) { 3251 switch (*Str++) { 3252 case '*': 3253 Type = Context.getPointerType(Type); 3254 break; 3255 case 'C': 3256 Type = Type.withConst(); 3257 break; 3258 default: 3259 CheckVectorArgs = true; 3260 --Str; 3261 break; 3262 } 3263 } 3264 return Type; 3265 } 3266 default: 3267 return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true); 3268 } 3269 } 3270 3271 static bool isPPC_64Builtin(unsigned BuiltinID) { 3272 // These builtins only work on PPC 64bit targets. 3273 switch (BuiltinID) { 3274 case PPC::BI__builtin_divde: 3275 case PPC::BI__builtin_divdeu: 3276 case PPC::BI__builtin_bpermd: 3277 case PPC::BI__builtin_ppc_ldarx: 3278 case PPC::BI__builtin_ppc_stdcx: 3279 case PPC::BI__builtin_ppc_tdw: 3280 case PPC::BI__builtin_ppc_trapd: 3281 case PPC::BI__builtin_ppc_cmpeqb: 3282 case PPC::BI__builtin_ppc_setb: 3283 case PPC::BI__builtin_ppc_mulhd: 3284 case PPC::BI__builtin_ppc_mulhdu: 3285 case PPC::BI__builtin_ppc_maddhd: 3286 case PPC::BI__builtin_ppc_maddhdu: 3287 case PPC::BI__builtin_ppc_maddld: 3288 case PPC::BI__builtin_ppc_load8r: 3289 case PPC::BI__builtin_ppc_store8r: 3290 case PPC::BI__builtin_ppc_insert_exp: 3291 case PPC::BI__builtin_ppc_extract_sig: 3292 case PPC::BI__builtin_ppc_addex: 3293 case PPC::BI__builtin_darn: 3294 case PPC::BI__builtin_darn_raw: 3295 case PPC::BI__builtin_ppc_compare_and_swaplp: 3296 case PPC::BI__builtin_ppc_fetch_and_addlp: 3297 case PPC::BI__builtin_ppc_fetch_and_andlp: 3298 case PPC::BI__builtin_ppc_fetch_and_orlp: 3299 case PPC::BI__builtin_ppc_fetch_and_swaplp: 3300 return true; 3301 } 3302 return false; 3303 } 3304 3305 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall, 3306 StringRef FeatureToCheck, unsigned DiagID, 3307 StringRef DiagArg = "") { 3308 if (S.Context.getTargetInfo().hasFeature(FeatureToCheck)) 3309 return false; 3310 3311 if (DiagArg.empty()) 3312 S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange(); 3313 else 3314 S.Diag(TheCall->getBeginLoc(), DiagID) 3315 << DiagArg << TheCall->getSourceRange(); 3316 3317 return true; 3318 } 3319 3320 /// Returns true if the argument consists of one contiguous run of 1s with any 3321 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so 3322 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not, 3323 /// since all 1s are not contiguous. 3324 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) { 3325 llvm::APSInt Result; 3326 // We can't check the value of a dependent argument. 3327 Expr *Arg = TheCall->getArg(ArgNum); 3328 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3329 return false; 3330 3331 // Check constant-ness first. 3332 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3333 return true; 3334 3335 // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s. 3336 if (Result.isShiftedMask() || (~Result).isShiftedMask()) 3337 return false; 3338 3339 return Diag(TheCall->getBeginLoc(), 3340 diag::err_argument_not_contiguous_bit_field) 3341 << ArgNum << Arg->getSourceRange(); 3342 } 3343 3344 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3345 CallExpr *TheCall) { 3346 unsigned i = 0, l = 0, u = 0; 3347 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3348 llvm::APSInt Result; 3349 3350 if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit) 3351 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3352 << TheCall->getSourceRange(); 3353 3354 switch (BuiltinID) { 3355 default: return false; 3356 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3357 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3358 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3359 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3360 case PPC::BI__builtin_altivec_dss: 3361 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3362 case PPC::BI__builtin_tbegin: 3363 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3364 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3365 case PPC::BI__builtin_tabortwc: 3366 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3367 case PPC::BI__builtin_tabortwci: 3368 case PPC::BI__builtin_tabortdci: 3369 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3370 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3371 case PPC::BI__builtin_altivec_dst: 3372 case PPC::BI__builtin_altivec_dstt: 3373 case PPC::BI__builtin_altivec_dstst: 3374 case PPC::BI__builtin_altivec_dststt: 3375 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3376 case PPC::BI__builtin_vsx_xxpermdi: 3377 case PPC::BI__builtin_vsx_xxsldwi: 3378 return SemaBuiltinVSX(TheCall); 3379 case PPC::BI__builtin_divwe: 3380 case PPC::BI__builtin_divweu: 3381 case PPC::BI__builtin_divde: 3382 case PPC::BI__builtin_divdeu: 3383 return SemaFeatureCheck(*this, TheCall, "extdiv", 3384 diag::err_ppc_builtin_only_on_arch, "7"); 3385 case PPC::BI__builtin_bpermd: 3386 return SemaFeatureCheck(*this, TheCall, "bpermd", 3387 diag::err_ppc_builtin_only_on_arch, "7"); 3388 case PPC::BI__builtin_unpack_vector_int128: 3389 return SemaFeatureCheck(*this, TheCall, "vsx", 3390 diag::err_ppc_builtin_only_on_arch, "7") || 3391 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3392 case PPC::BI__builtin_pack_vector_int128: 3393 return SemaFeatureCheck(*this, TheCall, "vsx", 3394 diag::err_ppc_builtin_only_on_arch, "7"); 3395 case PPC::BI__builtin_altivec_vgnb: 3396 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3397 case PPC::BI__builtin_altivec_vec_replace_elt: 3398 case PPC::BI__builtin_altivec_vec_replace_unaligned: { 3399 QualType VecTy = TheCall->getArg(0)->getType(); 3400 QualType EltTy = TheCall->getArg(1)->getType(); 3401 unsigned Width = Context.getIntWidth(EltTy); 3402 return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) || 3403 !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy); 3404 } 3405 case PPC::BI__builtin_vsx_xxeval: 3406 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3407 case PPC::BI__builtin_altivec_vsldbi: 3408 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3409 case PPC::BI__builtin_altivec_vsrdbi: 3410 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3411 case PPC::BI__builtin_vsx_xxpermx: 3412 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3413 case PPC::BI__builtin_ppc_tw: 3414 case PPC::BI__builtin_ppc_tdw: 3415 return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31); 3416 case PPC::BI__builtin_ppc_cmpeqb: 3417 case PPC::BI__builtin_ppc_setb: 3418 case PPC::BI__builtin_ppc_maddhd: 3419 case PPC::BI__builtin_ppc_maddhdu: 3420 case PPC::BI__builtin_ppc_maddld: 3421 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3422 diag::err_ppc_builtin_only_on_arch, "9"); 3423 case PPC::BI__builtin_ppc_cmprb: 3424 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3425 diag::err_ppc_builtin_only_on_arch, "9") || 3426 SemaBuiltinConstantArgRange(TheCall, 0, 0, 1); 3427 // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must 3428 // be a constant that represents a contiguous bit field. 3429 case PPC::BI__builtin_ppc_rlwnm: 3430 return SemaValueIsRunOfOnes(TheCall, 2); 3431 case PPC::BI__builtin_ppc_rlwimi: 3432 case PPC::BI__builtin_ppc_rldimi: 3433 return SemaBuiltinConstantArg(TheCall, 2, Result) || 3434 SemaValueIsRunOfOnes(TheCall, 3); 3435 case PPC::BI__builtin_ppc_extract_exp: 3436 case PPC::BI__builtin_ppc_extract_sig: 3437 case PPC::BI__builtin_ppc_insert_exp: 3438 return SemaFeatureCheck(*this, TheCall, "power9-vector", 3439 diag::err_ppc_builtin_only_on_arch, "9"); 3440 case PPC::BI__builtin_ppc_addex: { 3441 if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3442 diag::err_ppc_builtin_only_on_arch, "9") || 3443 SemaBuiltinConstantArgRange(TheCall, 2, 0, 3)) 3444 return true; 3445 // Output warning for reserved values 1 to 3. 3446 int ArgValue = 3447 TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue(); 3448 if (ArgValue != 0) 3449 Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour) 3450 << ArgValue; 3451 return false; 3452 } 3453 case PPC::BI__builtin_ppc_mtfsb0: 3454 case PPC::BI__builtin_ppc_mtfsb1: 3455 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 3456 case PPC::BI__builtin_ppc_mtfsf: 3457 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255); 3458 case PPC::BI__builtin_ppc_mtfsfi: 3459 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) || 3460 SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 3461 case PPC::BI__builtin_ppc_alignx: 3462 return SemaBuiltinConstantArgPower2(TheCall, 0); 3463 case PPC::BI__builtin_ppc_rdlam: 3464 return SemaValueIsRunOfOnes(TheCall, 2); 3465 case PPC::BI__builtin_ppc_icbt: 3466 case PPC::BI__builtin_ppc_sthcx: 3467 case PPC::BI__builtin_ppc_stbcx: 3468 case PPC::BI__builtin_ppc_lharx: 3469 case PPC::BI__builtin_ppc_lbarx: 3470 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3471 diag::err_ppc_builtin_only_on_arch, "8"); 3472 case PPC::BI__builtin_vsx_ldrmb: 3473 case PPC::BI__builtin_vsx_strmb: 3474 return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions", 3475 diag::err_ppc_builtin_only_on_arch, "8") || 3476 SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 3477 case PPC::BI__builtin_altivec_vcntmbb: 3478 case PPC::BI__builtin_altivec_vcntmbh: 3479 case PPC::BI__builtin_altivec_vcntmbw: 3480 case PPC::BI__builtin_altivec_vcntmbd: 3481 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3482 case PPC::BI__builtin_darn: 3483 case PPC::BI__builtin_darn_raw: 3484 case PPC::BI__builtin_darn_32: 3485 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3486 diag::err_ppc_builtin_only_on_arch, "9"); 3487 case PPC::BI__builtin_vsx_xxgenpcvbm: 3488 case PPC::BI__builtin_vsx_xxgenpcvhm: 3489 case PPC::BI__builtin_vsx_xxgenpcvwm: 3490 case PPC::BI__builtin_vsx_xxgenpcvdm: 3491 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3492 case PPC::BI__builtin_ppc_compare_exp_uo: 3493 case PPC::BI__builtin_ppc_compare_exp_lt: 3494 case PPC::BI__builtin_ppc_compare_exp_gt: 3495 case PPC::BI__builtin_ppc_compare_exp_eq: 3496 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3497 diag::err_ppc_builtin_only_on_arch, "9") || 3498 SemaFeatureCheck(*this, TheCall, "vsx", 3499 diag::err_ppc_builtin_requires_vsx); 3500 case PPC::BI__builtin_ppc_test_data_class: { 3501 // Check if the first argument of the __builtin_ppc_test_data_class call is 3502 // valid. The argument must be either a 'float' or a 'double'. 3503 QualType ArgType = TheCall->getArg(0)->getType(); 3504 if (ArgType != QualType(Context.FloatTy) && 3505 ArgType != QualType(Context.DoubleTy)) 3506 return Diag(TheCall->getBeginLoc(), 3507 diag::err_ppc_invalid_test_data_class_type); 3508 return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions", 3509 diag::err_ppc_builtin_only_on_arch, "9") || 3510 SemaFeatureCheck(*this, TheCall, "vsx", 3511 diag::err_ppc_builtin_requires_vsx) || 3512 SemaBuiltinConstantArgRange(TheCall, 1, 0, 127); 3513 } 3514 case PPC::BI__builtin_ppc_load8r: 3515 case PPC::BI__builtin_ppc_store8r: 3516 return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions", 3517 diag::err_ppc_builtin_only_on_arch, "7"); 3518 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \ 3519 case PPC::BI__builtin_##Name: \ 3520 return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types); 3521 #include "clang/Basic/BuiltinsPPC.def" 3522 } 3523 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3524 } 3525 3526 // Check if the given type is a non-pointer PPC MMA type. This function is used 3527 // in Sema to prevent invalid uses of restricted PPC MMA types. 3528 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) { 3529 if (Type->isPointerType() || Type->isArrayType()) 3530 return false; 3531 3532 QualType CoreType = Type.getCanonicalType().getUnqualifiedType(); 3533 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty 3534 if (false 3535 #include "clang/Basic/PPCTypes.def" 3536 ) { 3537 Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type); 3538 return true; 3539 } 3540 return false; 3541 } 3542 3543 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3544 CallExpr *TheCall) { 3545 // position of memory order and scope arguments in the builtin 3546 unsigned OrderIndex, ScopeIndex; 3547 switch (BuiltinID) { 3548 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3549 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3550 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3551 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3552 OrderIndex = 2; 3553 ScopeIndex = 3; 3554 break; 3555 case AMDGPU::BI__builtin_amdgcn_fence: 3556 OrderIndex = 0; 3557 ScopeIndex = 1; 3558 break; 3559 default: 3560 return false; 3561 } 3562 3563 ExprResult Arg = TheCall->getArg(OrderIndex); 3564 auto ArgExpr = Arg.get(); 3565 Expr::EvalResult ArgResult; 3566 3567 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3568 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3569 << ArgExpr->getType(); 3570 auto Ord = ArgResult.Val.getInt().getZExtValue(); 3571 3572 // Check validity of memory ordering as per C11 / C++11's memody model. 3573 // Only fence needs check. Atomic dec/inc allow all memory orders. 3574 if (!llvm::isValidAtomicOrderingCABI(Ord)) 3575 return Diag(ArgExpr->getBeginLoc(), 3576 diag::warn_atomic_op_has_invalid_memory_order) 3577 << ArgExpr->getSourceRange(); 3578 switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) { 3579 case llvm::AtomicOrderingCABI::relaxed: 3580 case llvm::AtomicOrderingCABI::consume: 3581 if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence) 3582 return Diag(ArgExpr->getBeginLoc(), 3583 diag::warn_atomic_op_has_invalid_memory_order) 3584 << ArgExpr->getSourceRange(); 3585 break; 3586 case llvm::AtomicOrderingCABI::acquire: 3587 case llvm::AtomicOrderingCABI::release: 3588 case llvm::AtomicOrderingCABI::acq_rel: 3589 case llvm::AtomicOrderingCABI::seq_cst: 3590 break; 3591 } 3592 3593 Arg = TheCall->getArg(ScopeIndex); 3594 ArgExpr = Arg.get(); 3595 Expr::EvalResult ArgResult1; 3596 // Check that sync scope is a constant literal 3597 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context)) 3598 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3599 << ArgExpr->getType(); 3600 3601 return false; 3602 } 3603 3604 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) { 3605 llvm::APSInt Result; 3606 3607 // We can't check the value of a dependent argument. 3608 Expr *Arg = TheCall->getArg(ArgNum); 3609 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3610 return false; 3611 3612 // Check constant-ness first. 3613 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3614 return true; 3615 3616 int64_t Val = Result.getSExtValue(); 3617 if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7)) 3618 return false; 3619 3620 return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul) 3621 << Arg->getSourceRange(); 3622 } 3623 3624 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, 3625 unsigned BuiltinID, 3626 CallExpr *TheCall) { 3627 // CodeGenFunction can also detect this, but this gives a better error 3628 // message. 3629 bool FeatureMissing = false; 3630 SmallVector<StringRef> ReqFeatures; 3631 StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID); 3632 Features.split(ReqFeatures, ','); 3633 3634 // Check if each required feature is included 3635 for (StringRef F : ReqFeatures) { 3636 if (TI.hasFeature(F)) 3637 continue; 3638 3639 // If the feature is 64bit, alter the string so it will print better in 3640 // the diagnostic. 3641 if (F == "64bit") 3642 F = "RV64"; 3643 3644 // Convert features like "zbr" and "experimental-zbr" to "Zbr". 3645 F.consume_front("experimental-"); 3646 std::string FeatureStr = F.str(); 3647 FeatureStr[0] = std::toupper(FeatureStr[0]); 3648 3649 // Error message 3650 FeatureMissing = true; 3651 Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension) 3652 << TheCall->getSourceRange() << StringRef(FeatureStr); 3653 } 3654 3655 if (FeatureMissing) 3656 return true; 3657 3658 switch (BuiltinID) { 3659 case RISCVVector::BI__builtin_rvv_vsetvli: 3660 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) || 3661 CheckRISCVLMUL(TheCall, 2); 3662 case RISCVVector::BI__builtin_rvv_vsetvlimax: 3663 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) || 3664 CheckRISCVLMUL(TheCall, 1); 3665 case RISCVVector::BI__builtin_rvv_vget_v_i8m2_i8m1: 3666 case RISCVVector::BI__builtin_rvv_vget_v_i16m2_i16m1: 3667 case RISCVVector::BI__builtin_rvv_vget_v_i32m2_i32m1: 3668 case RISCVVector::BI__builtin_rvv_vget_v_i64m2_i64m1: 3669 case RISCVVector::BI__builtin_rvv_vget_v_f32m2_f32m1: 3670 case RISCVVector::BI__builtin_rvv_vget_v_f64m2_f64m1: 3671 case RISCVVector::BI__builtin_rvv_vget_v_u8m2_u8m1: 3672 case RISCVVector::BI__builtin_rvv_vget_v_u16m2_u16m1: 3673 case RISCVVector::BI__builtin_rvv_vget_v_u32m2_u32m1: 3674 case RISCVVector::BI__builtin_rvv_vget_v_u64m2_u64m1: 3675 case RISCVVector::BI__builtin_rvv_vget_v_i8m4_i8m2: 3676 case RISCVVector::BI__builtin_rvv_vget_v_i16m4_i16m2: 3677 case RISCVVector::BI__builtin_rvv_vget_v_i32m4_i32m2: 3678 case RISCVVector::BI__builtin_rvv_vget_v_i64m4_i64m2: 3679 case RISCVVector::BI__builtin_rvv_vget_v_f32m4_f32m2: 3680 case RISCVVector::BI__builtin_rvv_vget_v_f64m4_f64m2: 3681 case RISCVVector::BI__builtin_rvv_vget_v_u8m4_u8m2: 3682 case RISCVVector::BI__builtin_rvv_vget_v_u16m4_u16m2: 3683 case RISCVVector::BI__builtin_rvv_vget_v_u32m4_u32m2: 3684 case RISCVVector::BI__builtin_rvv_vget_v_u64m4_u64m2: 3685 case RISCVVector::BI__builtin_rvv_vget_v_i8m8_i8m4: 3686 case RISCVVector::BI__builtin_rvv_vget_v_i16m8_i16m4: 3687 case RISCVVector::BI__builtin_rvv_vget_v_i32m8_i32m4: 3688 case RISCVVector::BI__builtin_rvv_vget_v_i64m8_i64m4: 3689 case RISCVVector::BI__builtin_rvv_vget_v_f32m8_f32m4: 3690 case RISCVVector::BI__builtin_rvv_vget_v_f64m8_f64m4: 3691 case RISCVVector::BI__builtin_rvv_vget_v_u8m8_u8m4: 3692 case RISCVVector::BI__builtin_rvv_vget_v_u16m8_u16m4: 3693 case RISCVVector::BI__builtin_rvv_vget_v_u32m8_u32m4: 3694 case RISCVVector::BI__builtin_rvv_vget_v_u64m8_u64m4: 3695 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3696 case RISCVVector::BI__builtin_rvv_vget_v_i8m4_i8m1: 3697 case RISCVVector::BI__builtin_rvv_vget_v_i16m4_i16m1: 3698 case RISCVVector::BI__builtin_rvv_vget_v_i32m4_i32m1: 3699 case RISCVVector::BI__builtin_rvv_vget_v_i64m4_i64m1: 3700 case RISCVVector::BI__builtin_rvv_vget_v_f32m4_f32m1: 3701 case RISCVVector::BI__builtin_rvv_vget_v_f64m4_f64m1: 3702 case RISCVVector::BI__builtin_rvv_vget_v_u8m4_u8m1: 3703 case RISCVVector::BI__builtin_rvv_vget_v_u16m4_u16m1: 3704 case RISCVVector::BI__builtin_rvv_vget_v_u32m4_u32m1: 3705 case RISCVVector::BI__builtin_rvv_vget_v_u64m4_u64m1: 3706 case RISCVVector::BI__builtin_rvv_vget_v_i8m8_i8m2: 3707 case RISCVVector::BI__builtin_rvv_vget_v_i16m8_i16m2: 3708 case RISCVVector::BI__builtin_rvv_vget_v_i32m8_i32m2: 3709 case RISCVVector::BI__builtin_rvv_vget_v_i64m8_i64m2: 3710 case RISCVVector::BI__builtin_rvv_vget_v_f32m8_f32m2: 3711 case RISCVVector::BI__builtin_rvv_vget_v_f64m8_f64m2: 3712 case RISCVVector::BI__builtin_rvv_vget_v_u8m8_u8m2: 3713 case RISCVVector::BI__builtin_rvv_vget_v_u16m8_u16m2: 3714 case RISCVVector::BI__builtin_rvv_vget_v_u32m8_u32m2: 3715 case RISCVVector::BI__builtin_rvv_vget_v_u64m8_u64m2: 3716 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3717 case RISCVVector::BI__builtin_rvv_vget_v_i8m8_i8m1: 3718 case RISCVVector::BI__builtin_rvv_vget_v_i16m8_i16m1: 3719 case RISCVVector::BI__builtin_rvv_vget_v_i32m8_i32m1: 3720 case RISCVVector::BI__builtin_rvv_vget_v_i64m8_i64m1: 3721 case RISCVVector::BI__builtin_rvv_vget_v_f32m8_f32m1: 3722 case RISCVVector::BI__builtin_rvv_vget_v_f64m8_f64m1: 3723 case RISCVVector::BI__builtin_rvv_vget_v_u8m8_u8m1: 3724 case RISCVVector::BI__builtin_rvv_vget_v_u16m8_u16m1: 3725 case RISCVVector::BI__builtin_rvv_vget_v_u32m8_u32m1: 3726 case RISCVVector::BI__builtin_rvv_vget_v_u64m8_u64m1: 3727 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); 3728 case RISCVVector::BI__builtin_rvv_vset_v_i8m1_i8m2: 3729 case RISCVVector::BI__builtin_rvv_vset_v_i16m1_i16m2: 3730 case RISCVVector::BI__builtin_rvv_vset_v_i32m1_i32m2: 3731 case RISCVVector::BI__builtin_rvv_vset_v_i64m1_i64m2: 3732 case RISCVVector::BI__builtin_rvv_vset_v_f32m1_f32m2: 3733 case RISCVVector::BI__builtin_rvv_vset_v_f64m1_f64m2: 3734 case RISCVVector::BI__builtin_rvv_vset_v_u8m1_u8m2: 3735 case RISCVVector::BI__builtin_rvv_vset_v_u16m1_u16m2: 3736 case RISCVVector::BI__builtin_rvv_vset_v_u32m1_u32m2: 3737 case RISCVVector::BI__builtin_rvv_vset_v_u64m1_u64m2: 3738 case RISCVVector::BI__builtin_rvv_vset_v_i8m2_i8m4: 3739 case RISCVVector::BI__builtin_rvv_vset_v_i16m2_i16m4: 3740 case RISCVVector::BI__builtin_rvv_vset_v_i32m2_i32m4: 3741 case RISCVVector::BI__builtin_rvv_vset_v_i64m2_i64m4: 3742 case RISCVVector::BI__builtin_rvv_vset_v_f32m2_f32m4: 3743 case RISCVVector::BI__builtin_rvv_vset_v_f64m2_f64m4: 3744 case RISCVVector::BI__builtin_rvv_vset_v_u8m2_u8m4: 3745 case RISCVVector::BI__builtin_rvv_vset_v_u16m2_u16m4: 3746 case RISCVVector::BI__builtin_rvv_vset_v_u32m2_u32m4: 3747 case RISCVVector::BI__builtin_rvv_vset_v_u64m2_u64m4: 3748 case RISCVVector::BI__builtin_rvv_vset_v_i8m4_i8m8: 3749 case RISCVVector::BI__builtin_rvv_vset_v_i16m4_i16m8: 3750 case RISCVVector::BI__builtin_rvv_vset_v_i32m4_i32m8: 3751 case RISCVVector::BI__builtin_rvv_vset_v_i64m4_i64m8: 3752 case RISCVVector::BI__builtin_rvv_vset_v_f32m4_f32m8: 3753 case RISCVVector::BI__builtin_rvv_vset_v_f64m4_f64m8: 3754 case RISCVVector::BI__builtin_rvv_vset_v_u8m4_u8m8: 3755 case RISCVVector::BI__builtin_rvv_vset_v_u16m4_u16m8: 3756 case RISCVVector::BI__builtin_rvv_vset_v_u32m4_u32m8: 3757 case RISCVVector::BI__builtin_rvv_vset_v_u64m4_u64m8: 3758 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3759 case RISCVVector::BI__builtin_rvv_vset_v_i8m1_i8m4: 3760 case RISCVVector::BI__builtin_rvv_vset_v_i16m1_i16m4: 3761 case RISCVVector::BI__builtin_rvv_vset_v_i32m1_i32m4: 3762 case RISCVVector::BI__builtin_rvv_vset_v_i64m1_i64m4: 3763 case RISCVVector::BI__builtin_rvv_vset_v_f32m1_f32m4: 3764 case RISCVVector::BI__builtin_rvv_vset_v_f64m1_f64m4: 3765 case RISCVVector::BI__builtin_rvv_vset_v_u8m1_u8m4: 3766 case RISCVVector::BI__builtin_rvv_vset_v_u16m1_u16m4: 3767 case RISCVVector::BI__builtin_rvv_vset_v_u32m1_u32m4: 3768 case RISCVVector::BI__builtin_rvv_vset_v_u64m1_u64m4: 3769 case RISCVVector::BI__builtin_rvv_vset_v_i8m2_i8m8: 3770 case RISCVVector::BI__builtin_rvv_vset_v_i16m2_i16m8: 3771 case RISCVVector::BI__builtin_rvv_vset_v_i32m2_i32m8: 3772 case RISCVVector::BI__builtin_rvv_vset_v_i64m2_i64m8: 3773 case RISCVVector::BI__builtin_rvv_vset_v_f32m2_f32m8: 3774 case RISCVVector::BI__builtin_rvv_vset_v_f64m2_f64m8: 3775 case RISCVVector::BI__builtin_rvv_vset_v_u8m2_u8m8: 3776 case RISCVVector::BI__builtin_rvv_vset_v_u16m2_u16m8: 3777 case RISCVVector::BI__builtin_rvv_vset_v_u32m2_u32m8: 3778 case RISCVVector::BI__builtin_rvv_vset_v_u64m2_u64m8: 3779 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3); 3780 case RISCVVector::BI__builtin_rvv_vset_v_i8m1_i8m8: 3781 case RISCVVector::BI__builtin_rvv_vset_v_i16m1_i16m8: 3782 case RISCVVector::BI__builtin_rvv_vset_v_i32m1_i32m8: 3783 case RISCVVector::BI__builtin_rvv_vset_v_i64m1_i64m8: 3784 case RISCVVector::BI__builtin_rvv_vset_v_f32m1_f32m8: 3785 case RISCVVector::BI__builtin_rvv_vset_v_f64m1_f64m8: 3786 case RISCVVector::BI__builtin_rvv_vset_v_u8m1_u8m8: 3787 case RISCVVector::BI__builtin_rvv_vset_v_u16m1_u16m8: 3788 case RISCVVector::BI__builtin_rvv_vset_v_u32m1_u32m8: 3789 case RISCVVector::BI__builtin_rvv_vset_v_u64m1_u64m8: 3790 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7); 3791 } 3792 3793 return false; 3794 } 3795 3796 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3797 CallExpr *TheCall) { 3798 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3799 Expr *Arg = TheCall->getArg(0); 3800 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3801 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3802 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3803 << Arg->getSourceRange(); 3804 } 3805 3806 // For intrinsics which take an immediate value as part of the instruction, 3807 // range check them here. 3808 unsigned i = 0, l = 0, u = 0; 3809 switch (BuiltinID) { 3810 default: return false; 3811 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3812 case SystemZ::BI__builtin_s390_verimb: 3813 case SystemZ::BI__builtin_s390_verimh: 3814 case SystemZ::BI__builtin_s390_verimf: 3815 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3816 case SystemZ::BI__builtin_s390_vfaeb: 3817 case SystemZ::BI__builtin_s390_vfaeh: 3818 case SystemZ::BI__builtin_s390_vfaef: 3819 case SystemZ::BI__builtin_s390_vfaebs: 3820 case SystemZ::BI__builtin_s390_vfaehs: 3821 case SystemZ::BI__builtin_s390_vfaefs: 3822 case SystemZ::BI__builtin_s390_vfaezb: 3823 case SystemZ::BI__builtin_s390_vfaezh: 3824 case SystemZ::BI__builtin_s390_vfaezf: 3825 case SystemZ::BI__builtin_s390_vfaezbs: 3826 case SystemZ::BI__builtin_s390_vfaezhs: 3827 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3828 case SystemZ::BI__builtin_s390_vfisb: 3829 case SystemZ::BI__builtin_s390_vfidb: 3830 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3831 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3832 case SystemZ::BI__builtin_s390_vftcisb: 3833 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3834 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3835 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3836 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3837 case SystemZ::BI__builtin_s390_vstrcb: 3838 case SystemZ::BI__builtin_s390_vstrch: 3839 case SystemZ::BI__builtin_s390_vstrcf: 3840 case SystemZ::BI__builtin_s390_vstrczb: 3841 case SystemZ::BI__builtin_s390_vstrczh: 3842 case SystemZ::BI__builtin_s390_vstrczf: 3843 case SystemZ::BI__builtin_s390_vstrcbs: 3844 case SystemZ::BI__builtin_s390_vstrchs: 3845 case SystemZ::BI__builtin_s390_vstrcfs: 3846 case SystemZ::BI__builtin_s390_vstrczbs: 3847 case SystemZ::BI__builtin_s390_vstrczhs: 3848 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3849 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3850 case SystemZ::BI__builtin_s390_vfminsb: 3851 case SystemZ::BI__builtin_s390_vfmaxsb: 3852 case SystemZ::BI__builtin_s390_vfmindb: 3853 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3854 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3855 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3856 case SystemZ::BI__builtin_s390_vclfnhs: 3857 case SystemZ::BI__builtin_s390_vclfnls: 3858 case SystemZ::BI__builtin_s390_vcfn: 3859 case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break; 3860 case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break; 3861 } 3862 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3863 } 3864 3865 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3866 /// This checks that the target supports __builtin_cpu_supports and 3867 /// that the string argument is constant and valid. 3868 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3869 CallExpr *TheCall) { 3870 Expr *Arg = TheCall->getArg(0); 3871 3872 // Check if the argument is a string literal. 3873 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3874 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3875 << Arg->getSourceRange(); 3876 3877 // Check the contents of the string. 3878 StringRef Feature = 3879 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3880 if (!TI.validateCpuSupports(Feature)) 3881 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3882 << Arg->getSourceRange(); 3883 return false; 3884 } 3885 3886 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3887 /// This checks that the target supports __builtin_cpu_is and 3888 /// that the string argument is constant and valid. 3889 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3890 Expr *Arg = TheCall->getArg(0); 3891 3892 // Check if the argument is a string literal. 3893 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3894 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3895 << Arg->getSourceRange(); 3896 3897 // Check the contents of the string. 3898 StringRef Feature = 3899 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3900 if (!TI.validateCpuIs(Feature)) 3901 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3902 << Arg->getSourceRange(); 3903 return false; 3904 } 3905 3906 // Check if the rounding mode is legal. 3907 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3908 // Indicates if this instruction has rounding control or just SAE. 3909 bool HasRC = false; 3910 3911 unsigned ArgNum = 0; 3912 switch (BuiltinID) { 3913 default: 3914 return false; 3915 case X86::BI__builtin_ia32_vcvttsd2si32: 3916 case X86::BI__builtin_ia32_vcvttsd2si64: 3917 case X86::BI__builtin_ia32_vcvttsd2usi32: 3918 case X86::BI__builtin_ia32_vcvttsd2usi64: 3919 case X86::BI__builtin_ia32_vcvttss2si32: 3920 case X86::BI__builtin_ia32_vcvttss2si64: 3921 case X86::BI__builtin_ia32_vcvttss2usi32: 3922 case X86::BI__builtin_ia32_vcvttss2usi64: 3923 case X86::BI__builtin_ia32_vcvttsh2si32: 3924 case X86::BI__builtin_ia32_vcvttsh2si64: 3925 case X86::BI__builtin_ia32_vcvttsh2usi32: 3926 case X86::BI__builtin_ia32_vcvttsh2usi64: 3927 ArgNum = 1; 3928 break; 3929 case X86::BI__builtin_ia32_maxpd512: 3930 case X86::BI__builtin_ia32_maxps512: 3931 case X86::BI__builtin_ia32_minpd512: 3932 case X86::BI__builtin_ia32_minps512: 3933 case X86::BI__builtin_ia32_maxph512: 3934 case X86::BI__builtin_ia32_minph512: 3935 ArgNum = 2; 3936 break; 3937 case X86::BI__builtin_ia32_vcvtph2pd512_mask: 3938 case X86::BI__builtin_ia32_vcvtph2psx512_mask: 3939 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3940 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3941 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3942 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3943 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3944 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3945 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3946 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3947 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3948 case X86::BI__builtin_ia32_vcvttph2w512_mask: 3949 case X86::BI__builtin_ia32_vcvttph2uw512_mask: 3950 case X86::BI__builtin_ia32_vcvttph2dq512_mask: 3951 case X86::BI__builtin_ia32_vcvttph2udq512_mask: 3952 case X86::BI__builtin_ia32_vcvttph2qq512_mask: 3953 case X86::BI__builtin_ia32_vcvttph2uqq512_mask: 3954 case X86::BI__builtin_ia32_exp2pd_mask: 3955 case X86::BI__builtin_ia32_exp2ps_mask: 3956 case X86::BI__builtin_ia32_getexppd512_mask: 3957 case X86::BI__builtin_ia32_getexpps512_mask: 3958 case X86::BI__builtin_ia32_getexpph512_mask: 3959 case X86::BI__builtin_ia32_rcp28pd_mask: 3960 case X86::BI__builtin_ia32_rcp28ps_mask: 3961 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3962 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3963 case X86::BI__builtin_ia32_vcomisd: 3964 case X86::BI__builtin_ia32_vcomiss: 3965 case X86::BI__builtin_ia32_vcomish: 3966 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3967 ArgNum = 3; 3968 break; 3969 case X86::BI__builtin_ia32_cmppd512_mask: 3970 case X86::BI__builtin_ia32_cmpps512_mask: 3971 case X86::BI__builtin_ia32_cmpsd_mask: 3972 case X86::BI__builtin_ia32_cmpss_mask: 3973 case X86::BI__builtin_ia32_cmpsh_mask: 3974 case X86::BI__builtin_ia32_vcvtsh2sd_round_mask: 3975 case X86::BI__builtin_ia32_vcvtsh2ss_round_mask: 3976 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3977 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3978 case X86::BI__builtin_ia32_getexpss128_round_mask: 3979 case X86::BI__builtin_ia32_getexpsh128_round_mask: 3980 case X86::BI__builtin_ia32_getmantpd512_mask: 3981 case X86::BI__builtin_ia32_getmantps512_mask: 3982 case X86::BI__builtin_ia32_getmantph512_mask: 3983 case X86::BI__builtin_ia32_maxsd_round_mask: 3984 case X86::BI__builtin_ia32_maxss_round_mask: 3985 case X86::BI__builtin_ia32_maxsh_round_mask: 3986 case X86::BI__builtin_ia32_minsd_round_mask: 3987 case X86::BI__builtin_ia32_minss_round_mask: 3988 case X86::BI__builtin_ia32_minsh_round_mask: 3989 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3990 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3991 case X86::BI__builtin_ia32_reducepd512_mask: 3992 case X86::BI__builtin_ia32_reduceps512_mask: 3993 case X86::BI__builtin_ia32_reduceph512_mask: 3994 case X86::BI__builtin_ia32_rndscalepd_mask: 3995 case X86::BI__builtin_ia32_rndscaleps_mask: 3996 case X86::BI__builtin_ia32_rndscaleph_mask: 3997 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3998 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3999 ArgNum = 4; 4000 break; 4001 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4002 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4003 case X86::BI__builtin_ia32_fixupimmps512_mask: 4004 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4005 case X86::BI__builtin_ia32_fixupimmsd_mask: 4006 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4007 case X86::BI__builtin_ia32_fixupimmss_mask: 4008 case X86::BI__builtin_ia32_fixupimmss_maskz: 4009 case X86::BI__builtin_ia32_getmantsd_round_mask: 4010 case X86::BI__builtin_ia32_getmantss_round_mask: 4011 case X86::BI__builtin_ia32_getmantsh_round_mask: 4012 case X86::BI__builtin_ia32_rangepd512_mask: 4013 case X86::BI__builtin_ia32_rangeps512_mask: 4014 case X86::BI__builtin_ia32_rangesd128_round_mask: 4015 case X86::BI__builtin_ia32_rangess128_round_mask: 4016 case X86::BI__builtin_ia32_reducesd_mask: 4017 case X86::BI__builtin_ia32_reducess_mask: 4018 case X86::BI__builtin_ia32_reducesh_mask: 4019 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4020 case X86::BI__builtin_ia32_rndscaless_round_mask: 4021 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4022 ArgNum = 5; 4023 break; 4024 case X86::BI__builtin_ia32_vcvtsd2si64: 4025 case X86::BI__builtin_ia32_vcvtsd2si32: 4026 case X86::BI__builtin_ia32_vcvtsd2usi32: 4027 case X86::BI__builtin_ia32_vcvtsd2usi64: 4028 case X86::BI__builtin_ia32_vcvtss2si32: 4029 case X86::BI__builtin_ia32_vcvtss2si64: 4030 case X86::BI__builtin_ia32_vcvtss2usi32: 4031 case X86::BI__builtin_ia32_vcvtss2usi64: 4032 case X86::BI__builtin_ia32_vcvtsh2si32: 4033 case X86::BI__builtin_ia32_vcvtsh2si64: 4034 case X86::BI__builtin_ia32_vcvtsh2usi32: 4035 case X86::BI__builtin_ia32_vcvtsh2usi64: 4036 case X86::BI__builtin_ia32_sqrtpd512: 4037 case X86::BI__builtin_ia32_sqrtps512: 4038 case X86::BI__builtin_ia32_sqrtph512: 4039 ArgNum = 1; 4040 HasRC = true; 4041 break; 4042 case X86::BI__builtin_ia32_addph512: 4043 case X86::BI__builtin_ia32_divph512: 4044 case X86::BI__builtin_ia32_mulph512: 4045 case X86::BI__builtin_ia32_subph512: 4046 case X86::BI__builtin_ia32_addpd512: 4047 case X86::BI__builtin_ia32_addps512: 4048 case X86::BI__builtin_ia32_divpd512: 4049 case X86::BI__builtin_ia32_divps512: 4050 case X86::BI__builtin_ia32_mulpd512: 4051 case X86::BI__builtin_ia32_mulps512: 4052 case X86::BI__builtin_ia32_subpd512: 4053 case X86::BI__builtin_ia32_subps512: 4054 case X86::BI__builtin_ia32_cvtsi2sd64: 4055 case X86::BI__builtin_ia32_cvtsi2ss32: 4056 case X86::BI__builtin_ia32_cvtsi2ss64: 4057 case X86::BI__builtin_ia32_cvtusi2sd64: 4058 case X86::BI__builtin_ia32_cvtusi2ss32: 4059 case X86::BI__builtin_ia32_cvtusi2ss64: 4060 case X86::BI__builtin_ia32_vcvtusi2sh: 4061 case X86::BI__builtin_ia32_vcvtusi642sh: 4062 case X86::BI__builtin_ia32_vcvtsi2sh: 4063 case X86::BI__builtin_ia32_vcvtsi642sh: 4064 ArgNum = 2; 4065 HasRC = true; 4066 break; 4067 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 4068 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 4069 case X86::BI__builtin_ia32_vcvtpd2ph512_mask: 4070 case X86::BI__builtin_ia32_vcvtps2phx512_mask: 4071 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 4072 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 4073 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 4074 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 4075 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 4076 case X86::BI__builtin_ia32_cvtps2dq512_mask: 4077 case X86::BI__builtin_ia32_cvtps2qq512_mask: 4078 case X86::BI__builtin_ia32_cvtps2udq512_mask: 4079 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 4080 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 4081 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 4082 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 4083 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 4084 case X86::BI__builtin_ia32_vcvtdq2ph512_mask: 4085 case X86::BI__builtin_ia32_vcvtudq2ph512_mask: 4086 case X86::BI__builtin_ia32_vcvtw2ph512_mask: 4087 case X86::BI__builtin_ia32_vcvtuw2ph512_mask: 4088 case X86::BI__builtin_ia32_vcvtph2w512_mask: 4089 case X86::BI__builtin_ia32_vcvtph2uw512_mask: 4090 case X86::BI__builtin_ia32_vcvtph2dq512_mask: 4091 case X86::BI__builtin_ia32_vcvtph2udq512_mask: 4092 case X86::BI__builtin_ia32_vcvtph2qq512_mask: 4093 case X86::BI__builtin_ia32_vcvtph2uqq512_mask: 4094 case X86::BI__builtin_ia32_vcvtqq2ph512_mask: 4095 case X86::BI__builtin_ia32_vcvtuqq2ph512_mask: 4096 ArgNum = 3; 4097 HasRC = true; 4098 break; 4099 case X86::BI__builtin_ia32_addsh_round_mask: 4100 case X86::BI__builtin_ia32_addss_round_mask: 4101 case X86::BI__builtin_ia32_addsd_round_mask: 4102 case X86::BI__builtin_ia32_divsh_round_mask: 4103 case X86::BI__builtin_ia32_divss_round_mask: 4104 case X86::BI__builtin_ia32_divsd_round_mask: 4105 case X86::BI__builtin_ia32_mulsh_round_mask: 4106 case X86::BI__builtin_ia32_mulss_round_mask: 4107 case X86::BI__builtin_ia32_mulsd_round_mask: 4108 case X86::BI__builtin_ia32_subsh_round_mask: 4109 case X86::BI__builtin_ia32_subss_round_mask: 4110 case X86::BI__builtin_ia32_subsd_round_mask: 4111 case X86::BI__builtin_ia32_scalefph512_mask: 4112 case X86::BI__builtin_ia32_scalefpd512_mask: 4113 case X86::BI__builtin_ia32_scalefps512_mask: 4114 case X86::BI__builtin_ia32_scalefsd_round_mask: 4115 case X86::BI__builtin_ia32_scalefss_round_mask: 4116 case X86::BI__builtin_ia32_scalefsh_round_mask: 4117 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 4118 case X86::BI__builtin_ia32_vcvtss2sh_round_mask: 4119 case X86::BI__builtin_ia32_vcvtsd2sh_round_mask: 4120 case X86::BI__builtin_ia32_sqrtsd_round_mask: 4121 case X86::BI__builtin_ia32_sqrtss_round_mask: 4122 case X86::BI__builtin_ia32_sqrtsh_round_mask: 4123 case X86::BI__builtin_ia32_vfmaddsd3_mask: 4124 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 4125 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 4126 case X86::BI__builtin_ia32_vfmaddss3_mask: 4127 case X86::BI__builtin_ia32_vfmaddss3_maskz: 4128 case X86::BI__builtin_ia32_vfmaddss3_mask3: 4129 case X86::BI__builtin_ia32_vfmaddsh3_mask: 4130 case X86::BI__builtin_ia32_vfmaddsh3_maskz: 4131 case X86::BI__builtin_ia32_vfmaddsh3_mask3: 4132 case X86::BI__builtin_ia32_vfmaddpd512_mask: 4133 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 4134 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 4135 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 4136 case X86::BI__builtin_ia32_vfmaddps512_mask: 4137 case X86::BI__builtin_ia32_vfmaddps512_maskz: 4138 case X86::BI__builtin_ia32_vfmaddps512_mask3: 4139 case X86::BI__builtin_ia32_vfmsubps512_mask3: 4140 case X86::BI__builtin_ia32_vfmaddph512_mask: 4141 case X86::BI__builtin_ia32_vfmaddph512_maskz: 4142 case X86::BI__builtin_ia32_vfmaddph512_mask3: 4143 case X86::BI__builtin_ia32_vfmsubph512_mask3: 4144 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 4145 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 4146 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 4147 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 4148 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 4149 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 4150 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 4151 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 4152 case X86::BI__builtin_ia32_vfmaddsubph512_mask: 4153 case X86::BI__builtin_ia32_vfmaddsubph512_maskz: 4154 case X86::BI__builtin_ia32_vfmaddsubph512_mask3: 4155 case X86::BI__builtin_ia32_vfmsubaddph512_mask3: 4156 case X86::BI__builtin_ia32_vfmaddcsh_mask: 4157 case X86::BI__builtin_ia32_vfmaddcsh_round_mask: 4158 case X86::BI__builtin_ia32_vfmaddcsh_round_mask3: 4159 case X86::BI__builtin_ia32_vfmaddcph512_mask: 4160 case X86::BI__builtin_ia32_vfmaddcph512_maskz: 4161 case X86::BI__builtin_ia32_vfmaddcph512_mask3: 4162 case X86::BI__builtin_ia32_vfcmaddcsh_mask: 4163 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask: 4164 case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3: 4165 case X86::BI__builtin_ia32_vfcmaddcph512_mask: 4166 case X86::BI__builtin_ia32_vfcmaddcph512_maskz: 4167 case X86::BI__builtin_ia32_vfcmaddcph512_mask3: 4168 case X86::BI__builtin_ia32_vfmulcsh_mask: 4169 case X86::BI__builtin_ia32_vfmulcph512_mask: 4170 case X86::BI__builtin_ia32_vfcmulcsh_mask: 4171 case X86::BI__builtin_ia32_vfcmulcph512_mask: 4172 ArgNum = 4; 4173 HasRC = true; 4174 break; 4175 } 4176 4177 llvm::APSInt Result; 4178 4179 // We can't check the value of a dependent argument. 4180 Expr *Arg = TheCall->getArg(ArgNum); 4181 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4182 return false; 4183 4184 // Check constant-ness first. 4185 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4186 return true; 4187 4188 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 4189 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 4190 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 4191 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 4192 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 4193 Result == 8/*ROUND_NO_EXC*/ || 4194 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 4195 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 4196 return false; 4197 4198 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 4199 << Arg->getSourceRange(); 4200 } 4201 4202 // Check if the gather/scatter scale is legal. 4203 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 4204 CallExpr *TheCall) { 4205 unsigned ArgNum = 0; 4206 switch (BuiltinID) { 4207 default: 4208 return false; 4209 case X86::BI__builtin_ia32_gatherpfdpd: 4210 case X86::BI__builtin_ia32_gatherpfdps: 4211 case X86::BI__builtin_ia32_gatherpfqpd: 4212 case X86::BI__builtin_ia32_gatherpfqps: 4213 case X86::BI__builtin_ia32_scatterpfdpd: 4214 case X86::BI__builtin_ia32_scatterpfdps: 4215 case X86::BI__builtin_ia32_scatterpfqpd: 4216 case X86::BI__builtin_ia32_scatterpfqps: 4217 ArgNum = 3; 4218 break; 4219 case X86::BI__builtin_ia32_gatherd_pd: 4220 case X86::BI__builtin_ia32_gatherd_pd256: 4221 case X86::BI__builtin_ia32_gatherq_pd: 4222 case X86::BI__builtin_ia32_gatherq_pd256: 4223 case X86::BI__builtin_ia32_gatherd_ps: 4224 case X86::BI__builtin_ia32_gatherd_ps256: 4225 case X86::BI__builtin_ia32_gatherq_ps: 4226 case X86::BI__builtin_ia32_gatherq_ps256: 4227 case X86::BI__builtin_ia32_gatherd_q: 4228 case X86::BI__builtin_ia32_gatherd_q256: 4229 case X86::BI__builtin_ia32_gatherq_q: 4230 case X86::BI__builtin_ia32_gatherq_q256: 4231 case X86::BI__builtin_ia32_gatherd_d: 4232 case X86::BI__builtin_ia32_gatherd_d256: 4233 case X86::BI__builtin_ia32_gatherq_d: 4234 case X86::BI__builtin_ia32_gatherq_d256: 4235 case X86::BI__builtin_ia32_gather3div2df: 4236 case X86::BI__builtin_ia32_gather3div2di: 4237 case X86::BI__builtin_ia32_gather3div4df: 4238 case X86::BI__builtin_ia32_gather3div4di: 4239 case X86::BI__builtin_ia32_gather3div4sf: 4240 case X86::BI__builtin_ia32_gather3div4si: 4241 case X86::BI__builtin_ia32_gather3div8sf: 4242 case X86::BI__builtin_ia32_gather3div8si: 4243 case X86::BI__builtin_ia32_gather3siv2df: 4244 case X86::BI__builtin_ia32_gather3siv2di: 4245 case X86::BI__builtin_ia32_gather3siv4df: 4246 case X86::BI__builtin_ia32_gather3siv4di: 4247 case X86::BI__builtin_ia32_gather3siv4sf: 4248 case X86::BI__builtin_ia32_gather3siv4si: 4249 case X86::BI__builtin_ia32_gather3siv8sf: 4250 case X86::BI__builtin_ia32_gather3siv8si: 4251 case X86::BI__builtin_ia32_gathersiv8df: 4252 case X86::BI__builtin_ia32_gathersiv16sf: 4253 case X86::BI__builtin_ia32_gatherdiv8df: 4254 case X86::BI__builtin_ia32_gatherdiv16sf: 4255 case X86::BI__builtin_ia32_gathersiv8di: 4256 case X86::BI__builtin_ia32_gathersiv16si: 4257 case X86::BI__builtin_ia32_gatherdiv8di: 4258 case X86::BI__builtin_ia32_gatherdiv16si: 4259 case X86::BI__builtin_ia32_scatterdiv2df: 4260 case X86::BI__builtin_ia32_scatterdiv2di: 4261 case X86::BI__builtin_ia32_scatterdiv4df: 4262 case X86::BI__builtin_ia32_scatterdiv4di: 4263 case X86::BI__builtin_ia32_scatterdiv4sf: 4264 case X86::BI__builtin_ia32_scatterdiv4si: 4265 case X86::BI__builtin_ia32_scatterdiv8sf: 4266 case X86::BI__builtin_ia32_scatterdiv8si: 4267 case X86::BI__builtin_ia32_scattersiv2df: 4268 case X86::BI__builtin_ia32_scattersiv2di: 4269 case X86::BI__builtin_ia32_scattersiv4df: 4270 case X86::BI__builtin_ia32_scattersiv4di: 4271 case X86::BI__builtin_ia32_scattersiv4sf: 4272 case X86::BI__builtin_ia32_scattersiv4si: 4273 case X86::BI__builtin_ia32_scattersiv8sf: 4274 case X86::BI__builtin_ia32_scattersiv8si: 4275 case X86::BI__builtin_ia32_scattersiv8df: 4276 case X86::BI__builtin_ia32_scattersiv16sf: 4277 case X86::BI__builtin_ia32_scatterdiv8df: 4278 case X86::BI__builtin_ia32_scatterdiv16sf: 4279 case X86::BI__builtin_ia32_scattersiv8di: 4280 case X86::BI__builtin_ia32_scattersiv16si: 4281 case X86::BI__builtin_ia32_scatterdiv8di: 4282 case X86::BI__builtin_ia32_scatterdiv16si: 4283 ArgNum = 4; 4284 break; 4285 } 4286 4287 llvm::APSInt Result; 4288 4289 // We can't check the value of a dependent argument. 4290 Expr *Arg = TheCall->getArg(ArgNum); 4291 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4292 return false; 4293 4294 // Check constant-ness first. 4295 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4296 return true; 4297 4298 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 4299 return false; 4300 4301 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 4302 << Arg->getSourceRange(); 4303 } 4304 4305 enum { TileRegLow = 0, TileRegHigh = 7 }; 4306 4307 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 4308 ArrayRef<int> ArgNums) { 4309 for (int ArgNum : ArgNums) { 4310 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 4311 return true; 4312 } 4313 return false; 4314 } 4315 4316 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 4317 ArrayRef<int> ArgNums) { 4318 // Because the max number of tile register is TileRegHigh + 1, so here we use 4319 // each bit to represent the usage of them in bitset. 4320 std::bitset<TileRegHigh + 1> ArgValues; 4321 for (int ArgNum : ArgNums) { 4322 Expr *Arg = TheCall->getArg(ArgNum); 4323 if (Arg->isTypeDependent() || Arg->isValueDependent()) 4324 continue; 4325 4326 llvm::APSInt Result; 4327 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 4328 return true; 4329 int ArgExtValue = Result.getExtValue(); 4330 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 4331 "Incorrect tile register num."); 4332 if (ArgValues.test(ArgExtValue)) 4333 return Diag(TheCall->getBeginLoc(), 4334 diag::err_x86_builtin_tile_arg_duplicate) 4335 << TheCall->getArg(ArgNum)->getSourceRange(); 4336 ArgValues.set(ArgExtValue); 4337 } 4338 return false; 4339 } 4340 4341 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 4342 ArrayRef<int> ArgNums) { 4343 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 4344 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 4345 } 4346 4347 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 4348 switch (BuiltinID) { 4349 default: 4350 return false; 4351 case X86::BI__builtin_ia32_tileloadd64: 4352 case X86::BI__builtin_ia32_tileloaddt164: 4353 case X86::BI__builtin_ia32_tilestored64: 4354 case X86::BI__builtin_ia32_tilezero: 4355 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 4356 case X86::BI__builtin_ia32_tdpbssd: 4357 case X86::BI__builtin_ia32_tdpbsud: 4358 case X86::BI__builtin_ia32_tdpbusd: 4359 case X86::BI__builtin_ia32_tdpbuud: 4360 case X86::BI__builtin_ia32_tdpbf16ps: 4361 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 4362 } 4363 } 4364 static bool isX86_32Builtin(unsigned BuiltinID) { 4365 // These builtins only work on x86-32 targets. 4366 switch (BuiltinID) { 4367 case X86::BI__builtin_ia32_readeflags_u32: 4368 case X86::BI__builtin_ia32_writeeflags_u32: 4369 return true; 4370 } 4371 4372 return false; 4373 } 4374 4375 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 4376 CallExpr *TheCall) { 4377 if (BuiltinID == X86::BI__builtin_cpu_supports) 4378 return SemaBuiltinCpuSupports(*this, TI, TheCall); 4379 4380 if (BuiltinID == X86::BI__builtin_cpu_is) 4381 return SemaBuiltinCpuIs(*this, TI, TheCall); 4382 4383 // Check for 32-bit only builtins on a 64-bit target. 4384 const llvm::Triple &TT = TI.getTriple(); 4385 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 4386 return Diag(TheCall->getCallee()->getBeginLoc(), 4387 diag::err_32_bit_builtin_64_bit_tgt); 4388 4389 // If the intrinsic has rounding or SAE make sure its valid. 4390 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 4391 return true; 4392 4393 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 4394 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 4395 return true; 4396 4397 // If the intrinsic has a tile arguments, make sure they are valid. 4398 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 4399 return true; 4400 4401 // For intrinsics which take an immediate value as part of the instruction, 4402 // range check them here. 4403 int i = 0, l = 0, u = 0; 4404 switch (BuiltinID) { 4405 default: 4406 return false; 4407 case X86::BI__builtin_ia32_vec_ext_v2si: 4408 case X86::BI__builtin_ia32_vec_ext_v2di: 4409 case X86::BI__builtin_ia32_vextractf128_pd256: 4410 case X86::BI__builtin_ia32_vextractf128_ps256: 4411 case X86::BI__builtin_ia32_vextractf128_si256: 4412 case X86::BI__builtin_ia32_extract128i256: 4413 case X86::BI__builtin_ia32_extractf64x4_mask: 4414 case X86::BI__builtin_ia32_extracti64x4_mask: 4415 case X86::BI__builtin_ia32_extractf32x8_mask: 4416 case X86::BI__builtin_ia32_extracti32x8_mask: 4417 case X86::BI__builtin_ia32_extractf64x2_256_mask: 4418 case X86::BI__builtin_ia32_extracti64x2_256_mask: 4419 case X86::BI__builtin_ia32_extractf32x4_256_mask: 4420 case X86::BI__builtin_ia32_extracti32x4_256_mask: 4421 i = 1; l = 0; u = 1; 4422 break; 4423 case X86::BI__builtin_ia32_vec_set_v2di: 4424 case X86::BI__builtin_ia32_vinsertf128_pd256: 4425 case X86::BI__builtin_ia32_vinsertf128_ps256: 4426 case X86::BI__builtin_ia32_vinsertf128_si256: 4427 case X86::BI__builtin_ia32_insert128i256: 4428 case X86::BI__builtin_ia32_insertf32x8: 4429 case X86::BI__builtin_ia32_inserti32x8: 4430 case X86::BI__builtin_ia32_insertf64x4: 4431 case X86::BI__builtin_ia32_inserti64x4: 4432 case X86::BI__builtin_ia32_insertf64x2_256: 4433 case X86::BI__builtin_ia32_inserti64x2_256: 4434 case X86::BI__builtin_ia32_insertf32x4_256: 4435 case X86::BI__builtin_ia32_inserti32x4_256: 4436 i = 2; l = 0; u = 1; 4437 break; 4438 case X86::BI__builtin_ia32_vpermilpd: 4439 case X86::BI__builtin_ia32_vec_ext_v4hi: 4440 case X86::BI__builtin_ia32_vec_ext_v4si: 4441 case X86::BI__builtin_ia32_vec_ext_v4sf: 4442 case X86::BI__builtin_ia32_vec_ext_v4di: 4443 case X86::BI__builtin_ia32_extractf32x4_mask: 4444 case X86::BI__builtin_ia32_extracti32x4_mask: 4445 case X86::BI__builtin_ia32_extractf64x2_512_mask: 4446 case X86::BI__builtin_ia32_extracti64x2_512_mask: 4447 i = 1; l = 0; u = 3; 4448 break; 4449 case X86::BI_mm_prefetch: 4450 case X86::BI__builtin_ia32_vec_ext_v8hi: 4451 case X86::BI__builtin_ia32_vec_ext_v8si: 4452 i = 1; l = 0; u = 7; 4453 break; 4454 case X86::BI__builtin_ia32_sha1rnds4: 4455 case X86::BI__builtin_ia32_blendpd: 4456 case X86::BI__builtin_ia32_shufpd: 4457 case X86::BI__builtin_ia32_vec_set_v4hi: 4458 case X86::BI__builtin_ia32_vec_set_v4si: 4459 case X86::BI__builtin_ia32_vec_set_v4di: 4460 case X86::BI__builtin_ia32_shuf_f32x4_256: 4461 case X86::BI__builtin_ia32_shuf_f64x2_256: 4462 case X86::BI__builtin_ia32_shuf_i32x4_256: 4463 case X86::BI__builtin_ia32_shuf_i64x2_256: 4464 case X86::BI__builtin_ia32_insertf64x2_512: 4465 case X86::BI__builtin_ia32_inserti64x2_512: 4466 case X86::BI__builtin_ia32_insertf32x4: 4467 case X86::BI__builtin_ia32_inserti32x4: 4468 i = 2; l = 0; u = 3; 4469 break; 4470 case X86::BI__builtin_ia32_vpermil2pd: 4471 case X86::BI__builtin_ia32_vpermil2pd256: 4472 case X86::BI__builtin_ia32_vpermil2ps: 4473 case X86::BI__builtin_ia32_vpermil2ps256: 4474 i = 3; l = 0; u = 3; 4475 break; 4476 case X86::BI__builtin_ia32_cmpb128_mask: 4477 case X86::BI__builtin_ia32_cmpw128_mask: 4478 case X86::BI__builtin_ia32_cmpd128_mask: 4479 case X86::BI__builtin_ia32_cmpq128_mask: 4480 case X86::BI__builtin_ia32_cmpb256_mask: 4481 case X86::BI__builtin_ia32_cmpw256_mask: 4482 case X86::BI__builtin_ia32_cmpd256_mask: 4483 case X86::BI__builtin_ia32_cmpq256_mask: 4484 case X86::BI__builtin_ia32_cmpb512_mask: 4485 case X86::BI__builtin_ia32_cmpw512_mask: 4486 case X86::BI__builtin_ia32_cmpd512_mask: 4487 case X86::BI__builtin_ia32_cmpq512_mask: 4488 case X86::BI__builtin_ia32_ucmpb128_mask: 4489 case X86::BI__builtin_ia32_ucmpw128_mask: 4490 case X86::BI__builtin_ia32_ucmpd128_mask: 4491 case X86::BI__builtin_ia32_ucmpq128_mask: 4492 case X86::BI__builtin_ia32_ucmpb256_mask: 4493 case X86::BI__builtin_ia32_ucmpw256_mask: 4494 case X86::BI__builtin_ia32_ucmpd256_mask: 4495 case X86::BI__builtin_ia32_ucmpq256_mask: 4496 case X86::BI__builtin_ia32_ucmpb512_mask: 4497 case X86::BI__builtin_ia32_ucmpw512_mask: 4498 case X86::BI__builtin_ia32_ucmpd512_mask: 4499 case X86::BI__builtin_ia32_ucmpq512_mask: 4500 case X86::BI__builtin_ia32_vpcomub: 4501 case X86::BI__builtin_ia32_vpcomuw: 4502 case X86::BI__builtin_ia32_vpcomud: 4503 case X86::BI__builtin_ia32_vpcomuq: 4504 case X86::BI__builtin_ia32_vpcomb: 4505 case X86::BI__builtin_ia32_vpcomw: 4506 case X86::BI__builtin_ia32_vpcomd: 4507 case X86::BI__builtin_ia32_vpcomq: 4508 case X86::BI__builtin_ia32_vec_set_v8hi: 4509 case X86::BI__builtin_ia32_vec_set_v8si: 4510 i = 2; l = 0; u = 7; 4511 break; 4512 case X86::BI__builtin_ia32_vpermilpd256: 4513 case X86::BI__builtin_ia32_roundps: 4514 case X86::BI__builtin_ia32_roundpd: 4515 case X86::BI__builtin_ia32_roundps256: 4516 case X86::BI__builtin_ia32_roundpd256: 4517 case X86::BI__builtin_ia32_getmantpd128_mask: 4518 case X86::BI__builtin_ia32_getmantpd256_mask: 4519 case X86::BI__builtin_ia32_getmantps128_mask: 4520 case X86::BI__builtin_ia32_getmantps256_mask: 4521 case X86::BI__builtin_ia32_getmantpd512_mask: 4522 case X86::BI__builtin_ia32_getmantps512_mask: 4523 case X86::BI__builtin_ia32_getmantph128_mask: 4524 case X86::BI__builtin_ia32_getmantph256_mask: 4525 case X86::BI__builtin_ia32_getmantph512_mask: 4526 case X86::BI__builtin_ia32_vec_ext_v16qi: 4527 case X86::BI__builtin_ia32_vec_ext_v16hi: 4528 i = 1; l = 0; u = 15; 4529 break; 4530 case X86::BI__builtin_ia32_pblendd128: 4531 case X86::BI__builtin_ia32_blendps: 4532 case X86::BI__builtin_ia32_blendpd256: 4533 case X86::BI__builtin_ia32_shufpd256: 4534 case X86::BI__builtin_ia32_roundss: 4535 case X86::BI__builtin_ia32_roundsd: 4536 case X86::BI__builtin_ia32_rangepd128_mask: 4537 case X86::BI__builtin_ia32_rangepd256_mask: 4538 case X86::BI__builtin_ia32_rangepd512_mask: 4539 case X86::BI__builtin_ia32_rangeps128_mask: 4540 case X86::BI__builtin_ia32_rangeps256_mask: 4541 case X86::BI__builtin_ia32_rangeps512_mask: 4542 case X86::BI__builtin_ia32_getmantsd_round_mask: 4543 case X86::BI__builtin_ia32_getmantss_round_mask: 4544 case X86::BI__builtin_ia32_getmantsh_round_mask: 4545 case X86::BI__builtin_ia32_vec_set_v16qi: 4546 case X86::BI__builtin_ia32_vec_set_v16hi: 4547 i = 2; l = 0; u = 15; 4548 break; 4549 case X86::BI__builtin_ia32_vec_ext_v32qi: 4550 i = 1; l = 0; u = 31; 4551 break; 4552 case X86::BI__builtin_ia32_cmpps: 4553 case X86::BI__builtin_ia32_cmpss: 4554 case X86::BI__builtin_ia32_cmppd: 4555 case X86::BI__builtin_ia32_cmpsd: 4556 case X86::BI__builtin_ia32_cmpps256: 4557 case X86::BI__builtin_ia32_cmppd256: 4558 case X86::BI__builtin_ia32_cmpps128_mask: 4559 case X86::BI__builtin_ia32_cmppd128_mask: 4560 case X86::BI__builtin_ia32_cmpps256_mask: 4561 case X86::BI__builtin_ia32_cmppd256_mask: 4562 case X86::BI__builtin_ia32_cmpps512_mask: 4563 case X86::BI__builtin_ia32_cmppd512_mask: 4564 case X86::BI__builtin_ia32_cmpsd_mask: 4565 case X86::BI__builtin_ia32_cmpss_mask: 4566 case X86::BI__builtin_ia32_vec_set_v32qi: 4567 i = 2; l = 0; u = 31; 4568 break; 4569 case X86::BI__builtin_ia32_permdf256: 4570 case X86::BI__builtin_ia32_permdi256: 4571 case X86::BI__builtin_ia32_permdf512: 4572 case X86::BI__builtin_ia32_permdi512: 4573 case X86::BI__builtin_ia32_vpermilps: 4574 case X86::BI__builtin_ia32_vpermilps256: 4575 case X86::BI__builtin_ia32_vpermilpd512: 4576 case X86::BI__builtin_ia32_vpermilps512: 4577 case X86::BI__builtin_ia32_pshufd: 4578 case X86::BI__builtin_ia32_pshufd256: 4579 case X86::BI__builtin_ia32_pshufd512: 4580 case X86::BI__builtin_ia32_pshufhw: 4581 case X86::BI__builtin_ia32_pshufhw256: 4582 case X86::BI__builtin_ia32_pshufhw512: 4583 case X86::BI__builtin_ia32_pshuflw: 4584 case X86::BI__builtin_ia32_pshuflw256: 4585 case X86::BI__builtin_ia32_pshuflw512: 4586 case X86::BI__builtin_ia32_vcvtps2ph: 4587 case X86::BI__builtin_ia32_vcvtps2ph_mask: 4588 case X86::BI__builtin_ia32_vcvtps2ph256: 4589 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 4590 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 4591 case X86::BI__builtin_ia32_rndscaleps_128_mask: 4592 case X86::BI__builtin_ia32_rndscalepd_128_mask: 4593 case X86::BI__builtin_ia32_rndscaleps_256_mask: 4594 case X86::BI__builtin_ia32_rndscalepd_256_mask: 4595 case X86::BI__builtin_ia32_rndscaleps_mask: 4596 case X86::BI__builtin_ia32_rndscalepd_mask: 4597 case X86::BI__builtin_ia32_rndscaleph_mask: 4598 case X86::BI__builtin_ia32_reducepd128_mask: 4599 case X86::BI__builtin_ia32_reducepd256_mask: 4600 case X86::BI__builtin_ia32_reducepd512_mask: 4601 case X86::BI__builtin_ia32_reduceps128_mask: 4602 case X86::BI__builtin_ia32_reduceps256_mask: 4603 case X86::BI__builtin_ia32_reduceps512_mask: 4604 case X86::BI__builtin_ia32_reduceph128_mask: 4605 case X86::BI__builtin_ia32_reduceph256_mask: 4606 case X86::BI__builtin_ia32_reduceph512_mask: 4607 case X86::BI__builtin_ia32_prold512: 4608 case X86::BI__builtin_ia32_prolq512: 4609 case X86::BI__builtin_ia32_prold128: 4610 case X86::BI__builtin_ia32_prold256: 4611 case X86::BI__builtin_ia32_prolq128: 4612 case X86::BI__builtin_ia32_prolq256: 4613 case X86::BI__builtin_ia32_prord512: 4614 case X86::BI__builtin_ia32_prorq512: 4615 case X86::BI__builtin_ia32_prord128: 4616 case X86::BI__builtin_ia32_prord256: 4617 case X86::BI__builtin_ia32_prorq128: 4618 case X86::BI__builtin_ia32_prorq256: 4619 case X86::BI__builtin_ia32_fpclasspd128_mask: 4620 case X86::BI__builtin_ia32_fpclasspd256_mask: 4621 case X86::BI__builtin_ia32_fpclassps128_mask: 4622 case X86::BI__builtin_ia32_fpclassps256_mask: 4623 case X86::BI__builtin_ia32_fpclassps512_mask: 4624 case X86::BI__builtin_ia32_fpclasspd512_mask: 4625 case X86::BI__builtin_ia32_fpclassph128_mask: 4626 case X86::BI__builtin_ia32_fpclassph256_mask: 4627 case X86::BI__builtin_ia32_fpclassph512_mask: 4628 case X86::BI__builtin_ia32_fpclasssd_mask: 4629 case X86::BI__builtin_ia32_fpclassss_mask: 4630 case X86::BI__builtin_ia32_fpclasssh_mask: 4631 case X86::BI__builtin_ia32_pslldqi128_byteshift: 4632 case X86::BI__builtin_ia32_pslldqi256_byteshift: 4633 case X86::BI__builtin_ia32_pslldqi512_byteshift: 4634 case X86::BI__builtin_ia32_psrldqi128_byteshift: 4635 case X86::BI__builtin_ia32_psrldqi256_byteshift: 4636 case X86::BI__builtin_ia32_psrldqi512_byteshift: 4637 case X86::BI__builtin_ia32_kshiftliqi: 4638 case X86::BI__builtin_ia32_kshiftlihi: 4639 case X86::BI__builtin_ia32_kshiftlisi: 4640 case X86::BI__builtin_ia32_kshiftlidi: 4641 case X86::BI__builtin_ia32_kshiftriqi: 4642 case X86::BI__builtin_ia32_kshiftrihi: 4643 case X86::BI__builtin_ia32_kshiftrisi: 4644 case X86::BI__builtin_ia32_kshiftridi: 4645 i = 1; l = 0; u = 255; 4646 break; 4647 case X86::BI__builtin_ia32_vperm2f128_pd256: 4648 case X86::BI__builtin_ia32_vperm2f128_ps256: 4649 case X86::BI__builtin_ia32_vperm2f128_si256: 4650 case X86::BI__builtin_ia32_permti256: 4651 case X86::BI__builtin_ia32_pblendw128: 4652 case X86::BI__builtin_ia32_pblendw256: 4653 case X86::BI__builtin_ia32_blendps256: 4654 case X86::BI__builtin_ia32_pblendd256: 4655 case X86::BI__builtin_ia32_palignr128: 4656 case X86::BI__builtin_ia32_palignr256: 4657 case X86::BI__builtin_ia32_palignr512: 4658 case X86::BI__builtin_ia32_alignq512: 4659 case X86::BI__builtin_ia32_alignd512: 4660 case X86::BI__builtin_ia32_alignd128: 4661 case X86::BI__builtin_ia32_alignd256: 4662 case X86::BI__builtin_ia32_alignq128: 4663 case X86::BI__builtin_ia32_alignq256: 4664 case X86::BI__builtin_ia32_vcomisd: 4665 case X86::BI__builtin_ia32_vcomiss: 4666 case X86::BI__builtin_ia32_shuf_f32x4: 4667 case X86::BI__builtin_ia32_shuf_f64x2: 4668 case X86::BI__builtin_ia32_shuf_i32x4: 4669 case X86::BI__builtin_ia32_shuf_i64x2: 4670 case X86::BI__builtin_ia32_shufpd512: 4671 case X86::BI__builtin_ia32_shufps: 4672 case X86::BI__builtin_ia32_shufps256: 4673 case X86::BI__builtin_ia32_shufps512: 4674 case X86::BI__builtin_ia32_dbpsadbw128: 4675 case X86::BI__builtin_ia32_dbpsadbw256: 4676 case X86::BI__builtin_ia32_dbpsadbw512: 4677 case X86::BI__builtin_ia32_vpshldd128: 4678 case X86::BI__builtin_ia32_vpshldd256: 4679 case X86::BI__builtin_ia32_vpshldd512: 4680 case X86::BI__builtin_ia32_vpshldq128: 4681 case X86::BI__builtin_ia32_vpshldq256: 4682 case X86::BI__builtin_ia32_vpshldq512: 4683 case X86::BI__builtin_ia32_vpshldw128: 4684 case X86::BI__builtin_ia32_vpshldw256: 4685 case X86::BI__builtin_ia32_vpshldw512: 4686 case X86::BI__builtin_ia32_vpshrdd128: 4687 case X86::BI__builtin_ia32_vpshrdd256: 4688 case X86::BI__builtin_ia32_vpshrdd512: 4689 case X86::BI__builtin_ia32_vpshrdq128: 4690 case X86::BI__builtin_ia32_vpshrdq256: 4691 case X86::BI__builtin_ia32_vpshrdq512: 4692 case X86::BI__builtin_ia32_vpshrdw128: 4693 case X86::BI__builtin_ia32_vpshrdw256: 4694 case X86::BI__builtin_ia32_vpshrdw512: 4695 i = 2; l = 0; u = 255; 4696 break; 4697 case X86::BI__builtin_ia32_fixupimmpd512_mask: 4698 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 4699 case X86::BI__builtin_ia32_fixupimmps512_mask: 4700 case X86::BI__builtin_ia32_fixupimmps512_maskz: 4701 case X86::BI__builtin_ia32_fixupimmsd_mask: 4702 case X86::BI__builtin_ia32_fixupimmsd_maskz: 4703 case X86::BI__builtin_ia32_fixupimmss_mask: 4704 case X86::BI__builtin_ia32_fixupimmss_maskz: 4705 case X86::BI__builtin_ia32_fixupimmpd128_mask: 4706 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 4707 case X86::BI__builtin_ia32_fixupimmpd256_mask: 4708 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4709 case X86::BI__builtin_ia32_fixupimmps128_mask: 4710 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4711 case X86::BI__builtin_ia32_fixupimmps256_mask: 4712 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4713 case X86::BI__builtin_ia32_pternlogd512_mask: 4714 case X86::BI__builtin_ia32_pternlogd512_maskz: 4715 case X86::BI__builtin_ia32_pternlogq512_mask: 4716 case X86::BI__builtin_ia32_pternlogq512_maskz: 4717 case X86::BI__builtin_ia32_pternlogd128_mask: 4718 case X86::BI__builtin_ia32_pternlogd128_maskz: 4719 case X86::BI__builtin_ia32_pternlogd256_mask: 4720 case X86::BI__builtin_ia32_pternlogd256_maskz: 4721 case X86::BI__builtin_ia32_pternlogq128_mask: 4722 case X86::BI__builtin_ia32_pternlogq128_maskz: 4723 case X86::BI__builtin_ia32_pternlogq256_mask: 4724 case X86::BI__builtin_ia32_pternlogq256_maskz: 4725 i = 3; l = 0; u = 255; 4726 break; 4727 case X86::BI__builtin_ia32_gatherpfdpd: 4728 case X86::BI__builtin_ia32_gatherpfdps: 4729 case X86::BI__builtin_ia32_gatherpfqpd: 4730 case X86::BI__builtin_ia32_gatherpfqps: 4731 case X86::BI__builtin_ia32_scatterpfdpd: 4732 case X86::BI__builtin_ia32_scatterpfdps: 4733 case X86::BI__builtin_ia32_scatterpfqpd: 4734 case X86::BI__builtin_ia32_scatterpfqps: 4735 i = 4; l = 2; u = 3; 4736 break; 4737 case X86::BI__builtin_ia32_reducesd_mask: 4738 case X86::BI__builtin_ia32_reducess_mask: 4739 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4740 case X86::BI__builtin_ia32_rndscaless_round_mask: 4741 case X86::BI__builtin_ia32_rndscalesh_round_mask: 4742 case X86::BI__builtin_ia32_reducesh_mask: 4743 i = 4; l = 0; u = 255; 4744 break; 4745 } 4746 4747 // Note that we don't force a hard error on the range check here, allowing 4748 // template-generated or macro-generated dead code to potentially have out-of- 4749 // range values. These need to code generate, but don't need to necessarily 4750 // make any sense. We use a warning that defaults to an error. 4751 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4752 } 4753 4754 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4755 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4756 /// Returns true when the format fits the function and the FormatStringInfo has 4757 /// been populated. 4758 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4759 FormatStringInfo *FSI) { 4760 FSI->HasVAListArg = Format->getFirstArg() == 0; 4761 FSI->FormatIdx = Format->getFormatIdx() - 1; 4762 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4763 4764 // The way the format attribute works in GCC, the implicit this argument 4765 // of member functions is counted. However, it doesn't appear in our own 4766 // lists, so decrement format_idx in that case. 4767 if (IsCXXMember) { 4768 if(FSI->FormatIdx == 0) 4769 return false; 4770 --FSI->FormatIdx; 4771 if (FSI->FirstDataArg != 0) 4772 --FSI->FirstDataArg; 4773 } 4774 return true; 4775 } 4776 4777 /// Checks if a the given expression evaluates to null. 4778 /// 4779 /// Returns true if the value evaluates to null. 4780 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4781 // If the expression has non-null type, it doesn't evaluate to null. 4782 if (auto nullability 4783 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4784 if (*nullability == NullabilityKind::NonNull) 4785 return false; 4786 } 4787 4788 // As a special case, transparent unions initialized with zero are 4789 // considered null for the purposes of the nonnull attribute. 4790 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4791 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4792 if (const CompoundLiteralExpr *CLE = 4793 dyn_cast<CompoundLiteralExpr>(Expr)) 4794 if (const InitListExpr *ILE = 4795 dyn_cast<InitListExpr>(CLE->getInitializer())) 4796 Expr = ILE->getInit(0); 4797 } 4798 4799 bool Result; 4800 return (!Expr->isValueDependent() && 4801 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4802 !Result); 4803 } 4804 4805 static void CheckNonNullArgument(Sema &S, 4806 const Expr *ArgExpr, 4807 SourceLocation CallSiteLoc) { 4808 if (CheckNonNullExpr(S, ArgExpr)) 4809 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4810 S.PDiag(diag::warn_null_arg) 4811 << ArgExpr->getSourceRange()); 4812 } 4813 4814 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4815 FormatStringInfo FSI; 4816 if ((GetFormatStringType(Format) == FST_NSString) && 4817 getFormatStringInfo(Format, false, &FSI)) { 4818 Idx = FSI.FormatIdx; 4819 return true; 4820 } 4821 return false; 4822 } 4823 4824 /// Diagnose use of %s directive in an NSString which is being passed 4825 /// as formatting string to formatting method. 4826 static void 4827 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4828 const NamedDecl *FDecl, 4829 Expr **Args, 4830 unsigned NumArgs) { 4831 unsigned Idx = 0; 4832 bool Format = false; 4833 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4834 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4835 Idx = 2; 4836 Format = true; 4837 } 4838 else 4839 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4840 if (S.GetFormatNSStringIdx(I, Idx)) { 4841 Format = true; 4842 break; 4843 } 4844 } 4845 if (!Format || NumArgs <= Idx) 4846 return; 4847 const Expr *FormatExpr = Args[Idx]; 4848 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4849 FormatExpr = CSCE->getSubExpr(); 4850 const StringLiteral *FormatString; 4851 if (const ObjCStringLiteral *OSL = 4852 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4853 FormatString = OSL->getString(); 4854 else 4855 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4856 if (!FormatString) 4857 return; 4858 if (S.FormatStringHasSArg(FormatString)) { 4859 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4860 << "%s" << 1 << 1; 4861 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4862 << FDecl->getDeclName(); 4863 } 4864 } 4865 4866 /// Determine whether the given type has a non-null nullability annotation. 4867 static bool isNonNullType(ASTContext &ctx, QualType type) { 4868 if (auto nullability = type->getNullability(ctx)) 4869 return *nullability == NullabilityKind::NonNull; 4870 4871 return false; 4872 } 4873 4874 static void CheckNonNullArguments(Sema &S, 4875 const NamedDecl *FDecl, 4876 const FunctionProtoType *Proto, 4877 ArrayRef<const Expr *> Args, 4878 SourceLocation CallSiteLoc) { 4879 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4880 4881 // Already checked by by constant evaluator. 4882 if (S.isConstantEvaluated()) 4883 return; 4884 // Check the attributes attached to the method/function itself. 4885 llvm::SmallBitVector NonNullArgs; 4886 if (FDecl) { 4887 // Handle the nonnull attribute on the function/method declaration itself. 4888 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4889 if (!NonNull->args_size()) { 4890 // Easy case: all pointer arguments are nonnull. 4891 for (const auto *Arg : Args) 4892 if (S.isValidPointerAttrType(Arg->getType())) 4893 CheckNonNullArgument(S, Arg, CallSiteLoc); 4894 return; 4895 } 4896 4897 for (const ParamIdx &Idx : NonNull->args()) { 4898 unsigned IdxAST = Idx.getASTIndex(); 4899 if (IdxAST >= Args.size()) 4900 continue; 4901 if (NonNullArgs.empty()) 4902 NonNullArgs.resize(Args.size()); 4903 NonNullArgs.set(IdxAST); 4904 } 4905 } 4906 } 4907 4908 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4909 // Handle the nonnull attribute on the parameters of the 4910 // function/method. 4911 ArrayRef<ParmVarDecl*> parms; 4912 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4913 parms = FD->parameters(); 4914 else 4915 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4916 4917 unsigned ParamIndex = 0; 4918 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4919 I != E; ++I, ++ParamIndex) { 4920 const ParmVarDecl *PVD = *I; 4921 if (PVD->hasAttr<NonNullAttr>() || 4922 isNonNullType(S.Context, PVD->getType())) { 4923 if (NonNullArgs.empty()) 4924 NonNullArgs.resize(Args.size()); 4925 4926 NonNullArgs.set(ParamIndex); 4927 } 4928 } 4929 } else { 4930 // If we have a non-function, non-method declaration but no 4931 // function prototype, try to dig out the function prototype. 4932 if (!Proto) { 4933 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4934 QualType type = VD->getType().getNonReferenceType(); 4935 if (auto pointerType = type->getAs<PointerType>()) 4936 type = pointerType->getPointeeType(); 4937 else if (auto blockType = type->getAs<BlockPointerType>()) 4938 type = blockType->getPointeeType(); 4939 // FIXME: data member pointers? 4940 4941 // Dig out the function prototype, if there is one. 4942 Proto = type->getAs<FunctionProtoType>(); 4943 } 4944 } 4945 4946 // Fill in non-null argument information from the nullability 4947 // information on the parameter types (if we have them). 4948 if (Proto) { 4949 unsigned Index = 0; 4950 for (auto paramType : Proto->getParamTypes()) { 4951 if (isNonNullType(S.Context, paramType)) { 4952 if (NonNullArgs.empty()) 4953 NonNullArgs.resize(Args.size()); 4954 4955 NonNullArgs.set(Index); 4956 } 4957 4958 ++Index; 4959 } 4960 } 4961 } 4962 4963 // Check for non-null arguments. 4964 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4965 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4966 if (NonNullArgs[ArgIndex]) 4967 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4968 } 4969 } 4970 4971 /// Warn if a pointer or reference argument passed to a function points to an 4972 /// object that is less aligned than the parameter. This can happen when 4973 /// creating a typedef with a lower alignment than the original type and then 4974 /// calling functions defined in terms of the original type. 4975 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, 4976 StringRef ParamName, QualType ArgTy, 4977 QualType ParamTy) { 4978 4979 // If a function accepts a pointer or reference type 4980 if (!ParamTy->isPointerType() && !ParamTy->isReferenceType()) 4981 return; 4982 4983 // If the parameter is a pointer type, get the pointee type for the 4984 // argument too. If the parameter is a reference type, don't try to get 4985 // the pointee type for the argument. 4986 if (ParamTy->isPointerType()) 4987 ArgTy = ArgTy->getPointeeType(); 4988 4989 // Remove reference or pointer 4990 ParamTy = ParamTy->getPointeeType(); 4991 4992 // Find expected alignment, and the actual alignment of the passed object. 4993 // getTypeAlignInChars requires complete types 4994 if (ArgTy.isNull() || ParamTy->isIncompleteType() || 4995 ArgTy->isIncompleteType() || ParamTy->isUndeducedType() || 4996 ArgTy->isUndeducedType()) 4997 return; 4998 4999 CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy); 5000 CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy); 5001 5002 // If the argument is less aligned than the parameter, there is a 5003 // potential alignment issue. 5004 if (ArgAlign < ParamAlign) 5005 Diag(Loc, diag::warn_param_mismatched_alignment) 5006 << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity() 5007 << ParamName << FDecl; 5008 } 5009 5010 /// Handles the checks for format strings, non-POD arguments to vararg 5011 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 5012 /// attributes. 5013 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 5014 const Expr *ThisArg, ArrayRef<const Expr *> Args, 5015 bool IsMemberFunction, SourceLocation Loc, 5016 SourceRange Range, VariadicCallType CallType) { 5017 // FIXME: We should check as much as we can in the template definition. 5018 if (CurContext->isDependentContext()) 5019 return; 5020 5021 // Printf and scanf checking. 5022 llvm::SmallBitVector CheckedVarArgs; 5023 if (FDecl) { 5024 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 5025 // Only create vector if there are format attributes. 5026 CheckedVarArgs.resize(Args.size()); 5027 5028 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 5029 CheckedVarArgs); 5030 } 5031 } 5032 5033 // Refuse POD arguments that weren't caught by the format string 5034 // checks above. 5035 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 5036 if (CallType != VariadicDoesNotApply && 5037 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 5038 unsigned NumParams = Proto ? Proto->getNumParams() 5039 : FDecl && isa<FunctionDecl>(FDecl) 5040 ? cast<FunctionDecl>(FDecl)->getNumParams() 5041 : FDecl && isa<ObjCMethodDecl>(FDecl) 5042 ? cast<ObjCMethodDecl>(FDecl)->param_size() 5043 : 0; 5044 5045 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 5046 // Args[ArgIdx] can be null in malformed code. 5047 if (const Expr *Arg = Args[ArgIdx]) { 5048 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 5049 checkVariadicArgument(Arg, CallType); 5050 } 5051 } 5052 } 5053 5054 if (FDecl || Proto) { 5055 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 5056 5057 // Type safety checking. 5058 if (FDecl) { 5059 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 5060 CheckArgumentWithTypeTag(I, Args, Loc); 5061 } 5062 } 5063 5064 // Check that passed arguments match the alignment of original arguments. 5065 // Try to get the missing prototype from the declaration. 5066 if (!Proto && FDecl) { 5067 const auto *FT = FDecl->getFunctionType(); 5068 if (isa_and_nonnull<FunctionProtoType>(FT)) 5069 Proto = cast<FunctionProtoType>(FDecl->getFunctionType()); 5070 } 5071 if (Proto) { 5072 // For variadic functions, we may have more args than parameters. 5073 // For some K&R functions, we may have less args than parameters. 5074 const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size()); 5075 for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) { 5076 // Args[ArgIdx] can be null in malformed code. 5077 if (const Expr *Arg = Args[ArgIdx]) { 5078 if (Arg->containsErrors()) 5079 continue; 5080 5081 QualType ParamTy = Proto->getParamType(ArgIdx); 5082 QualType ArgTy = Arg->getType(); 5083 CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1), 5084 ArgTy, ParamTy); 5085 } 5086 } 5087 } 5088 5089 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 5090 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 5091 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 5092 if (!Arg->isValueDependent()) { 5093 Expr::EvalResult Align; 5094 if (Arg->EvaluateAsInt(Align, Context)) { 5095 const llvm::APSInt &I = Align.Val.getInt(); 5096 if (!I.isPowerOf2()) 5097 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 5098 << Arg->getSourceRange(); 5099 5100 if (I > Sema::MaximumAlignment) 5101 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 5102 << Arg->getSourceRange() << Sema::MaximumAlignment; 5103 } 5104 } 5105 } 5106 5107 if (FD) 5108 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 5109 } 5110 5111 /// CheckConstructorCall - Check a constructor call for correctness and safety 5112 /// properties not enforced by the C type system. 5113 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, 5114 ArrayRef<const Expr *> Args, 5115 const FunctionProtoType *Proto, 5116 SourceLocation Loc) { 5117 VariadicCallType CallType = 5118 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 5119 5120 auto *Ctor = cast<CXXConstructorDecl>(FDecl); 5121 CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType), 5122 Context.getPointerType(Ctor->getThisObjectType())); 5123 5124 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 5125 Loc, SourceRange(), CallType); 5126 } 5127 5128 /// CheckFunctionCall - Check a direct function call for various correctness 5129 /// and safety properties not strictly enforced by the C type system. 5130 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 5131 const FunctionProtoType *Proto) { 5132 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 5133 isa<CXXMethodDecl>(FDecl); 5134 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 5135 IsMemberOperatorCall; 5136 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 5137 TheCall->getCallee()); 5138 Expr** Args = TheCall->getArgs(); 5139 unsigned NumArgs = TheCall->getNumArgs(); 5140 5141 Expr *ImplicitThis = nullptr; 5142 if (IsMemberOperatorCall) { 5143 // If this is a call to a member operator, hide the first argument 5144 // from checkCall. 5145 // FIXME: Our choice of AST representation here is less than ideal. 5146 ImplicitThis = Args[0]; 5147 ++Args; 5148 --NumArgs; 5149 } else if (IsMemberFunction) 5150 ImplicitThis = 5151 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 5152 5153 if (ImplicitThis) { 5154 // ImplicitThis may or may not be a pointer, depending on whether . or -> is 5155 // used. 5156 QualType ThisType = ImplicitThis->getType(); 5157 if (!ThisType->isPointerType()) { 5158 assert(!ThisType->isReferenceType()); 5159 ThisType = Context.getPointerType(ThisType); 5160 } 5161 5162 QualType ThisTypeFromDecl = 5163 Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType()); 5164 5165 CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType, 5166 ThisTypeFromDecl); 5167 } 5168 5169 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 5170 IsMemberFunction, TheCall->getRParenLoc(), 5171 TheCall->getCallee()->getSourceRange(), CallType); 5172 5173 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 5174 // None of the checks below are needed for functions that don't have 5175 // simple names (e.g., C++ conversion functions). 5176 if (!FnInfo) 5177 return false; 5178 5179 CheckTCBEnforcement(TheCall, FDecl); 5180 5181 CheckAbsoluteValueFunction(TheCall, FDecl); 5182 CheckMaxUnsignedZero(TheCall, FDecl); 5183 5184 if (getLangOpts().ObjC) 5185 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 5186 5187 unsigned CMId = FDecl->getMemoryFunctionKind(); 5188 5189 // Handle memory setting and copying functions. 5190 switch (CMId) { 5191 case 0: 5192 return false; 5193 case Builtin::BIstrlcpy: // fallthrough 5194 case Builtin::BIstrlcat: 5195 CheckStrlcpycatArguments(TheCall, FnInfo); 5196 break; 5197 case Builtin::BIstrncat: 5198 CheckStrncatArguments(TheCall, FnInfo); 5199 break; 5200 case Builtin::BIfree: 5201 CheckFreeArguments(TheCall); 5202 break; 5203 default: 5204 CheckMemaccessArguments(TheCall, CMId, FnInfo); 5205 } 5206 5207 return false; 5208 } 5209 5210 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 5211 ArrayRef<const Expr *> Args) { 5212 VariadicCallType CallType = 5213 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 5214 5215 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 5216 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 5217 CallType); 5218 5219 return false; 5220 } 5221 5222 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 5223 const FunctionProtoType *Proto) { 5224 QualType Ty; 5225 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 5226 Ty = V->getType().getNonReferenceType(); 5227 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 5228 Ty = F->getType().getNonReferenceType(); 5229 else 5230 return false; 5231 5232 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 5233 !Ty->isFunctionProtoType()) 5234 return false; 5235 5236 VariadicCallType CallType; 5237 if (!Proto || !Proto->isVariadic()) { 5238 CallType = VariadicDoesNotApply; 5239 } else if (Ty->isBlockPointerType()) { 5240 CallType = VariadicBlock; 5241 } else { // Ty->isFunctionPointerType() 5242 CallType = VariadicFunction; 5243 } 5244 5245 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 5246 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5247 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5248 TheCall->getCallee()->getSourceRange(), CallType); 5249 5250 return false; 5251 } 5252 5253 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 5254 /// such as function pointers returned from functions. 5255 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 5256 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 5257 TheCall->getCallee()); 5258 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 5259 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 5260 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 5261 TheCall->getCallee()->getSourceRange(), CallType); 5262 5263 return false; 5264 } 5265 5266 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 5267 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 5268 return false; 5269 5270 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 5271 switch (Op) { 5272 case AtomicExpr::AO__c11_atomic_init: 5273 case AtomicExpr::AO__opencl_atomic_init: 5274 llvm_unreachable("There is no ordering argument for an init"); 5275 5276 case AtomicExpr::AO__c11_atomic_load: 5277 case AtomicExpr::AO__opencl_atomic_load: 5278 case AtomicExpr::AO__atomic_load_n: 5279 case AtomicExpr::AO__atomic_load: 5280 return OrderingCABI != llvm::AtomicOrderingCABI::release && 5281 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5282 5283 case AtomicExpr::AO__c11_atomic_store: 5284 case AtomicExpr::AO__opencl_atomic_store: 5285 case AtomicExpr::AO__atomic_store: 5286 case AtomicExpr::AO__atomic_store_n: 5287 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 5288 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 5289 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 5290 5291 default: 5292 return true; 5293 } 5294 } 5295 5296 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 5297 AtomicExpr::AtomicOp Op) { 5298 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 5299 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5300 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 5301 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 5302 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 5303 Op); 5304 } 5305 5306 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 5307 SourceLocation RParenLoc, MultiExprArg Args, 5308 AtomicExpr::AtomicOp Op, 5309 AtomicArgumentOrder ArgOrder) { 5310 // All the non-OpenCL operations take one of the following forms. 5311 // The OpenCL operations take the __c11 forms with one extra argument for 5312 // synchronization scope. 5313 enum { 5314 // C __c11_atomic_init(A *, C) 5315 Init, 5316 5317 // C __c11_atomic_load(A *, int) 5318 Load, 5319 5320 // void __atomic_load(A *, CP, int) 5321 LoadCopy, 5322 5323 // void __atomic_store(A *, CP, int) 5324 Copy, 5325 5326 // C __c11_atomic_add(A *, M, int) 5327 Arithmetic, 5328 5329 // C __atomic_exchange_n(A *, CP, int) 5330 Xchg, 5331 5332 // void __atomic_exchange(A *, C *, CP, int) 5333 GNUXchg, 5334 5335 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 5336 C11CmpXchg, 5337 5338 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 5339 GNUCmpXchg 5340 } Form = Init; 5341 5342 const unsigned NumForm = GNUCmpXchg + 1; 5343 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 5344 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 5345 // where: 5346 // C is an appropriate type, 5347 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 5348 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 5349 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 5350 // the int parameters are for orderings. 5351 5352 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 5353 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 5354 "need to update code for modified forms"); 5355 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 5356 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 5357 AtomicExpr::AO__atomic_load, 5358 "need to update code for modified C11 atomics"); 5359 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 5360 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 5361 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 5362 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 5363 IsOpenCL; 5364 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 5365 Op == AtomicExpr::AO__atomic_store_n || 5366 Op == AtomicExpr::AO__atomic_exchange_n || 5367 Op == AtomicExpr::AO__atomic_compare_exchange_n; 5368 bool IsAddSub = false; 5369 5370 switch (Op) { 5371 case AtomicExpr::AO__c11_atomic_init: 5372 case AtomicExpr::AO__opencl_atomic_init: 5373 Form = Init; 5374 break; 5375 5376 case AtomicExpr::AO__c11_atomic_load: 5377 case AtomicExpr::AO__opencl_atomic_load: 5378 case AtomicExpr::AO__atomic_load_n: 5379 Form = Load; 5380 break; 5381 5382 case AtomicExpr::AO__atomic_load: 5383 Form = LoadCopy; 5384 break; 5385 5386 case AtomicExpr::AO__c11_atomic_store: 5387 case AtomicExpr::AO__opencl_atomic_store: 5388 case AtomicExpr::AO__atomic_store: 5389 case AtomicExpr::AO__atomic_store_n: 5390 Form = Copy; 5391 break; 5392 5393 case AtomicExpr::AO__c11_atomic_fetch_add: 5394 case AtomicExpr::AO__c11_atomic_fetch_sub: 5395 case AtomicExpr::AO__opencl_atomic_fetch_add: 5396 case AtomicExpr::AO__opencl_atomic_fetch_sub: 5397 case AtomicExpr::AO__atomic_fetch_add: 5398 case AtomicExpr::AO__atomic_fetch_sub: 5399 case AtomicExpr::AO__atomic_add_fetch: 5400 case AtomicExpr::AO__atomic_sub_fetch: 5401 IsAddSub = true; 5402 Form = Arithmetic; 5403 break; 5404 case AtomicExpr::AO__c11_atomic_fetch_and: 5405 case AtomicExpr::AO__c11_atomic_fetch_or: 5406 case AtomicExpr::AO__c11_atomic_fetch_xor: 5407 case AtomicExpr::AO__opencl_atomic_fetch_and: 5408 case AtomicExpr::AO__opencl_atomic_fetch_or: 5409 case AtomicExpr::AO__opencl_atomic_fetch_xor: 5410 case AtomicExpr::AO__atomic_fetch_and: 5411 case AtomicExpr::AO__atomic_fetch_or: 5412 case AtomicExpr::AO__atomic_fetch_xor: 5413 case AtomicExpr::AO__atomic_fetch_nand: 5414 case AtomicExpr::AO__atomic_and_fetch: 5415 case AtomicExpr::AO__atomic_or_fetch: 5416 case AtomicExpr::AO__atomic_xor_fetch: 5417 case AtomicExpr::AO__atomic_nand_fetch: 5418 Form = Arithmetic; 5419 break; 5420 case AtomicExpr::AO__c11_atomic_fetch_min: 5421 case AtomicExpr::AO__c11_atomic_fetch_max: 5422 case AtomicExpr::AO__opencl_atomic_fetch_min: 5423 case AtomicExpr::AO__opencl_atomic_fetch_max: 5424 case AtomicExpr::AO__atomic_min_fetch: 5425 case AtomicExpr::AO__atomic_max_fetch: 5426 case AtomicExpr::AO__atomic_fetch_min: 5427 case AtomicExpr::AO__atomic_fetch_max: 5428 Form = Arithmetic; 5429 break; 5430 5431 case AtomicExpr::AO__c11_atomic_exchange: 5432 case AtomicExpr::AO__opencl_atomic_exchange: 5433 case AtomicExpr::AO__atomic_exchange_n: 5434 Form = Xchg; 5435 break; 5436 5437 case AtomicExpr::AO__atomic_exchange: 5438 Form = GNUXchg; 5439 break; 5440 5441 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 5442 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 5443 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 5444 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 5445 Form = C11CmpXchg; 5446 break; 5447 5448 case AtomicExpr::AO__atomic_compare_exchange: 5449 case AtomicExpr::AO__atomic_compare_exchange_n: 5450 Form = GNUCmpXchg; 5451 break; 5452 } 5453 5454 unsigned AdjustedNumArgs = NumArgs[Form]; 5455 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 5456 ++AdjustedNumArgs; 5457 // Check we have the right number of arguments. 5458 if (Args.size() < AdjustedNumArgs) { 5459 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 5460 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5461 << ExprRange; 5462 return ExprError(); 5463 } else if (Args.size() > AdjustedNumArgs) { 5464 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 5465 diag::err_typecheck_call_too_many_args) 5466 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 5467 << ExprRange; 5468 return ExprError(); 5469 } 5470 5471 // Inspect the first argument of the atomic operation. 5472 Expr *Ptr = Args[0]; 5473 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 5474 if (ConvertedPtr.isInvalid()) 5475 return ExprError(); 5476 5477 Ptr = ConvertedPtr.get(); 5478 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 5479 if (!pointerType) { 5480 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 5481 << Ptr->getType() << Ptr->getSourceRange(); 5482 return ExprError(); 5483 } 5484 5485 // For a __c11 builtin, this should be a pointer to an _Atomic type. 5486 QualType AtomTy = pointerType->getPointeeType(); // 'A' 5487 QualType ValType = AtomTy; // 'C' 5488 if (IsC11) { 5489 if (!AtomTy->isAtomicType()) { 5490 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 5491 << Ptr->getType() << Ptr->getSourceRange(); 5492 return ExprError(); 5493 } 5494 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 5495 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 5496 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 5497 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 5498 << Ptr->getSourceRange(); 5499 return ExprError(); 5500 } 5501 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 5502 } else if (Form != Load && Form != LoadCopy) { 5503 if (ValType.isConstQualified()) { 5504 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 5505 << Ptr->getType() << Ptr->getSourceRange(); 5506 return ExprError(); 5507 } 5508 } 5509 5510 // For an arithmetic operation, the implied arithmetic must be well-formed. 5511 if (Form == Arithmetic) { 5512 // gcc does not enforce these rules for GNU atomics, but we do so for 5513 // sanity. 5514 auto IsAllowedValueType = [&](QualType ValType) { 5515 if (ValType->isIntegerType()) 5516 return true; 5517 if (ValType->isPointerType()) 5518 return true; 5519 if (!ValType->isFloatingType()) 5520 return false; 5521 // LLVM Parser does not allow atomicrmw with x86_fp80 type. 5522 if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) && 5523 &Context.getTargetInfo().getLongDoubleFormat() == 5524 &llvm::APFloat::x87DoubleExtended()) 5525 return false; 5526 return true; 5527 }; 5528 if (IsAddSub && !IsAllowedValueType(ValType)) { 5529 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp) 5530 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5531 return ExprError(); 5532 } 5533 if (!IsAddSub && !ValType->isIntegerType()) { 5534 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 5535 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5536 return ExprError(); 5537 } 5538 if (IsC11 && ValType->isPointerType() && 5539 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 5540 diag::err_incomplete_type)) { 5541 return ExprError(); 5542 } 5543 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 5544 // For __atomic_*_n operations, the value type must be a scalar integral or 5545 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 5546 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 5547 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 5548 return ExprError(); 5549 } 5550 5551 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 5552 !AtomTy->isScalarType()) { 5553 // For GNU atomics, require a trivially-copyable type. This is not part of 5554 // the GNU atomics specification, but we enforce it for sanity. 5555 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 5556 << Ptr->getType() << Ptr->getSourceRange(); 5557 return ExprError(); 5558 } 5559 5560 switch (ValType.getObjCLifetime()) { 5561 case Qualifiers::OCL_None: 5562 case Qualifiers::OCL_ExplicitNone: 5563 // okay 5564 break; 5565 5566 case Qualifiers::OCL_Weak: 5567 case Qualifiers::OCL_Strong: 5568 case Qualifiers::OCL_Autoreleasing: 5569 // FIXME: Can this happen? By this point, ValType should be known 5570 // to be trivially copyable. 5571 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 5572 << ValType << Ptr->getSourceRange(); 5573 return ExprError(); 5574 } 5575 5576 // All atomic operations have an overload which takes a pointer to a volatile 5577 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 5578 // into the result or the other operands. Similarly atomic_load takes a 5579 // pointer to a const 'A'. 5580 ValType.removeLocalVolatile(); 5581 ValType.removeLocalConst(); 5582 QualType ResultType = ValType; 5583 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 5584 Form == Init) 5585 ResultType = Context.VoidTy; 5586 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 5587 ResultType = Context.BoolTy; 5588 5589 // The type of a parameter passed 'by value'. In the GNU atomics, such 5590 // arguments are actually passed as pointers. 5591 QualType ByValType = ValType; // 'CP' 5592 bool IsPassedByAddress = false; 5593 if (!IsC11 && !IsN) { 5594 ByValType = Ptr->getType(); 5595 IsPassedByAddress = true; 5596 } 5597 5598 SmallVector<Expr *, 5> APIOrderedArgs; 5599 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 5600 APIOrderedArgs.push_back(Args[0]); 5601 switch (Form) { 5602 case Init: 5603 case Load: 5604 APIOrderedArgs.push_back(Args[1]); // Val1/Order 5605 break; 5606 case LoadCopy: 5607 case Copy: 5608 case Arithmetic: 5609 case Xchg: 5610 APIOrderedArgs.push_back(Args[2]); // Val1 5611 APIOrderedArgs.push_back(Args[1]); // Order 5612 break; 5613 case GNUXchg: 5614 APIOrderedArgs.push_back(Args[2]); // Val1 5615 APIOrderedArgs.push_back(Args[3]); // Val2 5616 APIOrderedArgs.push_back(Args[1]); // Order 5617 break; 5618 case C11CmpXchg: 5619 APIOrderedArgs.push_back(Args[2]); // Val1 5620 APIOrderedArgs.push_back(Args[4]); // Val2 5621 APIOrderedArgs.push_back(Args[1]); // Order 5622 APIOrderedArgs.push_back(Args[3]); // OrderFail 5623 break; 5624 case GNUCmpXchg: 5625 APIOrderedArgs.push_back(Args[2]); // Val1 5626 APIOrderedArgs.push_back(Args[4]); // Val2 5627 APIOrderedArgs.push_back(Args[5]); // Weak 5628 APIOrderedArgs.push_back(Args[1]); // Order 5629 APIOrderedArgs.push_back(Args[3]); // OrderFail 5630 break; 5631 } 5632 } else 5633 APIOrderedArgs.append(Args.begin(), Args.end()); 5634 5635 // The first argument's non-CV pointer type is used to deduce the type of 5636 // subsequent arguments, except for: 5637 // - weak flag (always converted to bool) 5638 // - memory order (always converted to int) 5639 // - scope (always converted to int) 5640 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 5641 QualType Ty; 5642 if (i < NumVals[Form] + 1) { 5643 switch (i) { 5644 case 0: 5645 // The first argument is always a pointer. It has a fixed type. 5646 // It is always dereferenced, a nullptr is undefined. 5647 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5648 // Nothing else to do: we already know all we want about this pointer. 5649 continue; 5650 case 1: 5651 // The second argument is the non-atomic operand. For arithmetic, this 5652 // is always passed by value, and for a compare_exchange it is always 5653 // passed by address. For the rest, GNU uses by-address and C11 uses 5654 // by-value. 5655 assert(Form != Load); 5656 if (Form == Arithmetic && ValType->isPointerType()) 5657 Ty = Context.getPointerDiffType(); 5658 else if (Form == Init || Form == Arithmetic) 5659 Ty = ValType; 5660 else if (Form == Copy || Form == Xchg) { 5661 if (IsPassedByAddress) { 5662 // The value pointer is always dereferenced, a nullptr is undefined. 5663 CheckNonNullArgument(*this, APIOrderedArgs[i], 5664 ExprRange.getBegin()); 5665 } 5666 Ty = ByValType; 5667 } else { 5668 Expr *ValArg = APIOrderedArgs[i]; 5669 // The value pointer is always dereferenced, a nullptr is undefined. 5670 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 5671 LangAS AS = LangAS::Default; 5672 // Keep address space of non-atomic pointer type. 5673 if (const PointerType *PtrTy = 5674 ValArg->getType()->getAs<PointerType>()) { 5675 AS = PtrTy->getPointeeType().getAddressSpace(); 5676 } 5677 Ty = Context.getPointerType( 5678 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 5679 } 5680 break; 5681 case 2: 5682 // The third argument to compare_exchange / GNU exchange is the desired 5683 // value, either by-value (for the C11 and *_n variant) or as a pointer. 5684 if (IsPassedByAddress) 5685 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 5686 Ty = ByValType; 5687 break; 5688 case 3: 5689 // The fourth argument to GNU compare_exchange is a 'weak' flag. 5690 Ty = Context.BoolTy; 5691 break; 5692 } 5693 } else { 5694 // The order(s) and scope are always converted to int. 5695 Ty = Context.IntTy; 5696 } 5697 5698 InitializedEntity Entity = 5699 InitializedEntity::InitializeParameter(Context, Ty, false); 5700 ExprResult Arg = APIOrderedArgs[i]; 5701 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5702 if (Arg.isInvalid()) 5703 return true; 5704 APIOrderedArgs[i] = Arg.get(); 5705 } 5706 5707 // Permute the arguments into a 'consistent' order. 5708 SmallVector<Expr*, 5> SubExprs; 5709 SubExprs.push_back(Ptr); 5710 switch (Form) { 5711 case Init: 5712 // Note, AtomicExpr::getVal1() has a special case for this atomic. 5713 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5714 break; 5715 case Load: 5716 SubExprs.push_back(APIOrderedArgs[1]); // Order 5717 break; 5718 case LoadCopy: 5719 case Copy: 5720 case Arithmetic: 5721 case Xchg: 5722 SubExprs.push_back(APIOrderedArgs[2]); // Order 5723 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5724 break; 5725 case GNUXchg: 5726 // Note, AtomicExpr::getVal2() has a special case for this atomic. 5727 SubExprs.push_back(APIOrderedArgs[3]); // Order 5728 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5729 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5730 break; 5731 case C11CmpXchg: 5732 SubExprs.push_back(APIOrderedArgs[3]); // Order 5733 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5734 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 5735 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5736 break; 5737 case GNUCmpXchg: 5738 SubExprs.push_back(APIOrderedArgs[4]); // Order 5739 SubExprs.push_back(APIOrderedArgs[1]); // Val1 5740 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 5741 SubExprs.push_back(APIOrderedArgs[2]); // Val2 5742 SubExprs.push_back(APIOrderedArgs[3]); // Weak 5743 break; 5744 } 5745 5746 if (SubExprs.size() >= 2 && Form != Init) { 5747 if (Optional<llvm::APSInt> Result = 5748 SubExprs[1]->getIntegerConstantExpr(Context)) 5749 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 5750 Diag(SubExprs[1]->getBeginLoc(), 5751 diag::warn_atomic_op_has_invalid_memory_order) 5752 << SubExprs[1]->getSourceRange(); 5753 } 5754 5755 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 5756 auto *Scope = Args[Args.size() - 1]; 5757 if (Optional<llvm::APSInt> Result = 5758 Scope->getIntegerConstantExpr(Context)) { 5759 if (!ScopeModel->isValid(Result->getZExtValue())) 5760 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 5761 << Scope->getSourceRange(); 5762 } 5763 SubExprs.push_back(Scope); 5764 } 5765 5766 AtomicExpr *AE = new (Context) 5767 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 5768 5769 if ((Op == AtomicExpr::AO__c11_atomic_load || 5770 Op == AtomicExpr::AO__c11_atomic_store || 5771 Op == AtomicExpr::AO__opencl_atomic_load || 5772 Op == AtomicExpr::AO__opencl_atomic_store ) && 5773 Context.AtomicUsesUnsupportedLibcall(AE)) 5774 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 5775 << ((Op == AtomicExpr::AO__c11_atomic_load || 5776 Op == AtomicExpr::AO__opencl_atomic_load) 5777 ? 0 5778 : 1); 5779 5780 if (ValType->isExtIntType()) { 5781 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit); 5782 return ExprError(); 5783 } 5784 5785 return AE; 5786 } 5787 5788 /// checkBuiltinArgument - Given a call to a builtin function, perform 5789 /// normal type-checking on the given argument, updating the call in 5790 /// place. This is useful when a builtin function requires custom 5791 /// type-checking for some of its arguments but not necessarily all of 5792 /// them. 5793 /// 5794 /// Returns true on error. 5795 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 5796 FunctionDecl *Fn = E->getDirectCallee(); 5797 assert(Fn && "builtin call without direct callee!"); 5798 5799 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 5800 InitializedEntity Entity = 5801 InitializedEntity::InitializeParameter(S.Context, Param); 5802 5803 ExprResult Arg = E->getArg(0); 5804 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 5805 if (Arg.isInvalid()) 5806 return true; 5807 5808 E->setArg(ArgIndex, Arg.get()); 5809 return false; 5810 } 5811 5812 /// We have a call to a function like __sync_fetch_and_add, which is an 5813 /// overloaded function based on the pointer type of its first argument. 5814 /// The main BuildCallExpr routines have already promoted the types of 5815 /// arguments because all of these calls are prototyped as void(...). 5816 /// 5817 /// This function goes through and does final semantic checking for these 5818 /// builtins, as well as generating any warnings. 5819 ExprResult 5820 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 5821 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 5822 Expr *Callee = TheCall->getCallee(); 5823 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 5824 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5825 5826 // Ensure that we have at least one argument to do type inference from. 5827 if (TheCall->getNumArgs() < 1) { 5828 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5829 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5830 return ExprError(); 5831 } 5832 5833 // Inspect the first argument of the atomic builtin. This should always be 5834 // a pointer type, whose element is an integral scalar or pointer type. 5835 // Because it is a pointer type, we don't have to worry about any implicit 5836 // casts here. 5837 // FIXME: We don't allow floating point scalars as input. 5838 Expr *FirstArg = TheCall->getArg(0); 5839 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5840 if (FirstArgResult.isInvalid()) 5841 return ExprError(); 5842 FirstArg = FirstArgResult.get(); 5843 TheCall->setArg(0, FirstArg); 5844 5845 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5846 if (!pointerType) { 5847 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5848 << FirstArg->getType() << FirstArg->getSourceRange(); 5849 return ExprError(); 5850 } 5851 5852 QualType ValType = pointerType->getPointeeType(); 5853 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5854 !ValType->isBlockPointerType()) { 5855 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5856 << FirstArg->getType() << FirstArg->getSourceRange(); 5857 return ExprError(); 5858 } 5859 5860 if (ValType.isConstQualified()) { 5861 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5862 << FirstArg->getType() << FirstArg->getSourceRange(); 5863 return ExprError(); 5864 } 5865 5866 switch (ValType.getObjCLifetime()) { 5867 case Qualifiers::OCL_None: 5868 case Qualifiers::OCL_ExplicitNone: 5869 // okay 5870 break; 5871 5872 case Qualifiers::OCL_Weak: 5873 case Qualifiers::OCL_Strong: 5874 case Qualifiers::OCL_Autoreleasing: 5875 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5876 << ValType << FirstArg->getSourceRange(); 5877 return ExprError(); 5878 } 5879 5880 // Strip any qualifiers off ValType. 5881 ValType = ValType.getUnqualifiedType(); 5882 5883 // The majority of builtins return a value, but a few have special return 5884 // types, so allow them to override appropriately below. 5885 QualType ResultType = ValType; 5886 5887 // We need to figure out which concrete builtin this maps onto. For example, 5888 // __sync_fetch_and_add with a 2 byte object turns into 5889 // __sync_fetch_and_add_2. 5890 #define BUILTIN_ROW(x) \ 5891 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5892 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5893 5894 static const unsigned BuiltinIndices[][5] = { 5895 BUILTIN_ROW(__sync_fetch_and_add), 5896 BUILTIN_ROW(__sync_fetch_and_sub), 5897 BUILTIN_ROW(__sync_fetch_and_or), 5898 BUILTIN_ROW(__sync_fetch_and_and), 5899 BUILTIN_ROW(__sync_fetch_and_xor), 5900 BUILTIN_ROW(__sync_fetch_and_nand), 5901 5902 BUILTIN_ROW(__sync_add_and_fetch), 5903 BUILTIN_ROW(__sync_sub_and_fetch), 5904 BUILTIN_ROW(__sync_and_and_fetch), 5905 BUILTIN_ROW(__sync_or_and_fetch), 5906 BUILTIN_ROW(__sync_xor_and_fetch), 5907 BUILTIN_ROW(__sync_nand_and_fetch), 5908 5909 BUILTIN_ROW(__sync_val_compare_and_swap), 5910 BUILTIN_ROW(__sync_bool_compare_and_swap), 5911 BUILTIN_ROW(__sync_lock_test_and_set), 5912 BUILTIN_ROW(__sync_lock_release), 5913 BUILTIN_ROW(__sync_swap) 5914 }; 5915 #undef BUILTIN_ROW 5916 5917 // Determine the index of the size. 5918 unsigned SizeIndex; 5919 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5920 case 1: SizeIndex = 0; break; 5921 case 2: SizeIndex = 1; break; 5922 case 4: SizeIndex = 2; break; 5923 case 8: SizeIndex = 3; break; 5924 case 16: SizeIndex = 4; break; 5925 default: 5926 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5927 << FirstArg->getType() << FirstArg->getSourceRange(); 5928 return ExprError(); 5929 } 5930 5931 // Each of these builtins has one pointer argument, followed by some number of 5932 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5933 // that we ignore. Find out which row of BuiltinIndices to read from as well 5934 // as the number of fixed args. 5935 unsigned BuiltinID = FDecl->getBuiltinID(); 5936 unsigned BuiltinIndex, NumFixed = 1; 5937 bool WarnAboutSemanticsChange = false; 5938 switch (BuiltinID) { 5939 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5940 case Builtin::BI__sync_fetch_and_add: 5941 case Builtin::BI__sync_fetch_and_add_1: 5942 case Builtin::BI__sync_fetch_and_add_2: 5943 case Builtin::BI__sync_fetch_and_add_4: 5944 case Builtin::BI__sync_fetch_and_add_8: 5945 case Builtin::BI__sync_fetch_and_add_16: 5946 BuiltinIndex = 0; 5947 break; 5948 5949 case Builtin::BI__sync_fetch_and_sub: 5950 case Builtin::BI__sync_fetch_and_sub_1: 5951 case Builtin::BI__sync_fetch_and_sub_2: 5952 case Builtin::BI__sync_fetch_and_sub_4: 5953 case Builtin::BI__sync_fetch_and_sub_8: 5954 case Builtin::BI__sync_fetch_and_sub_16: 5955 BuiltinIndex = 1; 5956 break; 5957 5958 case Builtin::BI__sync_fetch_and_or: 5959 case Builtin::BI__sync_fetch_and_or_1: 5960 case Builtin::BI__sync_fetch_and_or_2: 5961 case Builtin::BI__sync_fetch_and_or_4: 5962 case Builtin::BI__sync_fetch_and_or_8: 5963 case Builtin::BI__sync_fetch_and_or_16: 5964 BuiltinIndex = 2; 5965 break; 5966 5967 case Builtin::BI__sync_fetch_and_and: 5968 case Builtin::BI__sync_fetch_and_and_1: 5969 case Builtin::BI__sync_fetch_and_and_2: 5970 case Builtin::BI__sync_fetch_and_and_4: 5971 case Builtin::BI__sync_fetch_and_and_8: 5972 case Builtin::BI__sync_fetch_and_and_16: 5973 BuiltinIndex = 3; 5974 break; 5975 5976 case Builtin::BI__sync_fetch_and_xor: 5977 case Builtin::BI__sync_fetch_and_xor_1: 5978 case Builtin::BI__sync_fetch_and_xor_2: 5979 case Builtin::BI__sync_fetch_and_xor_4: 5980 case Builtin::BI__sync_fetch_and_xor_8: 5981 case Builtin::BI__sync_fetch_and_xor_16: 5982 BuiltinIndex = 4; 5983 break; 5984 5985 case Builtin::BI__sync_fetch_and_nand: 5986 case Builtin::BI__sync_fetch_and_nand_1: 5987 case Builtin::BI__sync_fetch_and_nand_2: 5988 case Builtin::BI__sync_fetch_and_nand_4: 5989 case Builtin::BI__sync_fetch_and_nand_8: 5990 case Builtin::BI__sync_fetch_and_nand_16: 5991 BuiltinIndex = 5; 5992 WarnAboutSemanticsChange = true; 5993 break; 5994 5995 case Builtin::BI__sync_add_and_fetch: 5996 case Builtin::BI__sync_add_and_fetch_1: 5997 case Builtin::BI__sync_add_and_fetch_2: 5998 case Builtin::BI__sync_add_and_fetch_4: 5999 case Builtin::BI__sync_add_and_fetch_8: 6000 case Builtin::BI__sync_add_and_fetch_16: 6001 BuiltinIndex = 6; 6002 break; 6003 6004 case Builtin::BI__sync_sub_and_fetch: 6005 case Builtin::BI__sync_sub_and_fetch_1: 6006 case Builtin::BI__sync_sub_and_fetch_2: 6007 case Builtin::BI__sync_sub_and_fetch_4: 6008 case Builtin::BI__sync_sub_and_fetch_8: 6009 case Builtin::BI__sync_sub_and_fetch_16: 6010 BuiltinIndex = 7; 6011 break; 6012 6013 case Builtin::BI__sync_and_and_fetch: 6014 case Builtin::BI__sync_and_and_fetch_1: 6015 case Builtin::BI__sync_and_and_fetch_2: 6016 case Builtin::BI__sync_and_and_fetch_4: 6017 case Builtin::BI__sync_and_and_fetch_8: 6018 case Builtin::BI__sync_and_and_fetch_16: 6019 BuiltinIndex = 8; 6020 break; 6021 6022 case Builtin::BI__sync_or_and_fetch: 6023 case Builtin::BI__sync_or_and_fetch_1: 6024 case Builtin::BI__sync_or_and_fetch_2: 6025 case Builtin::BI__sync_or_and_fetch_4: 6026 case Builtin::BI__sync_or_and_fetch_8: 6027 case Builtin::BI__sync_or_and_fetch_16: 6028 BuiltinIndex = 9; 6029 break; 6030 6031 case Builtin::BI__sync_xor_and_fetch: 6032 case Builtin::BI__sync_xor_and_fetch_1: 6033 case Builtin::BI__sync_xor_and_fetch_2: 6034 case Builtin::BI__sync_xor_and_fetch_4: 6035 case Builtin::BI__sync_xor_and_fetch_8: 6036 case Builtin::BI__sync_xor_and_fetch_16: 6037 BuiltinIndex = 10; 6038 break; 6039 6040 case Builtin::BI__sync_nand_and_fetch: 6041 case Builtin::BI__sync_nand_and_fetch_1: 6042 case Builtin::BI__sync_nand_and_fetch_2: 6043 case Builtin::BI__sync_nand_and_fetch_4: 6044 case Builtin::BI__sync_nand_and_fetch_8: 6045 case Builtin::BI__sync_nand_and_fetch_16: 6046 BuiltinIndex = 11; 6047 WarnAboutSemanticsChange = true; 6048 break; 6049 6050 case Builtin::BI__sync_val_compare_and_swap: 6051 case Builtin::BI__sync_val_compare_and_swap_1: 6052 case Builtin::BI__sync_val_compare_and_swap_2: 6053 case Builtin::BI__sync_val_compare_and_swap_4: 6054 case Builtin::BI__sync_val_compare_and_swap_8: 6055 case Builtin::BI__sync_val_compare_and_swap_16: 6056 BuiltinIndex = 12; 6057 NumFixed = 2; 6058 break; 6059 6060 case Builtin::BI__sync_bool_compare_and_swap: 6061 case Builtin::BI__sync_bool_compare_and_swap_1: 6062 case Builtin::BI__sync_bool_compare_and_swap_2: 6063 case Builtin::BI__sync_bool_compare_and_swap_4: 6064 case Builtin::BI__sync_bool_compare_and_swap_8: 6065 case Builtin::BI__sync_bool_compare_and_swap_16: 6066 BuiltinIndex = 13; 6067 NumFixed = 2; 6068 ResultType = Context.BoolTy; 6069 break; 6070 6071 case Builtin::BI__sync_lock_test_and_set: 6072 case Builtin::BI__sync_lock_test_and_set_1: 6073 case Builtin::BI__sync_lock_test_and_set_2: 6074 case Builtin::BI__sync_lock_test_and_set_4: 6075 case Builtin::BI__sync_lock_test_and_set_8: 6076 case Builtin::BI__sync_lock_test_and_set_16: 6077 BuiltinIndex = 14; 6078 break; 6079 6080 case Builtin::BI__sync_lock_release: 6081 case Builtin::BI__sync_lock_release_1: 6082 case Builtin::BI__sync_lock_release_2: 6083 case Builtin::BI__sync_lock_release_4: 6084 case Builtin::BI__sync_lock_release_8: 6085 case Builtin::BI__sync_lock_release_16: 6086 BuiltinIndex = 15; 6087 NumFixed = 0; 6088 ResultType = Context.VoidTy; 6089 break; 6090 6091 case Builtin::BI__sync_swap: 6092 case Builtin::BI__sync_swap_1: 6093 case Builtin::BI__sync_swap_2: 6094 case Builtin::BI__sync_swap_4: 6095 case Builtin::BI__sync_swap_8: 6096 case Builtin::BI__sync_swap_16: 6097 BuiltinIndex = 16; 6098 break; 6099 } 6100 6101 // Now that we know how many fixed arguments we expect, first check that we 6102 // have at least that many. 6103 if (TheCall->getNumArgs() < 1+NumFixed) { 6104 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 6105 << 0 << 1 + NumFixed << TheCall->getNumArgs() 6106 << Callee->getSourceRange(); 6107 return ExprError(); 6108 } 6109 6110 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 6111 << Callee->getSourceRange(); 6112 6113 if (WarnAboutSemanticsChange) { 6114 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 6115 << Callee->getSourceRange(); 6116 } 6117 6118 // Get the decl for the concrete builtin from this, we can tell what the 6119 // concrete integer type we should convert to is. 6120 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 6121 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 6122 FunctionDecl *NewBuiltinDecl; 6123 if (NewBuiltinID == BuiltinID) 6124 NewBuiltinDecl = FDecl; 6125 else { 6126 // Perform builtin lookup to avoid redeclaring it. 6127 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 6128 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 6129 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 6130 assert(Res.getFoundDecl()); 6131 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 6132 if (!NewBuiltinDecl) 6133 return ExprError(); 6134 } 6135 6136 // The first argument --- the pointer --- has a fixed type; we 6137 // deduce the types of the rest of the arguments accordingly. Walk 6138 // the remaining arguments, converting them to the deduced value type. 6139 for (unsigned i = 0; i != NumFixed; ++i) { 6140 ExprResult Arg = TheCall->getArg(i+1); 6141 6142 // GCC does an implicit conversion to the pointer or integer ValType. This 6143 // can fail in some cases (1i -> int**), check for this error case now. 6144 // Initialize the argument. 6145 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6146 ValType, /*consume*/ false); 6147 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6148 if (Arg.isInvalid()) 6149 return ExprError(); 6150 6151 // Okay, we have something that *can* be converted to the right type. Check 6152 // to see if there is a potentially weird extension going on here. This can 6153 // happen when you do an atomic operation on something like an char* and 6154 // pass in 42. The 42 gets converted to char. This is even more strange 6155 // for things like 45.123 -> char, etc. 6156 // FIXME: Do this check. 6157 TheCall->setArg(i+1, Arg.get()); 6158 } 6159 6160 // Create a new DeclRefExpr to refer to the new decl. 6161 DeclRefExpr *NewDRE = DeclRefExpr::Create( 6162 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 6163 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 6164 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 6165 6166 // Set the callee in the CallExpr. 6167 // FIXME: This loses syntactic information. 6168 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 6169 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 6170 CK_BuiltinFnToFnPtr); 6171 TheCall->setCallee(PromotedCall.get()); 6172 6173 // Change the result type of the call to match the original value type. This 6174 // is arbitrary, but the codegen for these builtins ins design to handle it 6175 // gracefully. 6176 TheCall->setType(ResultType); 6177 6178 // Prohibit use of _ExtInt with atomic builtins. 6179 // The arguments would have already been converted to the first argument's 6180 // type, so only need to check the first argument. 6181 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 6182 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 6183 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 6184 return ExprError(); 6185 } 6186 6187 return TheCallResult; 6188 } 6189 6190 /// SemaBuiltinNontemporalOverloaded - We have a call to 6191 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 6192 /// overloaded function based on the pointer type of its last argument. 6193 /// 6194 /// This function goes through and does final semantic checking for these 6195 /// builtins. 6196 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 6197 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 6198 DeclRefExpr *DRE = 6199 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6200 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6201 unsigned BuiltinID = FDecl->getBuiltinID(); 6202 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 6203 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 6204 "Unexpected nontemporal load/store builtin!"); 6205 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 6206 unsigned numArgs = isStore ? 2 : 1; 6207 6208 // Ensure that we have the proper number of arguments. 6209 if (checkArgCount(*this, TheCall, numArgs)) 6210 return ExprError(); 6211 6212 // Inspect the last argument of the nontemporal builtin. This should always 6213 // be a pointer type, from which we imply the type of the memory access. 6214 // Because it is a pointer type, we don't have to worry about any implicit 6215 // casts here. 6216 Expr *PointerArg = TheCall->getArg(numArgs - 1); 6217 ExprResult PointerArgResult = 6218 DefaultFunctionArrayLvalueConversion(PointerArg); 6219 6220 if (PointerArgResult.isInvalid()) 6221 return ExprError(); 6222 PointerArg = PointerArgResult.get(); 6223 TheCall->setArg(numArgs - 1, PointerArg); 6224 6225 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 6226 if (!pointerType) { 6227 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 6228 << PointerArg->getType() << PointerArg->getSourceRange(); 6229 return ExprError(); 6230 } 6231 6232 QualType ValType = pointerType->getPointeeType(); 6233 6234 // Strip any qualifiers off ValType. 6235 ValType = ValType.getUnqualifiedType(); 6236 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 6237 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 6238 !ValType->isVectorType()) { 6239 Diag(DRE->getBeginLoc(), 6240 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 6241 << PointerArg->getType() << PointerArg->getSourceRange(); 6242 return ExprError(); 6243 } 6244 6245 if (!isStore) { 6246 TheCall->setType(ValType); 6247 return TheCallResult; 6248 } 6249 6250 ExprResult ValArg = TheCall->getArg(0); 6251 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6252 Context, ValType, /*consume*/ false); 6253 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 6254 if (ValArg.isInvalid()) 6255 return ExprError(); 6256 6257 TheCall->setArg(0, ValArg.get()); 6258 TheCall->setType(Context.VoidTy); 6259 return TheCallResult; 6260 } 6261 6262 /// CheckObjCString - Checks that the argument to the builtin 6263 /// CFString constructor is correct 6264 /// Note: It might also make sense to do the UTF-16 conversion here (would 6265 /// simplify the backend). 6266 bool Sema::CheckObjCString(Expr *Arg) { 6267 Arg = Arg->IgnoreParenCasts(); 6268 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 6269 6270 if (!Literal || !Literal->isAscii()) { 6271 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 6272 << Arg->getSourceRange(); 6273 return true; 6274 } 6275 6276 if (Literal->containsNonAsciiOrNull()) { 6277 StringRef String = Literal->getString(); 6278 unsigned NumBytes = String.size(); 6279 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 6280 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 6281 llvm::UTF16 *ToPtr = &ToBuf[0]; 6282 6283 llvm::ConversionResult Result = 6284 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 6285 ToPtr + NumBytes, llvm::strictConversion); 6286 // Check for conversion failure. 6287 if (Result != llvm::conversionOK) 6288 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 6289 << Arg->getSourceRange(); 6290 } 6291 return false; 6292 } 6293 6294 /// CheckObjCString - Checks that the format string argument to the os_log() 6295 /// and os_trace() functions is correct, and converts it to const char *. 6296 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 6297 Arg = Arg->IgnoreParenCasts(); 6298 auto *Literal = dyn_cast<StringLiteral>(Arg); 6299 if (!Literal) { 6300 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 6301 Literal = ObjcLiteral->getString(); 6302 } 6303 } 6304 6305 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 6306 return ExprError( 6307 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 6308 << Arg->getSourceRange()); 6309 } 6310 6311 ExprResult Result(Literal); 6312 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 6313 InitializedEntity Entity = 6314 InitializedEntity::InitializeParameter(Context, ResultTy, false); 6315 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 6316 return Result; 6317 } 6318 6319 /// Check that the user is calling the appropriate va_start builtin for the 6320 /// target and calling convention. 6321 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 6322 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 6323 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 6324 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 6325 TT.getArch() == llvm::Triple::aarch64_32); 6326 bool IsWindows = TT.isOSWindows(); 6327 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 6328 if (IsX64 || IsAArch64) { 6329 CallingConv CC = CC_C; 6330 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 6331 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 6332 if (IsMSVAStart) { 6333 // Don't allow this in System V ABI functions. 6334 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 6335 return S.Diag(Fn->getBeginLoc(), 6336 diag::err_ms_va_start_used_in_sysv_function); 6337 } else { 6338 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 6339 // On x64 Windows, don't allow this in System V ABI functions. 6340 // (Yes, that means there's no corresponding way to support variadic 6341 // System V ABI functions on Windows.) 6342 if ((IsWindows && CC == CC_X86_64SysV) || 6343 (!IsWindows && CC == CC_Win64)) 6344 return S.Diag(Fn->getBeginLoc(), 6345 diag::err_va_start_used_in_wrong_abi_function) 6346 << !IsWindows; 6347 } 6348 return false; 6349 } 6350 6351 if (IsMSVAStart) 6352 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 6353 return false; 6354 } 6355 6356 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 6357 ParmVarDecl **LastParam = nullptr) { 6358 // Determine whether the current function, block, or obj-c method is variadic 6359 // and get its parameter list. 6360 bool IsVariadic = false; 6361 ArrayRef<ParmVarDecl *> Params; 6362 DeclContext *Caller = S.CurContext; 6363 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 6364 IsVariadic = Block->isVariadic(); 6365 Params = Block->parameters(); 6366 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 6367 IsVariadic = FD->isVariadic(); 6368 Params = FD->parameters(); 6369 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 6370 IsVariadic = MD->isVariadic(); 6371 // FIXME: This isn't correct for methods (results in bogus warning). 6372 Params = MD->parameters(); 6373 } else if (isa<CapturedDecl>(Caller)) { 6374 // We don't support va_start in a CapturedDecl. 6375 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 6376 return true; 6377 } else { 6378 // This must be some other declcontext that parses exprs. 6379 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 6380 return true; 6381 } 6382 6383 if (!IsVariadic) { 6384 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 6385 return true; 6386 } 6387 6388 if (LastParam) 6389 *LastParam = Params.empty() ? nullptr : Params.back(); 6390 6391 return false; 6392 } 6393 6394 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 6395 /// for validity. Emit an error and return true on failure; return false 6396 /// on success. 6397 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 6398 Expr *Fn = TheCall->getCallee(); 6399 6400 if (checkVAStartABI(*this, BuiltinID, Fn)) 6401 return true; 6402 6403 if (checkArgCount(*this, TheCall, 2)) 6404 return true; 6405 6406 // Type-check the first argument normally. 6407 if (checkBuiltinArgument(*this, TheCall, 0)) 6408 return true; 6409 6410 // Check that the current function is variadic, and get its last parameter. 6411 ParmVarDecl *LastParam; 6412 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 6413 return true; 6414 6415 // Verify that the second argument to the builtin is the last argument of the 6416 // current function or method. 6417 bool SecondArgIsLastNamedArgument = false; 6418 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 6419 6420 // These are valid if SecondArgIsLastNamedArgument is false after the next 6421 // block. 6422 QualType Type; 6423 SourceLocation ParamLoc; 6424 bool IsCRegister = false; 6425 6426 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 6427 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 6428 SecondArgIsLastNamedArgument = PV == LastParam; 6429 6430 Type = PV->getType(); 6431 ParamLoc = PV->getLocation(); 6432 IsCRegister = 6433 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 6434 } 6435 } 6436 6437 if (!SecondArgIsLastNamedArgument) 6438 Diag(TheCall->getArg(1)->getBeginLoc(), 6439 diag::warn_second_arg_of_va_start_not_last_named_param); 6440 else if (IsCRegister || Type->isReferenceType() || 6441 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 6442 // Promotable integers are UB, but enumerations need a bit of 6443 // extra checking to see what their promotable type actually is. 6444 if (!Type->isPromotableIntegerType()) 6445 return false; 6446 if (!Type->isEnumeralType()) 6447 return true; 6448 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 6449 return !(ED && 6450 Context.typesAreCompatible(ED->getPromotionType(), Type)); 6451 }()) { 6452 unsigned Reason = 0; 6453 if (Type->isReferenceType()) Reason = 1; 6454 else if (IsCRegister) Reason = 2; 6455 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 6456 Diag(ParamLoc, diag::note_parameter_type) << Type; 6457 } 6458 6459 TheCall->setType(Context.VoidTy); 6460 return false; 6461 } 6462 6463 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 6464 auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool { 6465 const LangOptions &LO = getLangOpts(); 6466 6467 if (LO.CPlusPlus) 6468 return Arg->getType() 6469 .getCanonicalType() 6470 .getTypePtr() 6471 ->getPointeeType() 6472 .withoutLocalFastQualifiers() == Context.CharTy; 6473 6474 // In C, allow aliasing through `char *`, this is required for AArch64 at 6475 // least. 6476 return true; 6477 }; 6478 6479 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 6480 // const char *named_addr); 6481 6482 Expr *Func = Call->getCallee(); 6483 6484 if (Call->getNumArgs() < 3) 6485 return Diag(Call->getEndLoc(), 6486 diag::err_typecheck_call_too_few_args_at_least) 6487 << 0 /*function call*/ << 3 << Call->getNumArgs(); 6488 6489 // Type-check the first argument normally. 6490 if (checkBuiltinArgument(*this, Call, 0)) 6491 return true; 6492 6493 // Check that the current function is variadic. 6494 if (checkVAStartIsInVariadicFunction(*this, Func)) 6495 return true; 6496 6497 // __va_start on Windows does not validate the parameter qualifiers 6498 6499 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 6500 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 6501 6502 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 6503 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 6504 6505 const QualType &ConstCharPtrTy = 6506 Context.getPointerType(Context.CharTy.withConst()); 6507 if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1)) 6508 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6509 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 6510 << 0 /* qualifier difference */ 6511 << 3 /* parameter mismatch */ 6512 << 2 << Arg1->getType() << ConstCharPtrTy; 6513 6514 const QualType SizeTy = Context.getSizeType(); 6515 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 6516 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 6517 << Arg2->getType() << SizeTy << 1 /* different class */ 6518 << 0 /* qualifier difference */ 6519 << 3 /* parameter mismatch */ 6520 << 3 << Arg2->getType() << SizeTy; 6521 6522 return false; 6523 } 6524 6525 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 6526 /// friends. This is declared to take (...), so we have to check everything. 6527 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 6528 if (checkArgCount(*this, TheCall, 2)) 6529 return true; 6530 6531 ExprResult OrigArg0 = TheCall->getArg(0); 6532 ExprResult OrigArg1 = TheCall->getArg(1); 6533 6534 // Do standard promotions between the two arguments, returning their common 6535 // type. 6536 QualType Res = UsualArithmeticConversions( 6537 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 6538 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 6539 return true; 6540 6541 // Make sure any conversions are pushed back into the call; this is 6542 // type safe since unordered compare builtins are declared as "_Bool 6543 // foo(...)". 6544 TheCall->setArg(0, OrigArg0.get()); 6545 TheCall->setArg(1, OrigArg1.get()); 6546 6547 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 6548 return false; 6549 6550 // If the common type isn't a real floating type, then the arguments were 6551 // invalid for this operation. 6552 if (Res.isNull() || !Res->isRealFloatingType()) 6553 return Diag(OrigArg0.get()->getBeginLoc(), 6554 diag::err_typecheck_call_invalid_ordered_compare) 6555 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 6556 << SourceRange(OrigArg0.get()->getBeginLoc(), 6557 OrigArg1.get()->getEndLoc()); 6558 6559 return false; 6560 } 6561 6562 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 6563 /// __builtin_isnan and friends. This is declared to take (...), so we have 6564 /// to check everything. We expect the last argument to be a floating point 6565 /// value. 6566 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 6567 if (checkArgCount(*this, TheCall, NumArgs)) 6568 return true; 6569 6570 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 6571 // on all preceding parameters just being int. Try all of those. 6572 for (unsigned i = 0; i < NumArgs - 1; ++i) { 6573 Expr *Arg = TheCall->getArg(i); 6574 6575 if (Arg->isTypeDependent()) 6576 return false; 6577 6578 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 6579 6580 if (Res.isInvalid()) 6581 return true; 6582 TheCall->setArg(i, Res.get()); 6583 } 6584 6585 Expr *OrigArg = TheCall->getArg(NumArgs-1); 6586 6587 if (OrigArg->isTypeDependent()) 6588 return false; 6589 6590 // Usual Unary Conversions will convert half to float, which we want for 6591 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 6592 // type how it is, but do normal L->Rvalue conversions. 6593 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 6594 OrigArg = UsualUnaryConversions(OrigArg).get(); 6595 else 6596 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 6597 TheCall->setArg(NumArgs - 1, OrigArg); 6598 6599 // This operation requires a non-_Complex floating-point number. 6600 if (!OrigArg->getType()->isRealFloatingType()) 6601 return Diag(OrigArg->getBeginLoc(), 6602 diag::err_typecheck_call_invalid_unary_fp) 6603 << OrigArg->getType() << OrigArg->getSourceRange(); 6604 6605 return false; 6606 } 6607 6608 /// Perform semantic analysis for a call to __builtin_complex. 6609 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 6610 if (checkArgCount(*this, TheCall, 2)) 6611 return true; 6612 6613 bool Dependent = false; 6614 for (unsigned I = 0; I != 2; ++I) { 6615 Expr *Arg = TheCall->getArg(I); 6616 QualType T = Arg->getType(); 6617 if (T->isDependentType()) { 6618 Dependent = true; 6619 continue; 6620 } 6621 6622 // Despite supporting _Complex int, GCC requires a real floating point type 6623 // for the operands of __builtin_complex. 6624 if (!T->isRealFloatingType()) { 6625 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 6626 << Arg->getType() << Arg->getSourceRange(); 6627 } 6628 6629 ExprResult Converted = DefaultLvalueConversion(Arg); 6630 if (Converted.isInvalid()) 6631 return true; 6632 TheCall->setArg(I, Converted.get()); 6633 } 6634 6635 if (Dependent) { 6636 TheCall->setType(Context.DependentTy); 6637 return false; 6638 } 6639 6640 Expr *Real = TheCall->getArg(0); 6641 Expr *Imag = TheCall->getArg(1); 6642 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 6643 return Diag(Real->getBeginLoc(), 6644 diag::err_typecheck_call_different_arg_types) 6645 << Real->getType() << Imag->getType() 6646 << Real->getSourceRange() << Imag->getSourceRange(); 6647 } 6648 6649 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 6650 // don't allow this builtin to form those types either. 6651 // FIXME: Should we allow these types? 6652 if (Real->getType()->isFloat16Type()) 6653 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6654 << "_Float16"; 6655 if (Real->getType()->isHalfType()) 6656 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 6657 << "half"; 6658 6659 TheCall->setType(Context.getComplexType(Real->getType())); 6660 return false; 6661 } 6662 6663 // Customized Sema Checking for VSX builtins that have the following signature: 6664 // vector [...] builtinName(vector [...], vector [...], const int); 6665 // Which takes the same type of vectors (any legal vector type) for the first 6666 // two arguments and takes compile time constant for the third argument. 6667 // Example builtins are : 6668 // vector double vec_xxpermdi(vector double, vector double, int); 6669 // vector short vec_xxsldwi(vector short, vector short, int); 6670 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 6671 unsigned ExpectedNumArgs = 3; 6672 if (checkArgCount(*this, TheCall, ExpectedNumArgs)) 6673 return true; 6674 6675 // Check the third argument is a compile time constant 6676 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 6677 return Diag(TheCall->getBeginLoc(), 6678 diag::err_vsx_builtin_nonconstant_argument) 6679 << 3 /* argument index */ << TheCall->getDirectCallee() 6680 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 6681 TheCall->getArg(2)->getEndLoc()); 6682 6683 QualType Arg1Ty = TheCall->getArg(0)->getType(); 6684 QualType Arg2Ty = TheCall->getArg(1)->getType(); 6685 6686 // Check the type of argument 1 and argument 2 are vectors. 6687 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 6688 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 6689 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 6690 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 6691 << TheCall->getDirectCallee() 6692 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6693 TheCall->getArg(1)->getEndLoc()); 6694 } 6695 6696 // Check the first two arguments are the same type. 6697 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 6698 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 6699 << TheCall->getDirectCallee() 6700 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6701 TheCall->getArg(1)->getEndLoc()); 6702 } 6703 6704 // When default clang type checking is turned off and the customized type 6705 // checking is used, the returning type of the function must be explicitly 6706 // set. Otherwise it is _Bool by default. 6707 TheCall->setType(Arg1Ty); 6708 6709 return false; 6710 } 6711 6712 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 6713 // This is declared to take (...), so we have to check everything. 6714 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 6715 if (TheCall->getNumArgs() < 2) 6716 return ExprError(Diag(TheCall->getEndLoc(), 6717 diag::err_typecheck_call_too_few_args_at_least) 6718 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 6719 << TheCall->getSourceRange()); 6720 6721 // Determine which of the following types of shufflevector we're checking: 6722 // 1) unary, vector mask: (lhs, mask) 6723 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 6724 QualType resType = TheCall->getArg(0)->getType(); 6725 unsigned numElements = 0; 6726 6727 if (!TheCall->getArg(0)->isTypeDependent() && 6728 !TheCall->getArg(1)->isTypeDependent()) { 6729 QualType LHSType = TheCall->getArg(0)->getType(); 6730 QualType RHSType = TheCall->getArg(1)->getType(); 6731 6732 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 6733 return ExprError( 6734 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 6735 << TheCall->getDirectCallee() 6736 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6737 TheCall->getArg(1)->getEndLoc())); 6738 6739 numElements = LHSType->castAs<VectorType>()->getNumElements(); 6740 unsigned numResElements = TheCall->getNumArgs() - 2; 6741 6742 // Check to see if we have a call with 2 vector arguments, the unary shuffle 6743 // with mask. If so, verify that RHS is an integer vector type with the 6744 // same number of elts as lhs. 6745 if (TheCall->getNumArgs() == 2) { 6746 if (!RHSType->hasIntegerRepresentation() || 6747 RHSType->castAs<VectorType>()->getNumElements() != numElements) 6748 return ExprError(Diag(TheCall->getBeginLoc(), 6749 diag::err_vec_builtin_incompatible_vector) 6750 << TheCall->getDirectCallee() 6751 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 6752 TheCall->getArg(1)->getEndLoc())); 6753 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 6754 return ExprError(Diag(TheCall->getBeginLoc(), 6755 diag::err_vec_builtin_incompatible_vector) 6756 << TheCall->getDirectCallee() 6757 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 6758 TheCall->getArg(1)->getEndLoc())); 6759 } else if (numElements != numResElements) { 6760 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 6761 resType = Context.getVectorType(eltType, numResElements, 6762 VectorType::GenericVector); 6763 } 6764 } 6765 6766 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 6767 if (TheCall->getArg(i)->isTypeDependent() || 6768 TheCall->getArg(i)->isValueDependent()) 6769 continue; 6770 6771 Optional<llvm::APSInt> Result; 6772 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 6773 return ExprError(Diag(TheCall->getBeginLoc(), 6774 diag::err_shufflevector_nonconstant_argument) 6775 << TheCall->getArg(i)->getSourceRange()); 6776 6777 // Allow -1 which will be translated to undef in the IR. 6778 if (Result->isSigned() && Result->isAllOnes()) 6779 continue; 6780 6781 if (Result->getActiveBits() > 64 || 6782 Result->getZExtValue() >= numElements * 2) 6783 return ExprError(Diag(TheCall->getBeginLoc(), 6784 diag::err_shufflevector_argument_too_large) 6785 << TheCall->getArg(i)->getSourceRange()); 6786 } 6787 6788 SmallVector<Expr*, 32> exprs; 6789 6790 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 6791 exprs.push_back(TheCall->getArg(i)); 6792 TheCall->setArg(i, nullptr); 6793 } 6794 6795 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 6796 TheCall->getCallee()->getBeginLoc(), 6797 TheCall->getRParenLoc()); 6798 } 6799 6800 /// SemaConvertVectorExpr - Handle __builtin_convertvector 6801 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 6802 SourceLocation BuiltinLoc, 6803 SourceLocation RParenLoc) { 6804 ExprValueKind VK = VK_PRValue; 6805 ExprObjectKind OK = OK_Ordinary; 6806 QualType DstTy = TInfo->getType(); 6807 QualType SrcTy = E->getType(); 6808 6809 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6810 return ExprError(Diag(BuiltinLoc, 6811 diag::err_convertvector_non_vector) 6812 << E->getSourceRange()); 6813 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6814 return ExprError(Diag(BuiltinLoc, 6815 diag::err_convertvector_non_vector_type)); 6816 6817 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6818 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6819 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6820 if (SrcElts != DstElts) 6821 return ExprError(Diag(BuiltinLoc, 6822 diag::err_convertvector_incompatible_vector) 6823 << E->getSourceRange()); 6824 } 6825 6826 return new (Context) 6827 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6828 } 6829 6830 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6831 // This is declared to take (const void*, ...) and can take two 6832 // optional constant int args. 6833 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6834 unsigned NumArgs = TheCall->getNumArgs(); 6835 6836 if (NumArgs > 3) 6837 return Diag(TheCall->getEndLoc(), 6838 diag::err_typecheck_call_too_many_args_at_most) 6839 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6840 6841 // Argument 0 is checked for us and the remaining arguments must be 6842 // constant integers. 6843 for (unsigned i = 1; i != NumArgs; ++i) 6844 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6845 return true; 6846 6847 return false; 6848 } 6849 6850 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence. 6851 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) { 6852 if (!Context.getTargetInfo().checkArithmeticFenceSupported()) 6853 return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 6854 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6855 if (checkArgCount(*this, TheCall, 1)) 6856 return true; 6857 Expr *Arg = TheCall->getArg(0); 6858 if (Arg->isInstantiationDependent()) 6859 return false; 6860 6861 QualType ArgTy = Arg->getType(); 6862 if (!ArgTy->hasFloatingRepresentation()) 6863 return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector) 6864 << ArgTy; 6865 if (Arg->isLValue()) { 6866 ExprResult FirstArg = DefaultLvalueConversion(Arg); 6867 TheCall->setArg(0, FirstArg.get()); 6868 } 6869 TheCall->setType(TheCall->getArg(0)->getType()); 6870 return false; 6871 } 6872 6873 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6874 // __assume does not evaluate its arguments, and should warn if its argument 6875 // has side effects. 6876 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6877 Expr *Arg = TheCall->getArg(0); 6878 if (Arg->isInstantiationDependent()) return false; 6879 6880 if (Arg->HasSideEffects(Context)) 6881 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6882 << Arg->getSourceRange() 6883 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6884 6885 return false; 6886 } 6887 6888 /// Handle __builtin_alloca_with_align. This is declared 6889 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6890 /// than 8. 6891 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6892 // The alignment must be a constant integer. 6893 Expr *Arg = TheCall->getArg(1); 6894 6895 // We can't check the value of a dependent argument. 6896 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6897 if (const auto *UE = 6898 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6899 if (UE->getKind() == UETT_AlignOf || 6900 UE->getKind() == UETT_PreferredAlignOf) 6901 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6902 << Arg->getSourceRange(); 6903 6904 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6905 6906 if (!Result.isPowerOf2()) 6907 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6908 << Arg->getSourceRange(); 6909 6910 if (Result < Context.getCharWidth()) 6911 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6912 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6913 6914 if (Result > std::numeric_limits<int32_t>::max()) 6915 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6916 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6917 } 6918 6919 return false; 6920 } 6921 6922 /// Handle __builtin_assume_aligned. This is declared 6923 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6924 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6925 unsigned NumArgs = TheCall->getNumArgs(); 6926 6927 if (NumArgs > 3) 6928 return Diag(TheCall->getEndLoc(), 6929 diag::err_typecheck_call_too_many_args_at_most) 6930 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6931 6932 // The alignment must be a constant integer. 6933 Expr *Arg = TheCall->getArg(1); 6934 6935 // We can't check the value of a dependent argument. 6936 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6937 llvm::APSInt Result; 6938 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6939 return true; 6940 6941 if (!Result.isPowerOf2()) 6942 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6943 << Arg->getSourceRange(); 6944 6945 if (Result > Sema::MaximumAlignment) 6946 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6947 << Arg->getSourceRange() << Sema::MaximumAlignment; 6948 } 6949 6950 if (NumArgs > 2) { 6951 ExprResult Arg(TheCall->getArg(2)); 6952 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6953 Context.getSizeType(), false); 6954 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6955 if (Arg.isInvalid()) return true; 6956 TheCall->setArg(2, Arg.get()); 6957 } 6958 6959 return false; 6960 } 6961 6962 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6963 unsigned BuiltinID = 6964 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6965 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6966 6967 unsigned NumArgs = TheCall->getNumArgs(); 6968 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6969 if (NumArgs < NumRequiredArgs) { 6970 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6971 << 0 /* function call */ << NumRequiredArgs << NumArgs 6972 << TheCall->getSourceRange(); 6973 } 6974 if (NumArgs >= NumRequiredArgs + 0x100) { 6975 return Diag(TheCall->getEndLoc(), 6976 diag::err_typecheck_call_too_many_args_at_most) 6977 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6978 << TheCall->getSourceRange(); 6979 } 6980 unsigned i = 0; 6981 6982 // For formatting call, check buffer arg. 6983 if (!IsSizeCall) { 6984 ExprResult Arg(TheCall->getArg(i)); 6985 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6986 Context, Context.VoidPtrTy, false); 6987 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6988 if (Arg.isInvalid()) 6989 return true; 6990 TheCall->setArg(i, Arg.get()); 6991 i++; 6992 } 6993 6994 // Check string literal arg. 6995 unsigned FormatIdx = i; 6996 { 6997 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6998 if (Arg.isInvalid()) 6999 return true; 7000 TheCall->setArg(i, Arg.get()); 7001 i++; 7002 } 7003 7004 // Make sure variadic args are scalar. 7005 unsigned FirstDataArg = i; 7006 while (i < NumArgs) { 7007 ExprResult Arg = DefaultVariadicArgumentPromotion( 7008 TheCall->getArg(i), VariadicFunction, nullptr); 7009 if (Arg.isInvalid()) 7010 return true; 7011 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 7012 if (ArgSize.getQuantity() >= 0x100) { 7013 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 7014 << i << (int)ArgSize.getQuantity() << 0xff 7015 << TheCall->getSourceRange(); 7016 } 7017 TheCall->setArg(i, Arg.get()); 7018 i++; 7019 } 7020 7021 // Check formatting specifiers. NOTE: We're only doing this for the non-size 7022 // call to avoid duplicate diagnostics. 7023 if (!IsSizeCall) { 7024 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 7025 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 7026 bool Success = CheckFormatArguments( 7027 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 7028 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 7029 CheckedVarArgs); 7030 if (!Success) 7031 return true; 7032 } 7033 7034 if (IsSizeCall) { 7035 TheCall->setType(Context.getSizeType()); 7036 } else { 7037 TheCall->setType(Context.VoidPtrTy); 7038 } 7039 return false; 7040 } 7041 7042 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 7043 /// TheCall is a constant expression. 7044 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 7045 llvm::APSInt &Result) { 7046 Expr *Arg = TheCall->getArg(ArgNum); 7047 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 7048 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 7049 7050 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 7051 7052 Optional<llvm::APSInt> R; 7053 if (!(R = Arg->getIntegerConstantExpr(Context))) 7054 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 7055 << FDecl->getDeclName() << Arg->getSourceRange(); 7056 Result = *R; 7057 return false; 7058 } 7059 7060 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 7061 /// TheCall is a constant expression in the range [Low, High]. 7062 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 7063 int Low, int High, bool RangeIsError) { 7064 if (isConstantEvaluated()) 7065 return false; 7066 llvm::APSInt Result; 7067 7068 // We can't check the value of a dependent argument. 7069 Expr *Arg = TheCall->getArg(ArgNum); 7070 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7071 return false; 7072 7073 // Check constant-ness first. 7074 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7075 return true; 7076 7077 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 7078 if (RangeIsError) 7079 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 7080 << toString(Result, 10) << Low << High << Arg->getSourceRange(); 7081 else 7082 // Defer the warning until we know if the code will be emitted so that 7083 // dead code can ignore this. 7084 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 7085 PDiag(diag::warn_argument_invalid_range) 7086 << toString(Result, 10) << Low << High 7087 << Arg->getSourceRange()); 7088 } 7089 7090 return false; 7091 } 7092 7093 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 7094 /// TheCall is a constant expression is a multiple of Num.. 7095 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 7096 unsigned Num) { 7097 llvm::APSInt Result; 7098 7099 // We can't check the value of a dependent argument. 7100 Expr *Arg = TheCall->getArg(ArgNum); 7101 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7102 return false; 7103 7104 // Check constant-ness first. 7105 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7106 return true; 7107 7108 if (Result.getSExtValue() % Num != 0) 7109 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 7110 << Num << Arg->getSourceRange(); 7111 7112 return false; 7113 } 7114 7115 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 7116 /// constant expression representing a power of 2. 7117 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 7118 llvm::APSInt Result; 7119 7120 // We can't check the value of a dependent argument. 7121 Expr *Arg = TheCall->getArg(ArgNum); 7122 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7123 return false; 7124 7125 // Check constant-ness first. 7126 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7127 return true; 7128 7129 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 7130 // and only if x is a power of 2. 7131 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 7132 return false; 7133 7134 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 7135 << Arg->getSourceRange(); 7136 } 7137 7138 static bool IsShiftedByte(llvm::APSInt Value) { 7139 if (Value.isNegative()) 7140 return false; 7141 7142 // Check if it's a shifted byte, by shifting it down 7143 while (true) { 7144 // If the value fits in the bottom byte, the check passes. 7145 if (Value < 0x100) 7146 return true; 7147 7148 // Otherwise, if the value has _any_ bits in the bottom byte, the check 7149 // fails. 7150 if ((Value & 0xFF) != 0) 7151 return false; 7152 7153 // If the bottom 8 bits are all 0, but something above that is nonzero, 7154 // then shifting the value right by 8 bits won't affect whether it's a 7155 // shifted byte or not. So do that, and go round again. 7156 Value >>= 8; 7157 } 7158 } 7159 7160 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 7161 /// a constant expression representing an arbitrary byte value shifted left by 7162 /// a multiple of 8 bits. 7163 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 7164 unsigned ArgBits) { 7165 llvm::APSInt Result; 7166 7167 // We can't check the value of a dependent argument. 7168 Expr *Arg = TheCall->getArg(ArgNum); 7169 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7170 return false; 7171 7172 // Check constant-ness first. 7173 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7174 return true; 7175 7176 // Truncate to the given size. 7177 Result = Result.getLoBits(ArgBits); 7178 Result.setIsUnsigned(true); 7179 7180 if (IsShiftedByte(Result)) 7181 return false; 7182 7183 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 7184 << Arg->getSourceRange(); 7185 } 7186 7187 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 7188 /// TheCall is a constant expression representing either a shifted byte value, 7189 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 7190 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 7191 /// Arm MVE intrinsics. 7192 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 7193 int ArgNum, 7194 unsigned ArgBits) { 7195 llvm::APSInt Result; 7196 7197 // We can't check the value of a dependent argument. 7198 Expr *Arg = TheCall->getArg(ArgNum); 7199 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7200 return false; 7201 7202 // Check constant-ness first. 7203 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 7204 return true; 7205 7206 // Truncate to the given size. 7207 Result = Result.getLoBits(ArgBits); 7208 Result.setIsUnsigned(true); 7209 7210 // Check to see if it's in either of the required forms. 7211 if (IsShiftedByte(Result) || 7212 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 7213 return false; 7214 7215 return Diag(TheCall->getBeginLoc(), 7216 diag::err_argument_not_shifted_byte_or_xxff) 7217 << Arg->getSourceRange(); 7218 } 7219 7220 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 7221 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 7222 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 7223 if (checkArgCount(*this, TheCall, 2)) 7224 return true; 7225 Expr *Arg0 = TheCall->getArg(0); 7226 Expr *Arg1 = TheCall->getArg(1); 7227 7228 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7229 if (FirstArg.isInvalid()) 7230 return true; 7231 QualType FirstArgType = FirstArg.get()->getType(); 7232 if (!FirstArgType->isAnyPointerType()) 7233 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7234 << "first" << FirstArgType << Arg0->getSourceRange(); 7235 TheCall->setArg(0, FirstArg.get()); 7236 7237 ExprResult SecArg = DefaultLvalueConversion(Arg1); 7238 if (SecArg.isInvalid()) 7239 return true; 7240 QualType SecArgType = SecArg.get()->getType(); 7241 if (!SecArgType->isIntegerType()) 7242 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7243 << "second" << SecArgType << Arg1->getSourceRange(); 7244 7245 // Derive the return type from the pointer argument. 7246 TheCall->setType(FirstArgType); 7247 return false; 7248 } 7249 7250 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 7251 if (checkArgCount(*this, TheCall, 2)) 7252 return true; 7253 7254 Expr *Arg0 = TheCall->getArg(0); 7255 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7256 if (FirstArg.isInvalid()) 7257 return true; 7258 QualType FirstArgType = FirstArg.get()->getType(); 7259 if (!FirstArgType->isAnyPointerType()) 7260 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7261 << "first" << FirstArgType << Arg0->getSourceRange(); 7262 TheCall->setArg(0, FirstArg.get()); 7263 7264 // Derive the return type from the pointer argument. 7265 TheCall->setType(FirstArgType); 7266 7267 // Second arg must be an constant in range [0,15] 7268 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7269 } 7270 7271 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 7272 if (checkArgCount(*this, TheCall, 2)) 7273 return true; 7274 Expr *Arg0 = TheCall->getArg(0); 7275 Expr *Arg1 = TheCall->getArg(1); 7276 7277 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7278 if (FirstArg.isInvalid()) 7279 return true; 7280 QualType FirstArgType = FirstArg.get()->getType(); 7281 if (!FirstArgType->isAnyPointerType()) 7282 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7283 << "first" << FirstArgType << Arg0->getSourceRange(); 7284 7285 QualType SecArgType = Arg1->getType(); 7286 if (!SecArgType->isIntegerType()) 7287 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 7288 << "second" << SecArgType << Arg1->getSourceRange(); 7289 TheCall->setType(Context.IntTy); 7290 return false; 7291 } 7292 7293 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 7294 BuiltinID == AArch64::BI__builtin_arm_stg) { 7295 if (checkArgCount(*this, TheCall, 1)) 7296 return true; 7297 Expr *Arg0 = TheCall->getArg(0); 7298 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 7299 if (FirstArg.isInvalid()) 7300 return true; 7301 7302 QualType FirstArgType = FirstArg.get()->getType(); 7303 if (!FirstArgType->isAnyPointerType()) 7304 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 7305 << "first" << FirstArgType << Arg0->getSourceRange(); 7306 TheCall->setArg(0, FirstArg.get()); 7307 7308 // Derive the return type from the pointer argument. 7309 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 7310 TheCall->setType(FirstArgType); 7311 return false; 7312 } 7313 7314 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 7315 Expr *ArgA = TheCall->getArg(0); 7316 Expr *ArgB = TheCall->getArg(1); 7317 7318 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 7319 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 7320 7321 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 7322 return true; 7323 7324 QualType ArgTypeA = ArgExprA.get()->getType(); 7325 QualType ArgTypeB = ArgExprB.get()->getType(); 7326 7327 auto isNull = [&] (Expr *E) -> bool { 7328 return E->isNullPointerConstant( 7329 Context, Expr::NPC_ValueDependentIsNotNull); }; 7330 7331 // argument should be either a pointer or null 7332 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 7333 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7334 << "first" << ArgTypeA << ArgA->getSourceRange(); 7335 7336 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 7337 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 7338 << "second" << ArgTypeB << ArgB->getSourceRange(); 7339 7340 // Ensure Pointee types are compatible 7341 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 7342 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 7343 QualType pointeeA = ArgTypeA->getPointeeType(); 7344 QualType pointeeB = ArgTypeB->getPointeeType(); 7345 if (!Context.typesAreCompatible( 7346 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 7347 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 7348 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 7349 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 7350 << ArgB->getSourceRange(); 7351 } 7352 } 7353 7354 // at least one argument should be pointer type 7355 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 7356 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 7357 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 7358 7359 if (isNull(ArgA)) // adopt type of the other pointer 7360 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 7361 7362 if (isNull(ArgB)) 7363 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 7364 7365 TheCall->setArg(0, ArgExprA.get()); 7366 TheCall->setArg(1, ArgExprB.get()); 7367 TheCall->setType(Context.LongLongTy); 7368 return false; 7369 } 7370 assert(false && "Unhandled ARM MTE intrinsic"); 7371 return true; 7372 } 7373 7374 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 7375 /// TheCall is an ARM/AArch64 special register string literal. 7376 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 7377 int ArgNum, unsigned ExpectedFieldNum, 7378 bool AllowName) { 7379 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 7380 BuiltinID == ARM::BI__builtin_arm_wsr64 || 7381 BuiltinID == ARM::BI__builtin_arm_rsr || 7382 BuiltinID == ARM::BI__builtin_arm_rsrp || 7383 BuiltinID == ARM::BI__builtin_arm_wsr || 7384 BuiltinID == ARM::BI__builtin_arm_wsrp; 7385 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 7386 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 7387 BuiltinID == AArch64::BI__builtin_arm_rsr || 7388 BuiltinID == AArch64::BI__builtin_arm_rsrp || 7389 BuiltinID == AArch64::BI__builtin_arm_wsr || 7390 BuiltinID == AArch64::BI__builtin_arm_wsrp; 7391 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 7392 7393 // We can't check the value of a dependent argument. 7394 Expr *Arg = TheCall->getArg(ArgNum); 7395 if (Arg->isTypeDependent() || Arg->isValueDependent()) 7396 return false; 7397 7398 // Check if the argument is a string literal. 7399 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 7400 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 7401 << Arg->getSourceRange(); 7402 7403 // Check the type of special register given. 7404 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 7405 SmallVector<StringRef, 6> Fields; 7406 Reg.split(Fields, ":"); 7407 7408 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 7409 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7410 << Arg->getSourceRange(); 7411 7412 // If the string is the name of a register then we cannot check that it is 7413 // valid here but if the string is of one the forms described in ACLE then we 7414 // can check that the supplied fields are integers and within the valid 7415 // ranges. 7416 if (Fields.size() > 1) { 7417 bool FiveFields = Fields.size() == 5; 7418 7419 bool ValidString = true; 7420 if (IsARMBuiltin) { 7421 ValidString &= Fields[0].startswith_insensitive("cp") || 7422 Fields[0].startswith_insensitive("p"); 7423 if (ValidString) 7424 Fields[0] = Fields[0].drop_front( 7425 Fields[0].startswith_insensitive("cp") ? 2 : 1); 7426 7427 ValidString &= Fields[2].startswith_insensitive("c"); 7428 if (ValidString) 7429 Fields[2] = Fields[2].drop_front(1); 7430 7431 if (FiveFields) { 7432 ValidString &= Fields[3].startswith_insensitive("c"); 7433 if (ValidString) 7434 Fields[3] = Fields[3].drop_front(1); 7435 } 7436 } 7437 7438 SmallVector<int, 5> Ranges; 7439 if (FiveFields) 7440 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 7441 else 7442 Ranges.append({15, 7, 15}); 7443 7444 for (unsigned i=0; i<Fields.size(); ++i) { 7445 int IntField; 7446 ValidString &= !Fields[i].getAsInteger(10, IntField); 7447 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 7448 } 7449 7450 if (!ValidString) 7451 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 7452 << Arg->getSourceRange(); 7453 } else if (IsAArch64Builtin && Fields.size() == 1) { 7454 // If the register name is one of those that appear in the condition below 7455 // and the special register builtin being used is one of the write builtins, 7456 // then we require that the argument provided for writing to the register 7457 // is an integer constant expression. This is because it will be lowered to 7458 // an MSR (immediate) instruction, so we need to know the immediate at 7459 // compile time. 7460 if (TheCall->getNumArgs() != 2) 7461 return false; 7462 7463 std::string RegLower = Reg.lower(); 7464 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 7465 RegLower != "pan" && RegLower != "uao") 7466 return false; 7467 7468 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 7469 } 7470 7471 return false; 7472 } 7473 7474 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity. 7475 /// Emit an error and return true on failure; return false on success. 7476 /// TypeStr is a string containing the type descriptor of the value returned by 7477 /// the builtin and the descriptors of the expected type of the arguments. 7478 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID, 7479 const char *TypeStr) { 7480 7481 assert((TypeStr[0] != '\0') && 7482 "Invalid types in PPC MMA builtin declaration"); 7483 7484 switch (BuiltinID) { 7485 default: 7486 // This function is called in CheckPPCBuiltinFunctionCall where the 7487 // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here 7488 // we are isolating the pair vector memop builtins that can be used with mma 7489 // off so the default case is every builtin that requires mma and paired 7490 // vector memops. 7491 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7492 diag::err_ppc_builtin_only_on_arch, "10") || 7493 SemaFeatureCheck(*this, TheCall, "mma", 7494 diag::err_ppc_builtin_only_on_arch, "10")) 7495 return true; 7496 break; 7497 case PPC::BI__builtin_vsx_lxvp: 7498 case PPC::BI__builtin_vsx_stxvp: 7499 case PPC::BI__builtin_vsx_assemble_pair: 7500 case PPC::BI__builtin_vsx_disassemble_pair: 7501 if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops", 7502 diag::err_ppc_builtin_only_on_arch, "10")) 7503 return true; 7504 break; 7505 } 7506 7507 unsigned Mask = 0; 7508 unsigned ArgNum = 0; 7509 7510 // The first type in TypeStr is the type of the value returned by the 7511 // builtin. So we first read that type and change the type of TheCall. 7512 QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7513 TheCall->setType(type); 7514 7515 while (*TypeStr != '\0') { 7516 Mask = 0; 7517 QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7518 if (ArgNum >= TheCall->getNumArgs()) { 7519 ArgNum++; 7520 break; 7521 } 7522 7523 Expr *Arg = TheCall->getArg(ArgNum); 7524 QualType PassedType = Arg->getType(); 7525 QualType StrippedRVType = PassedType.getCanonicalType(); 7526 7527 // Strip Restrict/Volatile qualifiers. 7528 if (StrippedRVType.isRestrictQualified() || 7529 StrippedRVType.isVolatileQualified()) 7530 StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType(); 7531 7532 // The only case where the argument type and expected type are allowed to 7533 // mismatch is if the argument type is a non-void pointer and expected type 7534 // is a void pointer. 7535 if (StrippedRVType != ExpectedType) 7536 if (!(ExpectedType->isVoidPointerType() && 7537 StrippedRVType->isPointerType())) 7538 return Diag(Arg->getBeginLoc(), 7539 diag::err_typecheck_convert_incompatible) 7540 << PassedType << ExpectedType << 1 << 0 << 0; 7541 7542 // If the value of the Mask is not 0, we have a constraint in the size of 7543 // the integer argument so here we ensure the argument is a constant that 7544 // is in the valid range. 7545 if (Mask != 0 && 7546 SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true)) 7547 return true; 7548 7549 ArgNum++; 7550 } 7551 7552 // In case we exited early from the previous loop, there are other types to 7553 // read from TypeStr. So we need to read them all to ensure we have the right 7554 // number of arguments in TheCall and if it is not the case, to display a 7555 // better error message. 7556 while (*TypeStr != '\0') { 7557 (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask); 7558 ArgNum++; 7559 } 7560 if (checkArgCount(*this, TheCall, ArgNum)) 7561 return true; 7562 7563 return false; 7564 } 7565 7566 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 7567 /// This checks that the target supports __builtin_longjmp and 7568 /// that val is a constant 1. 7569 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 7570 if (!Context.getTargetInfo().hasSjLjLowering()) 7571 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 7572 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7573 7574 Expr *Arg = TheCall->getArg(1); 7575 llvm::APSInt Result; 7576 7577 // TODO: This is less than ideal. Overload this to take a value. 7578 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 7579 return true; 7580 7581 if (Result != 1) 7582 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 7583 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 7584 7585 return false; 7586 } 7587 7588 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 7589 /// This checks that the target supports __builtin_setjmp. 7590 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 7591 if (!Context.getTargetInfo().hasSjLjLowering()) 7592 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 7593 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 7594 return false; 7595 } 7596 7597 namespace { 7598 7599 class UncoveredArgHandler { 7600 enum { Unknown = -1, AllCovered = -2 }; 7601 7602 signed FirstUncoveredArg = Unknown; 7603 SmallVector<const Expr *, 4> DiagnosticExprs; 7604 7605 public: 7606 UncoveredArgHandler() = default; 7607 7608 bool hasUncoveredArg() const { 7609 return (FirstUncoveredArg >= 0); 7610 } 7611 7612 unsigned getUncoveredArg() const { 7613 assert(hasUncoveredArg() && "no uncovered argument"); 7614 return FirstUncoveredArg; 7615 } 7616 7617 void setAllCovered() { 7618 // A string has been found with all arguments covered, so clear out 7619 // the diagnostics. 7620 DiagnosticExprs.clear(); 7621 FirstUncoveredArg = AllCovered; 7622 } 7623 7624 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 7625 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 7626 7627 // Don't update if a previous string covers all arguments. 7628 if (FirstUncoveredArg == AllCovered) 7629 return; 7630 7631 // UncoveredArgHandler tracks the highest uncovered argument index 7632 // and with it all the strings that match this index. 7633 if (NewFirstUncoveredArg == FirstUncoveredArg) 7634 DiagnosticExprs.push_back(StrExpr); 7635 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 7636 DiagnosticExprs.clear(); 7637 DiagnosticExprs.push_back(StrExpr); 7638 FirstUncoveredArg = NewFirstUncoveredArg; 7639 } 7640 } 7641 7642 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 7643 }; 7644 7645 enum StringLiteralCheckType { 7646 SLCT_NotALiteral, 7647 SLCT_UncheckedLiteral, 7648 SLCT_CheckedLiteral 7649 }; 7650 7651 } // namespace 7652 7653 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 7654 BinaryOperatorKind BinOpKind, 7655 bool AddendIsRight) { 7656 unsigned BitWidth = Offset.getBitWidth(); 7657 unsigned AddendBitWidth = Addend.getBitWidth(); 7658 // There might be negative interim results. 7659 if (Addend.isUnsigned()) { 7660 Addend = Addend.zext(++AddendBitWidth); 7661 Addend.setIsSigned(true); 7662 } 7663 // Adjust the bit width of the APSInts. 7664 if (AddendBitWidth > BitWidth) { 7665 Offset = Offset.sext(AddendBitWidth); 7666 BitWidth = AddendBitWidth; 7667 } else if (BitWidth > AddendBitWidth) { 7668 Addend = Addend.sext(BitWidth); 7669 } 7670 7671 bool Ov = false; 7672 llvm::APSInt ResOffset = Offset; 7673 if (BinOpKind == BO_Add) 7674 ResOffset = Offset.sadd_ov(Addend, Ov); 7675 else { 7676 assert(AddendIsRight && BinOpKind == BO_Sub && 7677 "operator must be add or sub with addend on the right"); 7678 ResOffset = Offset.ssub_ov(Addend, Ov); 7679 } 7680 7681 // We add an offset to a pointer here so we should support an offset as big as 7682 // possible. 7683 if (Ov) { 7684 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 7685 "index (intermediate) result too big"); 7686 Offset = Offset.sext(2 * BitWidth); 7687 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 7688 return; 7689 } 7690 7691 Offset = ResOffset; 7692 } 7693 7694 namespace { 7695 7696 // This is a wrapper class around StringLiteral to support offsetted string 7697 // literals as format strings. It takes the offset into account when returning 7698 // the string and its length or the source locations to display notes correctly. 7699 class FormatStringLiteral { 7700 const StringLiteral *FExpr; 7701 int64_t Offset; 7702 7703 public: 7704 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 7705 : FExpr(fexpr), Offset(Offset) {} 7706 7707 StringRef getString() const { 7708 return FExpr->getString().drop_front(Offset); 7709 } 7710 7711 unsigned getByteLength() const { 7712 return FExpr->getByteLength() - getCharByteWidth() * Offset; 7713 } 7714 7715 unsigned getLength() const { return FExpr->getLength() - Offset; } 7716 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 7717 7718 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 7719 7720 QualType getType() const { return FExpr->getType(); } 7721 7722 bool isAscii() const { return FExpr->isAscii(); } 7723 bool isWide() const { return FExpr->isWide(); } 7724 bool isUTF8() const { return FExpr->isUTF8(); } 7725 bool isUTF16() const { return FExpr->isUTF16(); } 7726 bool isUTF32() const { return FExpr->isUTF32(); } 7727 bool isPascal() const { return FExpr->isPascal(); } 7728 7729 SourceLocation getLocationOfByte( 7730 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 7731 const TargetInfo &Target, unsigned *StartToken = nullptr, 7732 unsigned *StartTokenByteOffset = nullptr) const { 7733 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 7734 StartToken, StartTokenByteOffset); 7735 } 7736 7737 SourceLocation getBeginLoc() const LLVM_READONLY { 7738 return FExpr->getBeginLoc().getLocWithOffset(Offset); 7739 } 7740 7741 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 7742 }; 7743 7744 } // namespace 7745 7746 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 7747 const Expr *OrigFormatExpr, 7748 ArrayRef<const Expr *> Args, 7749 bool HasVAListArg, unsigned format_idx, 7750 unsigned firstDataArg, 7751 Sema::FormatStringType Type, 7752 bool inFunctionCall, 7753 Sema::VariadicCallType CallType, 7754 llvm::SmallBitVector &CheckedVarArgs, 7755 UncoveredArgHandler &UncoveredArg, 7756 bool IgnoreStringsWithoutSpecifiers); 7757 7758 // Determine if an expression is a string literal or constant string. 7759 // If this function returns false on the arguments to a function expecting a 7760 // format string, we will usually need to emit a warning. 7761 // True string literals are then checked by CheckFormatString. 7762 static StringLiteralCheckType 7763 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 7764 bool HasVAListArg, unsigned format_idx, 7765 unsigned firstDataArg, Sema::FormatStringType Type, 7766 Sema::VariadicCallType CallType, bool InFunctionCall, 7767 llvm::SmallBitVector &CheckedVarArgs, 7768 UncoveredArgHandler &UncoveredArg, 7769 llvm::APSInt Offset, 7770 bool IgnoreStringsWithoutSpecifiers = false) { 7771 if (S.isConstantEvaluated()) 7772 return SLCT_NotALiteral; 7773 tryAgain: 7774 assert(Offset.isSigned() && "invalid offset"); 7775 7776 if (E->isTypeDependent() || E->isValueDependent()) 7777 return SLCT_NotALiteral; 7778 7779 E = E->IgnoreParenCasts(); 7780 7781 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 7782 // Technically -Wformat-nonliteral does not warn about this case. 7783 // The behavior of printf and friends in this case is implementation 7784 // dependent. Ideally if the format string cannot be null then 7785 // it should have a 'nonnull' attribute in the function prototype. 7786 return SLCT_UncheckedLiteral; 7787 7788 switch (E->getStmtClass()) { 7789 case Stmt::BinaryConditionalOperatorClass: 7790 case Stmt::ConditionalOperatorClass: { 7791 // The expression is a literal if both sub-expressions were, and it was 7792 // completely checked only if both sub-expressions were checked. 7793 const AbstractConditionalOperator *C = 7794 cast<AbstractConditionalOperator>(E); 7795 7796 // Determine whether it is necessary to check both sub-expressions, for 7797 // example, because the condition expression is a constant that can be 7798 // evaluated at compile time. 7799 bool CheckLeft = true, CheckRight = true; 7800 7801 bool Cond; 7802 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 7803 S.isConstantEvaluated())) { 7804 if (Cond) 7805 CheckRight = false; 7806 else 7807 CheckLeft = false; 7808 } 7809 7810 // We need to maintain the offsets for the right and the left hand side 7811 // separately to check if every possible indexed expression is a valid 7812 // string literal. They might have different offsets for different string 7813 // literals in the end. 7814 StringLiteralCheckType Left; 7815 if (!CheckLeft) 7816 Left = SLCT_UncheckedLiteral; 7817 else { 7818 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 7819 HasVAListArg, format_idx, firstDataArg, 7820 Type, CallType, InFunctionCall, 7821 CheckedVarArgs, UncoveredArg, Offset, 7822 IgnoreStringsWithoutSpecifiers); 7823 if (Left == SLCT_NotALiteral || !CheckRight) { 7824 return Left; 7825 } 7826 } 7827 7828 StringLiteralCheckType Right = checkFormatStringExpr( 7829 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 7830 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7831 IgnoreStringsWithoutSpecifiers); 7832 7833 return (CheckLeft && Left < Right) ? Left : Right; 7834 } 7835 7836 case Stmt::ImplicitCastExprClass: 7837 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 7838 goto tryAgain; 7839 7840 case Stmt::OpaqueValueExprClass: 7841 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 7842 E = src; 7843 goto tryAgain; 7844 } 7845 return SLCT_NotALiteral; 7846 7847 case Stmt::PredefinedExprClass: 7848 // While __func__, etc., are technically not string literals, they 7849 // cannot contain format specifiers and thus are not a security 7850 // liability. 7851 return SLCT_UncheckedLiteral; 7852 7853 case Stmt::DeclRefExprClass: { 7854 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 7855 7856 // As an exception, do not flag errors for variables binding to 7857 // const string literals. 7858 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 7859 bool isConstant = false; 7860 QualType T = DR->getType(); 7861 7862 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 7863 isConstant = AT->getElementType().isConstant(S.Context); 7864 } else if (const PointerType *PT = T->getAs<PointerType>()) { 7865 isConstant = T.isConstant(S.Context) && 7866 PT->getPointeeType().isConstant(S.Context); 7867 } else if (T->isObjCObjectPointerType()) { 7868 // In ObjC, there is usually no "const ObjectPointer" type, 7869 // so don't check if the pointee type is constant. 7870 isConstant = T.isConstant(S.Context); 7871 } 7872 7873 if (isConstant) { 7874 if (const Expr *Init = VD->getAnyInitializer()) { 7875 // Look through initializers like const char c[] = { "foo" } 7876 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 7877 if (InitList->isStringLiteralInit()) 7878 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 7879 } 7880 return checkFormatStringExpr(S, Init, Args, 7881 HasVAListArg, format_idx, 7882 firstDataArg, Type, CallType, 7883 /*InFunctionCall*/ false, CheckedVarArgs, 7884 UncoveredArg, Offset); 7885 } 7886 } 7887 7888 // For vprintf* functions (i.e., HasVAListArg==true), we add a 7889 // special check to see if the format string is a function parameter 7890 // of the function calling the printf function. If the function 7891 // has an attribute indicating it is a printf-like function, then we 7892 // should suppress warnings concerning non-literals being used in a call 7893 // to a vprintf function. For example: 7894 // 7895 // void 7896 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 7897 // va_list ap; 7898 // va_start(ap, fmt); 7899 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 7900 // ... 7901 // } 7902 if (HasVAListArg) { 7903 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 7904 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 7905 int PVIndex = PV->getFunctionScopeIndex() + 1; 7906 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 7907 // adjust for implicit parameter 7908 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 7909 if (MD->isInstance()) 7910 ++PVIndex; 7911 // We also check if the formats are compatible. 7912 // We can't pass a 'scanf' string to a 'printf' function. 7913 if (PVIndex == PVFormat->getFormatIdx() && 7914 Type == S.GetFormatStringType(PVFormat)) 7915 return SLCT_UncheckedLiteral; 7916 } 7917 } 7918 } 7919 } 7920 } 7921 7922 return SLCT_NotALiteral; 7923 } 7924 7925 case Stmt::CallExprClass: 7926 case Stmt::CXXMemberCallExprClass: { 7927 const CallExpr *CE = cast<CallExpr>(E); 7928 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7929 bool IsFirst = true; 7930 StringLiteralCheckType CommonResult; 7931 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7932 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7933 StringLiteralCheckType Result = checkFormatStringExpr( 7934 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7935 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7936 IgnoreStringsWithoutSpecifiers); 7937 if (IsFirst) { 7938 CommonResult = Result; 7939 IsFirst = false; 7940 } 7941 } 7942 if (!IsFirst) 7943 return CommonResult; 7944 7945 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7946 unsigned BuiltinID = FD->getBuiltinID(); 7947 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7948 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7949 const Expr *Arg = CE->getArg(0); 7950 return checkFormatStringExpr(S, Arg, Args, 7951 HasVAListArg, format_idx, 7952 firstDataArg, Type, CallType, 7953 InFunctionCall, CheckedVarArgs, 7954 UncoveredArg, Offset, 7955 IgnoreStringsWithoutSpecifiers); 7956 } 7957 } 7958 } 7959 7960 return SLCT_NotALiteral; 7961 } 7962 case Stmt::ObjCMessageExprClass: { 7963 const auto *ME = cast<ObjCMessageExpr>(E); 7964 if (const auto *MD = ME->getMethodDecl()) { 7965 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7966 // As a special case heuristic, if we're using the method -[NSBundle 7967 // localizedStringForKey:value:table:], ignore any key strings that lack 7968 // format specifiers. The idea is that if the key doesn't have any 7969 // format specifiers then its probably just a key to map to the 7970 // localized strings. If it does have format specifiers though, then its 7971 // likely that the text of the key is the format string in the 7972 // programmer's language, and should be checked. 7973 const ObjCInterfaceDecl *IFace; 7974 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7975 IFace->getIdentifier()->isStr("NSBundle") && 7976 MD->getSelector().isKeywordSelector( 7977 {"localizedStringForKey", "value", "table"})) { 7978 IgnoreStringsWithoutSpecifiers = true; 7979 } 7980 7981 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7982 return checkFormatStringExpr( 7983 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7984 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7985 IgnoreStringsWithoutSpecifiers); 7986 } 7987 } 7988 7989 return SLCT_NotALiteral; 7990 } 7991 case Stmt::ObjCStringLiteralClass: 7992 case Stmt::StringLiteralClass: { 7993 const StringLiteral *StrE = nullptr; 7994 7995 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7996 StrE = ObjCFExpr->getString(); 7997 else 7998 StrE = cast<StringLiteral>(E); 7999 8000 if (StrE) { 8001 if (Offset.isNegative() || Offset > StrE->getLength()) { 8002 // TODO: It would be better to have an explicit warning for out of 8003 // bounds literals. 8004 return SLCT_NotALiteral; 8005 } 8006 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 8007 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 8008 firstDataArg, Type, InFunctionCall, CallType, 8009 CheckedVarArgs, UncoveredArg, 8010 IgnoreStringsWithoutSpecifiers); 8011 return SLCT_CheckedLiteral; 8012 } 8013 8014 return SLCT_NotALiteral; 8015 } 8016 case Stmt::BinaryOperatorClass: { 8017 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 8018 8019 // A string literal + an int offset is still a string literal. 8020 if (BinOp->isAdditiveOp()) { 8021 Expr::EvalResult LResult, RResult; 8022 8023 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 8024 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8025 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 8026 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 8027 8028 if (LIsInt != RIsInt) { 8029 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 8030 8031 if (LIsInt) { 8032 if (BinOpKind == BO_Add) { 8033 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 8034 E = BinOp->getRHS(); 8035 goto tryAgain; 8036 } 8037 } else { 8038 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 8039 E = BinOp->getLHS(); 8040 goto tryAgain; 8041 } 8042 } 8043 } 8044 8045 return SLCT_NotALiteral; 8046 } 8047 case Stmt::UnaryOperatorClass: { 8048 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 8049 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 8050 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 8051 Expr::EvalResult IndexResult; 8052 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 8053 Expr::SE_NoSideEffects, 8054 S.isConstantEvaluated())) { 8055 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 8056 /*RHS is int*/ true); 8057 E = ASE->getBase(); 8058 goto tryAgain; 8059 } 8060 } 8061 8062 return SLCT_NotALiteral; 8063 } 8064 8065 default: 8066 return SLCT_NotALiteral; 8067 } 8068 } 8069 8070 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 8071 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 8072 .Case("scanf", FST_Scanf) 8073 .Cases("printf", "printf0", FST_Printf) 8074 .Cases("NSString", "CFString", FST_NSString) 8075 .Case("strftime", FST_Strftime) 8076 .Case("strfmon", FST_Strfmon) 8077 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 8078 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 8079 .Case("os_trace", FST_OSLog) 8080 .Case("os_log", FST_OSLog) 8081 .Default(FST_Unknown); 8082 } 8083 8084 /// CheckFormatArguments - Check calls to printf and scanf (and similar 8085 /// functions) for correct use of format strings. 8086 /// Returns true if a format string has been fully checked. 8087 bool Sema::CheckFormatArguments(const FormatAttr *Format, 8088 ArrayRef<const Expr *> Args, 8089 bool IsCXXMember, 8090 VariadicCallType CallType, 8091 SourceLocation Loc, SourceRange Range, 8092 llvm::SmallBitVector &CheckedVarArgs) { 8093 FormatStringInfo FSI; 8094 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 8095 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 8096 FSI.FirstDataArg, GetFormatStringType(Format), 8097 CallType, Loc, Range, CheckedVarArgs); 8098 return false; 8099 } 8100 8101 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 8102 bool HasVAListArg, unsigned format_idx, 8103 unsigned firstDataArg, FormatStringType Type, 8104 VariadicCallType CallType, 8105 SourceLocation Loc, SourceRange Range, 8106 llvm::SmallBitVector &CheckedVarArgs) { 8107 // CHECK: printf/scanf-like function is called with no format string. 8108 if (format_idx >= Args.size()) { 8109 Diag(Loc, diag::warn_missing_format_string) << Range; 8110 return false; 8111 } 8112 8113 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 8114 8115 // CHECK: format string is not a string literal. 8116 // 8117 // Dynamically generated format strings are difficult to 8118 // automatically vet at compile time. Requiring that format strings 8119 // are string literals: (1) permits the checking of format strings by 8120 // the compiler and thereby (2) can practically remove the source of 8121 // many format string exploits. 8122 8123 // Format string can be either ObjC string (e.g. @"%d") or 8124 // C string (e.g. "%d") 8125 // ObjC string uses the same format specifiers as C string, so we can use 8126 // the same format string checking logic for both ObjC and C strings. 8127 UncoveredArgHandler UncoveredArg; 8128 StringLiteralCheckType CT = 8129 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 8130 format_idx, firstDataArg, Type, CallType, 8131 /*IsFunctionCall*/ true, CheckedVarArgs, 8132 UncoveredArg, 8133 /*no string offset*/ llvm::APSInt(64, false) = 0); 8134 8135 // Generate a diagnostic where an uncovered argument is detected. 8136 if (UncoveredArg.hasUncoveredArg()) { 8137 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 8138 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 8139 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 8140 } 8141 8142 if (CT != SLCT_NotALiteral) 8143 // Literal format string found, check done! 8144 return CT == SLCT_CheckedLiteral; 8145 8146 // Strftime is particular as it always uses a single 'time' argument, 8147 // so it is safe to pass a non-literal string. 8148 if (Type == FST_Strftime) 8149 return false; 8150 8151 // Do not emit diag when the string param is a macro expansion and the 8152 // format is either NSString or CFString. This is a hack to prevent 8153 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 8154 // which are usually used in place of NS and CF string literals. 8155 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 8156 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 8157 return false; 8158 8159 // If there are no arguments specified, warn with -Wformat-security, otherwise 8160 // warn only with -Wformat-nonliteral. 8161 if (Args.size() == firstDataArg) { 8162 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 8163 << OrigFormatExpr->getSourceRange(); 8164 switch (Type) { 8165 default: 8166 break; 8167 case FST_Kprintf: 8168 case FST_FreeBSDKPrintf: 8169 case FST_Printf: 8170 Diag(FormatLoc, diag::note_format_security_fixit) 8171 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 8172 break; 8173 case FST_NSString: 8174 Diag(FormatLoc, diag::note_format_security_fixit) 8175 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 8176 break; 8177 } 8178 } else { 8179 Diag(FormatLoc, diag::warn_format_nonliteral) 8180 << OrigFormatExpr->getSourceRange(); 8181 } 8182 return false; 8183 } 8184 8185 namespace { 8186 8187 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 8188 protected: 8189 Sema &S; 8190 const FormatStringLiteral *FExpr; 8191 const Expr *OrigFormatExpr; 8192 const Sema::FormatStringType FSType; 8193 const unsigned FirstDataArg; 8194 const unsigned NumDataArgs; 8195 const char *Beg; // Start of format string. 8196 const bool HasVAListArg; 8197 ArrayRef<const Expr *> Args; 8198 unsigned FormatIdx; 8199 llvm::SmallBitVector CoveredArgs; 8200 bool usesPositionalArgs = false; 8201 bool atFirstArg = true; 8202 bool inFunctionCall; 8203 Sema::VariadicCallType CallType; 8204 llvm::SmallBitVector &CheckedVarArgs; 8205 UncoveredArgHandler &UncoveredArg; 8206 8207 public: 8208 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 8209 const Expr *origFormatExpr, 8210 const Sema::FormatStringType type, unsigned firstDataArg, 8211 unsigned numDataArgs, const char *beg, bool hasVAListArg, 8212 ArrayRef<const Expr *> Args, unsigned formatIdx, 8213 bool inFunctionCall, Sema::VariadicCallType callType, 8214 llvm::SmallBitVector &CheckedVarArgs, 8215 UncoveredArgHandler &UncoveredArg) 8216 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 8217 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 8218 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 8219 inFunctionCall(inFunctionCall), CallType(callType), 8220 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 8221 CoveredArgs.resize(numDataArgs); 8222 CoveredArgs.reset(); 8223 } 8224 8225 void DoneProcessing(); 8226 8227 void HandleIncompleteSpecifier(const char *startSpecifier, 8228 unsigned specifierLen) override; 8229 8230 void HandleInvalidLengthModifier( 8231 const analyze_format_string::FormatSpecifier &FS, 8232 const analyze_format_string::ConversionSpecifier &CS, 8233 const char *startSpecifier, unsigned specifierLen, 8234 unsigned DiagID); 8235 8236 void HandleNonStandardLengthModifier( 8237 const analyze_format_string::FormatSpecifier &FS, 8238 const char *startSpecifier, unsigned specifierLen); 8239 8240 void HandleNonStandardConversionSpecifier( 8241 const analyze_format_string::ConversionSpecifier &CS, 8242 const char *startSpecifier, unsigned specifierLen); 8243 8244 void HandlePosition(const char *startPos, unsigned posLen) override; 8245 8246 void HandleInvalidPosition(const char *startSpecifier, 8247 unsigned specifierLen, 8248 analyze_format_string::PositionContext p) override; 8249 8250 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 8251 8252 void HandleNullChar(const char *nullCharacter) override; 8253 8254 template <typename Range> 8255 static void 8256 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 8257 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 8258 bool IsStringLocation, Range StringRange, 8259 ArrayRef<FixItHint> Fixit = None); 8260 8261 protected: 8262 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 8263 const char *startSpec, 8264 unsigned specifierLen, 8265 const char *csStart, unsigned csLen); 8266 8267 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 8268 const char *startSpec, 8269 unsigned specifierLen); 8270 8271 SourceRange getFormatStringRange(); 8272 CharSourceRange getSpecifierRange(const char *startSpecifier, 8273 unsigned specifierLen); 8274 SourceLocation getLocationOfByte(const char *x); 8275 8276 const Expr *getDataArg(unsigned i) const; 8277 8278 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 8279 const analyze_format_string::ConversionSpecifier &CS, 8280 const char *startSpecifier, unsigned specifierLen, 8281 unsigned argIndex); 8282 8283 template <typename Range> 8284 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 8285 bool IsStringLocation, Range StringRange, 8286 ArrayRef<FixItHint> Fixit = None); 8287 }; 8288 8289 } // namespace 8290 8291 SourceRange CheckFormatHandler::getFormatStringRange() { 8292 return OrigFormatExpr->getSourceRange(); 8293 } 8294 8295 CharSourceRange CheckFormatHandler:: 8296 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 8297 SourceLocation Start = getLocationOfByte(startSpecifier); 8298 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 8299 8300 // Advance the end SourceLocation by one due to half-open ranges. 8301 End = End.getLocWithOffset(1); 8302 8303 return CharSourceRange::getCharRange(Start, End); 8304 } 8305 8306 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 8307 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 8308 S.getLangOpts(), S.Context.getTargetInfo()); 8309 } 8310 8311 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 8312 unsigned specifierLen){ 8313 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 8314 getLocationOfByte(startSpecifier), 8315 /*IsStringLocation*/true, 8316 getSpecifierRange(startSpecifier, specifierLen)); 8317 } 8318 8319 void CheckFormatHandler::HandleInvalidLengthModifier( 8320 const analyze_format_string::FormatSpecifier &FS, 8321 const analyze_format_string::ConversionSpecifier &CS, 8322 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 8323 using namespace analyze_format_string; 8324 8325 const LengthModifier &LM = FS.getLengthModifier(); 8326 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8327 8328 // See if we know how to fix this length modifier. 8329 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8330 if (FixedLM) { 8331 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8332 getLocationOfByte(LM.getStart()), 8333 /*IsStringLocation*/true, 8334 getSpecifierRange(startSpecifier, specifierLen)); 8335 8336 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8337 << FixedLM->toString() 8338 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8339 8340 } else { 8341 FixItHint Hint; 8342 if (DiagID == diag::warn_format_nonsensical_length) 8343 Hint = FixItHint::CreateRemoval(LMRange); 8344 8345 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 8346 getLocationOfByte(LM.getStart()), 8347 /*IsStringLocation*/true, 8348 getSpecifierRange(startSpecifier, specifierLen), 8349 Hint); 8350 } 8351 } 8352 8353 void CheckFormatHandler::HandleNonStandardLengthModifier( 8354 const analyze_format_string::FormatSpecifier &FS, 8355 const char *startSpecifier, unsigned specifierLen) { 8356 using namespace analyze_format_string; 8357 8358 const LengthModifier &LM = FS.getLengthModifier(); 8359 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 8360 8361 // See if we know how to fix this length modifier. 8362 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 8363 if (FixedLM) { 8364 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8365 << LM.toString() << 0, 8366 getLocationOfByte(LM.getStart()), 8367 /*IsStringLocation*/true, 8368 getSpecifierRange(startSpecifier, specifierLen)); 8369 8370 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 8371 << FixedLM->toString() 8372 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 8373 8374 } else { 8375 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8376 << LM.toString() << 0, 8377 getLocationOfByte(LM.getStart()), 8378 /*IsStringLocation*/true, 8379 getSpecifierRange(startSpecifier, specifierLen)); 8380 } 8381 } 8382 8383 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 8384 const analyze_format_string::ConversionSpecifier &CS, 8385 const char *startSpecifier, unsigned specifierLen) { 8386 using namespace analyze_format_string; 8387 8388 // See if we know how to fix this conversion specifier. 8389 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 8390 if (FixedCS) { 8391 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8392 << CS.toString() << /*conversion specifier*/1, 8393 getLocationOfByte(CS.getStart()), 8394 /*IsStringLocation*/true, 8395 getSpecifierRange(startSpecifier, specifierLen)); 8396 8397 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 8398 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 8399 << FixedCS->toString() 8400 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 8401 } else { 8402 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 8403 << CS.toString() << /*conversion specifier*/1, 8404 getLocationOfByte(CS.getStart()), 8405 /*IsStringLocation*/true, 8406 getSpecifierRange(startSpecifier, specifierLen)); 8407 } 8408 } 8409 8410 void CheckFormatHandler::HandlePosition(const char *startPos, 8411 unsigned posLen) { 8412 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 8413 getLocationOfByte(startPos), 8414 /*IsStringLocation*/true, 8415 getSpecifierRange(startPos, posLen)); 8416 } 8417 8418 void 8419 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 8420 analyze_format_string::PositionContext p) { 8421 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 8422 << (unsigned) p, 8423 getLocationOfByte(startPos), /*IsStringLocation*/true, 8424 getSpecifierRange(startPos, posLen)); 8425 } 8426 8427 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 8428 unsigned posLen) { 8429 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 8430 getLocationOfByte(startPos), 8431 /*IsStringLocation*/true, 8432 getSpecifierRange(startPos, posLen)); 8433 } 8434 8435 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 8436 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 8437 // The presence of a null character is likely an error. 8438 EmitFormatDiagnostic( 8439 S.PDiag(diag::warn_printf_format_string_contains_null_char), 8440 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 8441 getFormatStringRange()); 8442 } 8443 } 8444 8445 // Note that this may return NULL if there was an error parsing or building 8446 // one of the argument expressions. 8447 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 8448 return Args[FirstDataArg + i]; 8449 } 8450 8451 void CheckFormatHandler::DoneProcessing() { 8452 // Does the number of data arguments exceed the number of 8453 // format conversions in the format string? 8454 if (!HasVAListArg) { 8455 // Find any arguments that weren't covered. 8456 CoveredArgs.flip(); 8457 signed notCoveredArg = CoveredArgs.find_first(); 8458 if (notCoveredArg >= 0) { 8459 assert((unsigned)notCoveredArg < NumDataArgs); 8460 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 8461 } else { 8462 UncoveredArg.setAllCovered(); 8463 } 8464 } 8465 } 8466 8467 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 8468 const Expr *ArgExpr) { 8469 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 8470 "Invalid state"); 8471 8472 if (!ArgExpr) 8473 return; 8474 8475 SourceLocation Loc = ArgExpr->getBeginLoc(); 8476 8477 if (S.getSourceManager().isInSystemMacro(Loc)) 8478 return; 8479 8480 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 8481 for (auto E : DiagnosticExprs) 8482 PDiag << E->getSourceRange(); 8483 8484 CheckFormatHandler::EmitFormatDiagnostic( 8485 S, IsFunctionCall, DiagnosticExprs[0], 8486 PDiag, Loc, /*IsStringLocation*/false, 8487 DiagnosticExprs[0]->getSourceRange()); 8488 } 8489 8490 bool 8491 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 8492 SourceLocation Loc, 8493 const char *startSpec, 8494 unsigned specifierLen, 8495 const char *csStart, 8496 unsigned csLen) { 8497 bool keepGoing = true; 8498 if (argIndex < NumDataArgs) { 8499 // Consider the argument coverered, even though the specifier doesn't 8500 // make sense. 8501 CoveredArgs.set(argIndex); 8502 } 8503 else { 8504 // If argIndex exceeds the number of data arguments we 8505 // don't issue a warning because that is just a cascade of warnings (and 8506 // they may have intended '%%' anyway). We don't want to continue processing 8507 // the format string after this point, however, as we will like just get 8508 // gibberish when trying to match arguments. 8509 keepGoing = false; 8510 } 8511 8512 StringRef Specifier(csStart, csLen); 8513 8514 // If the specifier in non-printable, it could be the first byte of a UTF-8 8515 // sequence. In that case, print the UTF-8 code point. If not, print the byte 8516 // hex value. 8517 std::string CodePointStr; 8518 if (!llvm::sys::locale::isPrint(*csStart)) { 8519 llvm::UTF32 CodePoint; 8520 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 8521 const llvm::UTF8 *E = 8522 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 8523 llvm::ConversionResult Result = 8524 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 8525 8526 if (Result != llvm::conversionOK) { 8527 unsigned char FirstChar = *csStart; 8528 CodePoint = (llvm::UTF32)FirstChar; 8529 } 8530 8531 llvm::raw_string_ostream OS(CodePointStr); 8532 if (CodePoint < 256) 8533 OS << "\\x" << llvm::format("%02x", CodePoint); 8534 else if (CodePoint <= 0xFFFF) 8535 OS << "\\u" << llvm::format("%04x", CodePoint); 8536 else 8537 OS << "\\U" << llvm::format("%08x", CodePoint); 8538 OS.flush(); 8539 Specifier = CodePointStr; 8540 } 8541 8542 EmitFormatDiagnostic( 8543 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 8544 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 8545 8546 return keepGoing; 8547 } 8548 8549 void 8550 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 8551 const char *startSpec, 8552 unsigned specifierLen) { 8553 EmitFormatDiagnostic( 8554 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 8555 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 8556 } 8557 8558 bool 8559 CheckFormatHandler::CheckNumArgs( 8560 const analyze_format_string::FormatSpecifier &FS, 8561 const analyze_format_string::ConversionSpecifier &CS, 8562 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 8563 8564 if (argIndex >= NumDataArgs) { 8565 PartialDiagnostic PDiag = FS.usesPositionalArg() 8566 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 8567 << (argIndex+1) << NumDataArgs) 8568 : S.PDiag(diag::warn_printf_insufficient_data_args); 8569 EmitFormatDiagnostic( 8570 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 8571 getSpecifierRange(startSpecifier, specifierLen)); 8572 8573 // Since more arguments than conversion tokens are given, by extension 8574 // all arguments are covered, so mark this as so. 8575 UncoveredArg.setAllCovered(); 8576 return false; 8577 } 8578 return true; 8579 } 8580 8581 template<typename Range> 8582 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 8583 SourceLocation Loc, 8584 bool IsStringLocation, 8585 Range StringRange, 8586 ArrayRef<FixItHint> FixIt) { 8587 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 8588 Loc, IsStringLocation, StringRange, FixIt); 8589 } 8590 8591 /// If the format string is not within the function call, emit a note 8592 /// so that the function call and string are in diagnostic messages. 8593 /// 8594 /// \param InFunctionCall if true, the format string is within the function 8595 /// call and only one diagnostic message will be produced. Otherwise, an 8596 /// extra note will be emitted pointing to location of the format string. 8597 /// 8598 /// \param ArgumentExpr the expression that is passed as the format string 8599 /// argument in the function call. Used for getting locations when two 8600 /// diagnostics are emitted. 8601 /// 8602 /// \param PDiag the callee should already have provided any strings for the 8603 /// diagnostic message. This function only adds locations and fixits 8604 /// to diagnostics. 8605 /// 8606 /// \param Loc primary location for diagnostic. If two diagnostics are 8607 /// required, one will be at Loc and a new SourceLocation will be created for 8608 /// the other one. 8609 /// 8610 /// \param IsStringLocation if true, Loc points to the format string should be 8611 /// used for the note. Otherwise, Loc points to the argument list and will 8612 /// be used with PDiag. 8613 /// 8614 /// \param StringRange some or all of the string to highlight. This is 8615 /// templated so it can accept either a CharSourceRange or a SourceRange. 8616 /// 8617 /// \param FixIt optional fix it hint for the format string. 8618 template <typename Range> 8619 void CheckFormatHandler::EmitFormatDiagnostic( 8620 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 8621 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 8622 Range StringRange, ArrayRef<FixItHint> FixIt) { 8623 if (InFunctionCall) { 8624 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 8625 D << StringRange; 8626 D << FixIt; 8627 } else { 8628 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 8629 << ArgumentExpr->getSourceRange(); 8630 8631 const Sema::SemaDiagnosticBuilder &Note = 8632 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 8633 diag::note_format_string_defined); 8634 8635 Note << StringRange; 8636 Note << FixIt; 8637 } 8638 } 8639 8640 //===--- CHECK: Printf format string checking ------------------------------===// 8641 8642 namespace { 8643 8644 class CheckPrintfHandler : public CheckFormatHandler { 8645 public: 8646 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 8647 const Expr *origFormatExpr, 8648 const Sema::FormatStringType type, unsigned firstDataArg, 8649 unsigned numDataArgs, bool isObjC, const char *beg, 8650 bool hasVAListArg, ArrayRef<const Expr *> Args, 8651 unsigned formatIdx, bool inFunctionCall, 8652 Sema::VariadicCallType CallType, 8653 llvm::SmallBitVector &CheckedVarArgs, 8654 UncoveredArgHandler &UncoveredArg) 8655 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8656 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8657 inFunctionCall, CallType, CheckedVarArgs, 8658 UncoveredArg) {} 8659 8660 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 8661 8662 /// Returns true if '%@' specifiers are allowed in the format string. 8663 bool allowsObjCArg() const { 8664 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 8665 FSType == Sema::FST_OSTrace; 8666 } 8667 8668 bool HandleInvalidPrintfConversionSpecifier( 8669 const analyze_printf::PrintfSpecifier &FS, 8670 const char *startSpecifier, 8671 unsigned specifierLen) override; 8672 8673 void handleInvalidMaskType(StringRef MaskType) override; 8674 8675 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 8676 const char *startSpecifier, 8677 unsigned specifierLen) override; 8678 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8679 const char *StartSpecifier, 8680 unsigned SpecifierLen, 8681 const Expr *E); 8682 8683 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 8684 const char *startSpecifier, unsigned specifierLen); 8685 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 8686 const analyze_printf::OptionalAmount &Amt, 8687 unsigned type, 8688 const char *startSpecifier, unsigned specifierLen); 8689 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8690 const analyze_printf::OptionalFlag &flag, 8691 const char *startSpecifier, unsigned specifierLen); 8692 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 8693 const analyze_printf::OptionalFlag &ignoredFlag, 8694 const analyze_printf::OptionalFlag &flag, 8695 const char *startSpecifier, unsigned specifierLen); 8696 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 8697 const Expr *E); 8698 8699 void HandleEmptyObjCModifierFlag(const char *startFlag, 8700 unsigned flagLen) override; 8701 8702 void HandleInvalidObjCModifierFlag(const char *startFlag, 8703 unsigned flagLen) override; 8704 8705 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 8706 const char *flagsEnd, 8707 const char *conversionPosition) 8708 override; 8709 }; 8710 8711 } // namespace 8712 8713 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 8714 const analyze_printf::PrintfSpecifier &FS, 8715 const char *startSpecifier, 8716 unsigned specifierLen) { 8717 const analyze_printf::PrintfConversionSpecifier &CS = 8718 FS.getConversionSpecifier(); 8719 8720 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8721 getLocationOfByte(CS.getStart()), 8722 startSpecifier, specifierLen, 8723 CS.getStart(), CS.getLength()); 8724 } 8725 8726 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 8727 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 8728 } 8729 8730 bool CheckPrintfHandler::HandleAmount( 8731 const analyze_format_string::OptionalAmount &Amt, 8732 unsigned k, const char *startSpecifier, 8733 unsigned specifierLen) { 8734 if (Amt.hasDataArgument()) { 8735 if (!HasVAListArg) { 8736 unsigned argIndex = Amt.getArgIndex(); 8737 if (argIndex >= NumDataArgs) { 8738 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 8739 << k, 8740 getLocationOfByte(Amt.getStart()), 8741 /*IsStringLocation*/true, 8742 getSpecifierRange(startSpecifier, specifierLen)); 8743 // Don't do any more checking. We will just emit 8744 // spurious errors. 8745 return false; 8746 } 8747 8748 // Type check the data argument. It should be an 'int'. 8749 // Although not in conformance with C99, we also allow the argument to be 8750 // an 'unsigned int' as that is a reasonably safe case. GCC also 8751 // doesn't emit a warning for that case. 8752 CoveredArgs.set(argIndex); 8753 const Expr *Arg = getDataArg(argIndex); 8754 if (!Arg) 8755 return false; 8756 8757 QualType T = Arg->getType(); 8758 8759 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 8760 assert(AT.isValid()); 8761 8762 if (!AT.matchesType(S.Context, T)) { 8763 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 8764 << k << AT.getRepresentativeTypeName(S.Context) 8765 << T << Arg->getSourceRange(), 8766 getLocationOfByte(Amt.getStart()), 8767 /*IsStringLocation*/true, 8768 getSpecifierRange(startSpecifier, specifierLen)); 8769 // Don't do any more checking. We will just emit 8770 // spurious errors. 8771 return false; 8772 } 8773 } 8774 } 8775 return true; 8776 } 8777 8778 void CheckPrintfHandler::HandleInvalidAmount( 8779 const analyze_printf::PrintfSpecifier &FS, 8780 const analyze_printf::OptionalAmount &Amt, 8781 unsigned type, 8782 const char *startSpecifier, 8783 unsigned specifierLen) { 8784 const analyze_printf::PrintfConversionSpecifier &CS = 8785 FS.getConversionSpecifier(); 8786 8787 FixItHint fixit = 8788 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 8789 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 8790 Amt.getConstantLength())) 8791 : FixItHint(); 8792 8793 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 8794 << type << CS.toString(), 8795 getLocationOfByte(Amt.getStart()), 8796 /*IsStringLocation*/true, 8797 getSpecifierRange(startSpecifier, specifierLen), 8798 fixit); 8799 } 8800 8801 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 8802 const analyze_printf::OptionalFlag &flag, 8803 const char *startSpecifier, 8804 unsigned specifierLen) { 8805 // Warn about pointless flag with a fixit removal. 8806 const analyze_printf::PrintfConversionSpecifier &CS = 8807 FS.getConversionSpecifier(); 8808 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 8809 << flag.toString() << CS.toString(), 8810 getLocationOfByte(flag.getPosition()), 8811 /*IsStringLocation*/true, 8812 getSpecifierRange(startSpecifier, specifierLen), 8813 FixItHint::CreateRemoval( 8814 getSpecifierRange(flag.getPosition(), 1))); 8815 } 8816 8817 void CheckPrintfHandler::HandleIgnoredFlag( 8818 const analyze_printf::PrintfSpecifier &FS, 8819 const analyze_printf::OptionalFlag &ignoredFlag, 8820 const analyze_printf::OptionalFlag &flag, 8821 const char *startSpecifier, 8822 unsigned specifierLen) { 8823 // Warn about ignored flag with a fixit removal. 8824 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 8825 << ignoredFlag.toString() << flag.toString(), 8826 getLocationOfByte(ignoredFlag.getPosition()), 8827 /*IsStringLocation*/true, 8828 getSpecifierRange(startSpecifier, specifierLen), 8829 FixItHint::CreateRemoval( 8830 getSpecifierRange(ignoredFlag.getPosition(), 1))); 8831 } 8832 8833 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 8834 unsigned flagLen) { 8835 // Warn about an empty flag. 8836 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 8837 getLocationOfByte(startFlag), 8838 /*IsStringLocation*/true, 8839 getSpecifierRange(startFlag, flagLen)); 8840 } 8841 8842 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 8843 unsigned flagLen) { 8844 // Warn about an invalid flag. 8845 auto Range = getSpecifierRange(startFlag, flagLen); 8846 StringRef flag(startFlag, flagLen); 8847 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 8848 getLocationOfByte(startFlag), 8849 /*IsStringLocation*/true, 8850 Range, FixItHint::CreateRemoval(Range)); 8851 } 8852 8853 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 8854 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 8855 // Warn about using '[...]' without a '@' conversion. 8856 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 8857 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 8858 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 8859 getLocationOfByte(conversionPosition), 8860 /*IsStringLocation*/true, 8861 Range, FixItHint::CreateRemoval(Range)); 8862 } 8863 8864 // Determines if the specified is a C++ class or struct containing 8865 // a member with the specified name and kind (e.g. a CXXMethodDecl named 8866 // "c_str()"). 8867 template<typename MemberKind> 8868 static llvm::SmallPtrSet<MemberKind*, 1> 8869 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 8870 const RecordType *RT = Ty->getAs<RecordType>(); 8871 llvm::SmallPtrSet<MemberKind*, 1> Results; 8872 8873 if (!RT) 8874 return Results; 8875 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 8876 if (!RD || !RD->getDefinition()) 8877 return Results; 8878 8879 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 8880 Sema::LookupMemberName); 8881 R.suppressDiagnostics(); 8882 8883 // We just need to include all members of the right kind turned up by the 8884 // filter, at this point. 8885 if (S.LookupQualifiedName(R, RT->getDecl())) 8886 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 8887 NamedDecl *decl = (*I)->getUnderlyingDecl(); 8888 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 8889 Results.insert(FK); 8890 } 8891 return Results; 8892 } 8893 8894 /// Check if we could call '.c_str()' on an object. 8895 /// 8896 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 8897 /// allow the call, or if it would be ambiguous). 8898 bool Sema::hasCStrMethod(const Expr *E) { 8899 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8900 8901 MethodSet Results = 8902 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 8903 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8904 MI != ME; ++MI) 8905 if ((*MI)->getMinRequiredArguments() == 0) 8906 return true; 8907 return false; 8908 } 8909 8910 // Check if a (w)string was passed when a (w)char* was needed, and offer a 8911 // better diagnostic if so. AT is assumed to be valid. 8912 // Returns true when a c_str() conversion method is found. 8913 bool CheckPrintfHandler::checkForCStrMembers( 8914 const analyze_printf::ArgType &AT, const Expr *E) { 8915 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 8916 8917 MethodSet Results = 8918 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 8919 8920 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8921 MI != ME; ++MI) { 8922 const CXXMethodDecl *Method = *MI; 8923 if (Method->getMinRequiredArguments() == 0 && 8924 AT.matchesType(S.Context, Method->getReturnType())) { 8925 // FIXME: Suggest parens if the expression needs them. 8926 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8927 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8928 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8929 return true; 8930 } 8931 } 8932 8933 return false; 8934 } 8935 8936 bool 8937 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8938 &FS, 8939 const char *startSpecifier, 8940 unsigned specifierLen) { 8941 using namespace analyze_format_string; 8942 using namespace analyze_printf; 8943 8944 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8945 8946 if (FS.consumesDataArgument()) { 8947 if (atFirstArg) { 8948 atFirstArg = false; 8949 usesPositionalArgs = FS.usesPositionalArg(); 8950 } 8951 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8952 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8953 startSpecifier, specifierLen); 8954 return false; 8955 } 8956 } 8957 8958 // First check if the field width, precision, and conversion specifier 8959 // have matching data arguments. 8960 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8961 startSpecifier, specifierLen)) { 8962 return false; 8963 } 8964 8965 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8966 startSpecifier, specifierLen)) { 8967 return false; 8968 } 8969 8970 if (!CS.consumesDataArgument()) { 8971 // FIXME: Technically specifying a precision or field width here 8972 // makes no sense. Worth issuing a warning at some point. 8973 return true; 8974 } 8975 8976 // Consume the argument. 8977 unsigned argIndex = FS.getArgIndex(); 8978 if (argIndex < NumDataArgs) { 8979 // The check to see if the argIndex is valid will come later. 8980 // We set the bit here because we may exit early from this 8981 // function if we encounter some other error. 8982 CoveredArgs.set(argIndex); 8983 } 8984 8985 // FreeBSD kernel extensions. 8986 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8987 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8988 // We need at least two arguments. 8989 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8990 return false; 8991 8992 // Claim the second argument. 8993 CoveredArgs.set(argIndex + 1); 8994 8995 // Type check the first argument (int for %b, pointer for %D) 8996 const Expr *Ex = getDataArg(argIndex); 8997 const analyze_printf::ArgType &AT = 8998 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8999 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 9000 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 9001 EmitFormatDiagnostic( 9002 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9003 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 9004 << false << Ex->getSourceRange(), 9005 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9006 getSpecifierRange(startSpecifier, specifierLen)); 9007 9008 // Type check the second argument (char * for both %b and %D) 9009 Ex = getDataArg(argIndex + 1); 9010 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 9011 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 9012 EmitFormatDiagnostic( 9013 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9014 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 9015 << false << Ex->getSourceRange(), 9016 Ex->getBeginLoc(), /*IsStringLocation*/ false, 9017 getSpecifierRange(startSpecifier, specifierLen)); 9018 9019 return true; 9020 } 9021 9022 // Check for using an Objective-C specific conversion specifier 9023 // in a non-ObjC literal. 9024 if (!allowsObjCArg() && CS.isObjCArg()) { 9025 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9026 specifierLen); 9027 } 9028 9029 // %P can only be used with os_log. 9030 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 9031 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9032 specifierLen); 9033 } 9034 9035 // %n is not allowed with os_log. 9036 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 9037 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 9038 getLocationOfByte(CS.getStart()), 9039 /*IsStringLocation*/ false, 9040 getSpecifierRange(startSpecifier, specifierLen)); 9041 9042 return true; 9043 } 9044 9045 // Only scalars are allowed for os_trace. 9046 if (FSType == Sema::FST_OSTrace && 9047 (CS.getKind() == ConversionSpecifier::PArg || 9048 CS.getKind() == ConversionSpecifier::sArg || 9049 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 9050 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 9051 specifierLen); 9052 } 9053 9054 // Check for use of public/private annotation outside of os_log(). 9055 if (FSType != Sema::FST_OSLog) { 9056 if (FS.isPublic().isSet()) { 9057 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9058 << "public", 9059 getLocationOfByte(FS.isPublic().getPosition()), 9060 /*IsStringLocation*/ false, 9061 getSpecifierRange(startSpecifier, specifierLen)); 9062 } 9063 if (FS.isPrivate().isSet()) { 9064 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 9065 << "private", 9066 getLocationOfByte(FS.isPrivate().getPosition()), 9067 /*IsStringLocation*/ false, 9068 getSpecifierRange(startSpecifier, specifierLen)); 9069 } 9070 } 9071 9072 // Check for invalid use of field width 9073 if (!FS.hasValidFieldWidth()) { 9074 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 9075 startSpecifier, specifierLen); 9076 } 9077 9078 // Check for invalid use of precision 9079 if (!FS.hasValidPrecision()) { 9080 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 9081 startSpecifier, specifierLen); 9082 } 9083 9084 // Precision is mandatory for %P specifier. 9085 if (CS.getKind() == ConversionSpecifier::PArg && 9086 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 9087 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 9088 getLocationOfByte(startSpecifier), 9089 /*IsStringLocation*/ false, 9090 getSpecifierRange(startSpecifier, specifierLen)); 9091 } 9092 9093 // Check each flag does not conflict with any other component. 9094 if (!FS.hasValidThousandsGroupingPrefix()) 9095 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 9096 if (!FS.hasValidLeadingZeros()) 9097 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 9098 if (!FS.hasValidPlusPrefix()) 9099 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 9100 if (!FS.hasValidSpacePrefix()) 9101 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 9102 if (!FS.hasValidAlternativeForm()) 9103 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 9104 if (!FS.hasValidLeftJustified()) 9105 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 9106 9107 // Check that flags are not ignored by another flag 9108 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 9109 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 9110 startSpecifier, specifierLen); 9111 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 9112 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 9113 startSpecifier, specifierLen); 9114 9115 // Check the length modifier is valid with the given conversion specifier. 9116 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9117 S.getLangOpts())) 9118 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9119 diag::warn_format_nonsensical_length); 9120 else if (!FS.hasStandardLengthModifier()) 9121 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9122 else if (!FS.hasStandardLengthConversionCombination()) 9123 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9124 diag::warn_format_non_standard_conversion_spec); 9125 9126 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9127 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9128 9129 // The remaining checks depend on the data arguments. 9130 if (HasVAListArg) 9131 return true; 9132 9133 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9134 return false; 9135 9136 const Expr *Arg = getDataArg(argIndex); 9137 if (!Arg) 9138 return true; 9139 9140 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 9141 } 9142 9143 static bool requiresParensToAddCast(const Expr *E) { 9144 // FIXME: We should have a general way to reason about operator 9145 // precedence and whether parens are actually needed here. 9146 // Take care of a few common cases where they aren't. 9147 const Expr *Inside = E->IgnoreImpCasts(); 9148 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 9149 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 9150 9151 switch (Inside->getStmtClass()) { 9152 case Stmt::ArraySubscriptExprClass: 9153 case Stmt::CallExprClass: 9154 case Stmt::CharacterLiteralClass: 9155 case Stmt::CXXBoolLiteralExprClass: 9156 case Stmt::DeclRefExprClass: 9157 case Stmt::FloatingLiteralClass: 9158 case Stmt::IntegerLiteralClass: 9159 case Stmt::MemberExprClass: 9160 case Stmt::ObjCArrayLiteralClass: 9161 case Stmt::ObjCBoolLiteralExprClass: 9162 case Stmt::ObjCBoxedExprClass: 9163 case Stmt::ObjCDictionaryLiteralClass: 9164 case Stmt::ObjCEncodeExprClass: 9165 case Stmt::ObjCIvarRefExprClass: 9166 case Stmt::ObjCMessageExprClass: 9167 case Stmt::ObjCPropertyRefExprClass: 9168 case Stmt::ObjCStringLiteralClass: 9169 case Stmt::ObjCSubscriptRefExprClass: 9170 case Stmt::ParenExprClass: 9171 case Stmt::StringLiteralClass: 9172 case Stmt::UnaryOperatorClass: 9173 return false; 9174 default: 9175 return true; 9176 } 9177 } 9178 9179 static std::pair<QualType, StringRef> 9180 shouldNotPrintDirectly(const ASTContext &Context, 9181 QualType IntendedTy, 9182 const Expr *E) { 9183 // Use a 'while' to peel off layers of typedefs. 9184 QualType TyTy = IntendedTy; 9185 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 9186 StringRef Name = UserTy->getDecl()->getName(); 9187 QualType CastTy = llvm::StringSwitch<QualType>(Name) 9188 .Case("CFIndex", Context.getNSIntegerType()) 9189 .Case("NSInteger", Context.getNSIntegerType()) 9190 .Case("NSUInteger", Context.getNSUIntegerType()) 9191 .Case("SInt32", Context.IntTy) 9192 .Case("UInt32", Context.UnsignedIntTy) 9193 .Default(QualType()); 9194 9195 if (!CastTy.isNull()) 9196 return std::make_pair(CastTy, Name); 9197 9198 TyTy = UserTy->desugar(); 9199 } 9200 9201 // Strip parens if necessary. 9202 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 9203 return shouldNotPrintDirectly(Context, 9204 PE->getSubExpr()->getType(), 9205 PE->getSubExpr()); 9206 9207 // If this is a conditional expression, then its result type is constructed 9208 // via usual arithmetic conversions and thus there might be no necessary 9209 // typedef sugar there. Recurse to operands to check for NSInteger & 9210 // Co. usage condition. 9211 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 9212 QualType TrueTy, FalseTy; 9213 StringRef TrueName, FalseName; 9214 9215 std::tie(TrueTy, TrueName) = 9216 shouldNotPrintDirectly(Context, 9217 CO->getTrueExpr()->getType(), 9218 CO->getTrueExpr()); 9219 std::tie(FalseTy, FalseName) = 9220 shouldNotPrintDirectly(Context, 9221 CO->getFalseExpr()->getType(), 9222 CO->getFalseExpr()); 9223 9224 if (TrueTy == FalseTy) 9225 return std::make_pair(TrueTy, TrueName); 9226 else if (TrueTy.isNull()) 9227 return std::make_pair(FalseTy, FalseName); 9228 else if (FalseTy.isNull()) 9229 return std::make_pair(TrueTy, TrueName); 9230 } 9231 9232 return std::make_pair(QualType(), StringRef()); 9233 } 9234 9235 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 9236 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 9237 /// type do not count. 9238 static bool 9239 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 9240 QualType From = ICE->getSubExpr()->getType(); 9241 QualType To = ICE->getType(); 9242 // It's an integer promotion if the destination type is the promoted 9243 // source type. 9244 if (ICE->getCastKind() == CK_IntegralCast && 9245 From->isPromotableIntegerType() && 9246 S.Context.getPromotedIntegerType(From) == To) 9247 return true; 9248 // Look through vector types, since we do default argument promotion for 9249 // those in OpenCL. 9250 if (const auto *VecTy = From->getAs<ExtVectorType>()) 9251 From = VecTy->getElementType(); 9252 if (const auto *VecTy = To->getAs<ExtVectorType>()) 9253 To = VecTy->getElementType(); 9254 // It's a floating promotion if the source type is a lower rank. 9255 return ICE->getCastKind() == CK_FloatingCast && 9256 S.Context.getFloatingTypeOrder(From, To) < 0; 9257 } 9258 9259 bool 9260 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 9261 const char *StartSpecifier, 9262 unsigned SpecifierLen, 9263 const Expr *E) { 9264 using namespace analyze_format_string; 9265 using namespace analyze_printf; 9266 9267 // Now type check the data expression that matches the 9268 // format specifier. 9269 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 9270 if (!AT.isValid()) 9271 return true; 9272 9273 QualType ExprTy = E->getType(); 9274 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 9275 ExprTy = TET->getUnderlyingExpr()->getType(); 9276 } 9277 9278 // Diagnose attempts to print a boolean value as a character. Unlike other 9279 // -Wformat diagnostics, this is fine from a type perspective, but it still 9280 // doesn't make sense. 9281 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 9282 E->isKnownToHaveBooleanValue()) { 9283 const CharSourceRange &CSR = 9284 getSpecifierRange(StartSpecifier, SpecifierLen); 9285 SmallString<4> FSString; 9286 llvm::raw_svector_ostream os(FSString); 9287 FS.toString(os); 9288 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 9289 << FSString, 9290 E->getExprLoc(), false, CSR); 9291 return true; 9292 } 9293 9294 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 9295 if (Match == analyze_printf::ArgType::Match) 9296 return true; 9297 9298 // Look through argument promotions for our error message's reported type. 9299 // This includes the integral and floating promotions, but excludes array 9300 // and function pointer decay (seeing that an argument intended to be a 9301 // string has type 'char [6]' is probably more confusing than 'char *') and 9302 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 9303 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 9304 if (isArithmeticArgumentPromotion(S, ICE)) { 9305 E = ICE->getSubExpr(); 9306 ExprTy = E->getType(); 9307 9308 // Check if we didn't match because of an implicit cast from a 'char' 9309 // or 'short' to an 'int'. This is done because printf is a varargs 9310 // function. 9311 if (ICE->getType() == S.Context.IntTy || 9312 ICE->getType() == S.Context.UnsignedIntTy) { 9313 // All further checking is done on the subexpression 9314 const analyze_printf::ArgType::MatchKind ImplicitMatch = 9315 AT.matchesType(S.Context, ExprTy); 9316 if (ImplicitMatch == analyze_printf::ArgType::Match) 9317 return true; 9318 if (ImplicitMatch == ArgType::NoMatchPedantic || 9319 ImplicitMatch == ArgType::NoMatchTypeConfusion) 9320 Match = ImplicitMatch; 9321 } 9322 } 9323 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 9324 // Special case for 'a', which has type 'int' in C. 9325 // Note, however, that we do /not/ want to treat multibyte constants like 9326 // 'MooV' as characters! This form is deprecated but still exists. In 9327 // addition, don't treat expressions as of type 'char' if one byte length 9328 // modifier is provided. 9329 if (ExprTy == S.Context.IntTy && 9330 FS.getLengthModifier().getKind() != LengthModifier::AsChar) 9331 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 9332 ExprTy = S.Context.CharTy; 9333 } 9334 9335 // Look through enums to their underlying type. 9336 bool IsEnum = false; 9337 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 9338 ExprTy = EnumTy->getDecl()->getIntegerType(); 9339 IsEnum = true; 9340 } 9341 9342 // %C in an Objective-C context prints a unichar, not a wchar_t. 9343 // If the argument is an integer of some kind, believe the %C and suggest 9344 // a cast instead of changing the conversion specifier. 9345 QualType IntendedTy = ExprTy; 9346 if (isObjCContext() && 9347 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 9348 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 9349 !ExprTy->isCharType()) { 9350 // 'unichar' is defined as a typedef of unsigned short, but we should 9351 // prefer using the typedef if it is visible. 9352 IntendedTy = S.Context.UnsignedShortTy; 9353 9354 // While we are here, check if the value is an IntegerLiteral that happens 9355 // to be within the valid range. 9356 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 9357 const llvm::APInt &V = IL->getValue(); 9358 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 9359 return true; 9360 } 9361 9362 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 9363 Sema::LookupOrdinaryName); 9364 if (S.LookupName(Result, S.getCurScope())) { 9365 NamedDecl *ND = Result.getFoundDecl(); 9366 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 9367 if (TD->getUnderlyingType() == IntendedTy) 9368 IntendedTy = S.Context.getTypedefType(TD); 9369 } 9370 } 9371 } 9372 9373 // Special-case some of Darwin's platform-independence types by suggesting 9374 // casts to primitive types that are known to be large enough. 9375 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 9376 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 9377 QualType CastTy; 9378 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 9379 if (!CastTy.isNull()) { 9380 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 9381 // (long in ASTContext). Only complain to pedants. 9382 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 9383 (AT.isSizeT() || AT.isPtrdiffT()) && 9384 AT.matchesType(S.Context, CastTy)) 9385 Match = ArgType::NoMatchPedantic; 9386 IntendedTy = CastTy; 9387 ShouldNotPrintDirectly = true; 9388 } 9389 } 9390 9391 // We may be able to offer a FixItHint if it is a supported type. 9392 PrintfSpecifier fixedFS = FS; 9393 bool Success = 9394 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 9395 9396 if (Success) { 9397 // Get the fix string from the fixed format specifier 9398 SmallString<16> buf; 9399 llvm::raw_svector_ostream os(buf); 9400 fixedFS.toString(os); 9401 9402 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 9403 9404 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 9405 unsigned Diag; 9406 switch (Match) { 9407 case ArgType::Match: llvm_unreachable("expected non-matching"); 9408 case ArgType::NoMatchPedantic: 9409 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9410 break; 9411 case ArgType::NoMatchTypeConfusion: 9412 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9413 break; 9414 case ArgType::NoMatch: 9415 Diag = diag::warn_format_conversion_argument_type_mismatch; 9416 break; 9417 } 9418 9419 // In this case, the specifier is wrong and should be changed to match 9420 // the argument. 9421 EmitFormatDiagnostic(S.PDiag(Diag) 9422 << AT.getRepresentativeTypeName(S.Context) 9423 << IntendedTy << IsEnum << E->getSourceRange(), 9424 E->getBeginLoc(), 9425 /*IsStringLocation*/ false, SpecRange, 9426 FixItHint::CreateReplacement(SpecRange, os.str())); 9427 } else { 9428 // The canonical type for formatting this value is different from the 9429 // actual type of the expression. (This occurs, for example, with Darwin's 9430 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 9431 // should be printed as 'long' for 64-bit compatibility.) 9432 // Rather than emitting a normal format/argument mismatch, we want to 9433 // add a cast to the recommended type (and correct the format string 9434 // if necessary). 9435 SmallString<16> CastBuf; 9436 llvm::raw_svector_ostream CastFix(CastBuf); 9437 CastFix << "("; 9438 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 9439 CastFix << ")"; 9440 9441 SmallVector<FixItHint,4> Hints; 9442 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 9443 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 9444 9445 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 9446 // If there's already a cast present, just replace it. 9447 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 9448 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 9449 9450 } else if (!requiresParensToAddCast(E)) { 9451 // If the expression has high enough precedence, 9452 // just write the C-style cast. 9453 Hints.push_back( 9454 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9455 } else { 9456 // Otherwise, add parens around the expression as well as the cast. 9457 CastFix << "("; 9458 Hints.push_back( 9459 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 9460 9461 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 9462 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 9463 } 9464 9465 if (ShouldNotPrintDirectly) { 9466 // The expression has a type that should not be printed directly. 9467 // We extract the name from the typedef because we don't want to show 9468 // the underlying type in the diagnostic. 9469 StringRef Name; 9470 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 9471 Name = TypedefTy->getDecl()->getName(); 9472 else 9473 Name = CastTyName; 9474 unsigned Diag = Match == ArgType::NoMatchPedantic 9475 ? diag::warn_format_argument_needs_cast_pedantic 9476 : diag::warn_format_argument_needs_cast; 9477 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 9478 << E->getSourceRange(), 9479 E->getBeginLoc(), /*IsStringLocation=*/false, 9480 SpecRange, Hints); 9481 } else { 9482 // In this case, the expression could be printed using a different 9483 // specifier, but we've decided that the specifier is probably correct 9484 // and we should cast instead. Just use the normal warning message. 9485 EmitFormatDiagnostic( 9486 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 9487 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 9488 << E->getSourceRange(), 9489 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 9490 } 9491 } 9492 } else { 9493 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 9494 SpecifierLen); 9495 // Since the warning for passing non-POD types to variadic functions 9496 // was deferred until now, we emit a warning for non-POD 9497 // arguments here. 9498 switch (S.isValidVarArgType(ExprTy)) { 9499 case Sema::VAK_Valid: 9500 case Sema::VAK_ValidInCXX11: { 9501 unsigned Diag; 9502 switch (Match) { 9503 case ArgType::Match: llvm_unreachable("expected non-matching"); 9504 case ArgType::NoMatchPedantic: 9505 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 9506 break; 9507 case ArgType::NoMatchTypeConfusion: 9508 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 9509 break; 9510 case ArgType::NoMatch: 9511 Diag = diag::warn_format_conversion_argument_type_mismatch; 9512 break; 9513 } 9514 9515 EmitFormatDiagnostic( 9516 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 9517 << IsEnum << CSR << E->getSourceRange(), 9518 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9519 break; 9520 } 9521 case Sema::VAK_Undefined: 9522 case Sema::VAK_MSVCUndefined: 9523 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 9524 << S.getLangOpts().CPlusPlus11 << ExprTy 9525 << CallType 9526 << AT.getRepresentativeTypeName(S.Context) << CSR 9527 << E->getSourceRange(), 9528 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9529 checkForCStrMembers(AT, E); 9530 break; 9531 9532 case Sema::VAK_Invalid: 9533 if (ExprTy->isObjCObjectType()) 9534 EmitFormatDiagnostic( 9535 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 9536 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 9537 << AT.getRepresentativeTypeName(S.Context) << CSR 9538 << E->getSourceRange(), 9539 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 9540 else 9541 // FIXME: If this is an initializer list, suggest removing the braces 9542 // or inserting a cast to the target type. 9543 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 9544 << isa<InitListExpr>(E) << ExprTy << CallType 9545 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 9546 break; 9547 } 9548 9549 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 9550 "format string specifier index out of range"); 9551 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 9552 } 9553 9554 return true; 9555 } 9556 9557 //===--- CHECK: Scanf format string checking ------------------------------===// 9558 9559 namespace { 9560 9561 class CheckScanfHandler : public CheckFormatHandler { 9562 public: 9563 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 9564 const Expr *origFormatExpr, Sema::FormatStringType type, 9565 unsigned firstDataArg, unsigned numDataArgs, 9566 const char *beg, bool hasVAListArg, 9567 ArrayRef<const Expr *> Args, unsigned formatIdx, 9568 bool inFunctionCall, Sema::VariadicCallType CallType, 9569 llvm::SmallBitVector &CheckedVarArgs, 9570 UncoveredArgHandler &UncoveredArg) 9571 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 9572 numDataArgs, beg, hasVAListArg, Args, formatIdx, 9573 inFunctionCall, CallType, CheckedVarArgs, 9574 UncoveredArg) {} 9575 9576 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 9577 const char *startSpecifier, 9578 unsigned specifierLen) override; 9579 9580 bool HandleInvalidScanfConversionSpecifier( 9581 const analyze_scanf::ScanfSpecifier &FS, 9582 const char *startSpecifier, 9583 unsigned specifierLen) override; 9584 9585 void HandleIncompleteScanList(const char *start, const char *end) override; 9586 }; 9587 9588 } // namespace 9589 9590 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 9591 const char *end) { 9592 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 9593 getLocationOfByte(end), /*IsStringLocation*/true, 9594 getSpecifierRange(start, end - start)); 9595 } 9596 9597 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 9598 const analyze_scanf::ScanfSpecifier &FS, 9599 const char *startSpecifier, 9600 unsigned specifierLen) { 9601 const analyze_scanf::ScanfConversionSpecifier &CS = 9602 FS.getConversionSpecifier(); 9603 9604 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 9605 getLocationOfByte(CS.getStart()), 9606 startSpecifier, specifierLen, 9607 CS.getStart(), CS.getLength()); 9608 } 9609 9610 bool CheckScanfHandler::HandleScanfSpecifier( 9611 const analyze_scanf::ScanfSpecifier &FS, 9612 const char *startSpecifier, 9613 unsigned specifierLen) { 9614 using namespace analyze_scanf; 9615 using namespace analyze_format_string; 9616 9617 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 9618 9619 // Handle case where '%' and '*' don't consume an argument. These shouldn't 9620 // be used to decide if we are using positional arguments consistently. 9621 if (FS.consumesDataArgument()) { 9622 if (atFirstArg) { 9623 atFirstArg = false; 9624 usesPositionalArgs = FS.usesPositionalArg(); 9625 } 9626 else if (usesPositionalArgs != FS.usesPositionalArg()) { 9627 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 9628 startSpecifier, specifierLen); 9629 return false; 9630 } 9631 } 9632 9633 // Check if the field with is non-zero. 9634 const OptionalAmount &Amt = FS.getFieldWidth(); 9635 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 9636 if (Amt.getConstantAmount() == 0) { 9637 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 9638 Amt.getConstantLength()); 9639 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 9640 getLocationOfByte(Amt.getStart()), 9641 /*IsStringLocation*/true, R, 9642 FixItHint::CreateRemoval(R)); 9643 } 9644 } 9645 9646 if (!FS.consumesDataArgument()) { 9647 // FIXME: Technically specifying a precision or field width here 9648 // makes no sense. Worth issuing a warning at some point. 9649 return true; 9650 } 9651 9652 // Consume the argument. 9653 unsigned argIndex = FS.getArgIndex(); 9654 if (argIndex < NumDataArgs) { 9655 // The check to see if the argIndex is valid will come later. 9656 // We set the bit here because we may exit early from this 9657 // function if we encounter some other error. 9658 CoveredArgs.set(argIndex); 9659 } 9660 9661 // Check the length modifier is valid with the given conversion specifier. 9662 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 9663 S.getLangOpts())) 9664 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9665 diag::warn_format_nonsensical_length); 9666 else if (!FS.hasStandardLengthModifier()) 9667 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 9668 else if (!FS.hasStandardLengthConversionCombination()) 9669 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 9670 diag::warn_format_non_standard_conversion_spec); 9671 9672 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 9673 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 9674 9675 // The remaining checks depend on the data arguments. 9676 if (HasVAListArg) 9677 return true; 9678 9679 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 9680 return false; 9681 9682 // Check that the argument type matches the format specifier. 9683 const Expr *Ex = getDataArg(argIndex); 9684 if (!Ex) 9685 return true; 9686 9687 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 9688 9689 if (!AT.isValid()) { 9690 return true; 9691 } 9692 9693 analyze_format_string::ArgType::MatchKind Match = 9694 AT.matchesType(S.Context, Ex->getType()); 9695 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 9696 if (Match == analyze_format_string::ArgType::Match) 9697 return true; 9698 9699 ScanfSpecifier fixedFS = FS; 9700 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 9701 S.getLangOpts(), S.Context); 9702 9703 unsigned Diag = 9704 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 9705 : diag::warn_format_conversion_argument_type_mismatch; 9706 9707 if (Success) { 9708 // Get the fix string from the fixed format specifier. 9709 SmallString<128> buf; 9710 llvm::raw_svector_ostream os(buf); 9711 fixedFS.toString(os); 9712 9713 EmitFormatDiagnostic( 9714 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 9715 << Ex->getType() << false << Ex->getSourceRange(), 9716 Ex->getBeginLoc(), 9717 /*IsStringLocation*/ false, 9718 getSpecifierRange(startSpecifier, specifierLen), 9719 FixItHint::CreateReplacement( 9720 getSpecifierRange(startSpecifier, specifierLen), os.str())); 9721 } else { 9722 EmitFormatDiagnostic(S.PDiag(Diag) 9723 << AT.getRepresentativeTypeName(S.Context) 9724 << Ex->getType() << false << Ex->getSourceRange(), 9725 Ex->getBeginLoc(), 9726 /*IsStringLocation*/ false, 9727 getSpecifierRange(startSpecifier, specifierLen)); 9728 } 9729 9730 return true; 9731 } 9732 9733 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 9734 const Expr *OrigFormatExpr, 9735 ArrayRef<const Expr *> Args, 9736 bool HasVAListArg, unsigned format_idx, 9737 unsigned firstDataArg, 9738 Sema::FormatStringType Type, 9739 bool inFunctionCall, 9740 Sema::VariadicCallType CallType, 9741 llvm::SmallBitVector &CheckedVarArgs, 9742 UncoveredArgHandler &UncoveredArg, 9743 bool IgnoreStringsWithoutSpecifiers) { 9744 // CHECK: is the format string a wide literal? 9745 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 9746 CheckFormatHandler::EmitFormatDiagnostic( 9747 S, inFunctionCall, Args[format_idx], 9748 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 9749 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9750 return; 9751 } 9752 9753 // Str - The format string. NOTE: this is NOT null-terminated! 9754 StringRef StrRef = FExpr->getString(); 9755 const char *Str = StrRef.data(); 9756 // Account for cases where the string literal is truncated in a declaration. 9757 const ConstantArrayType *T = 9758 S.Context.getAsConstantArrayType(FExpr->getType()); 9759 assert(T && "String literal not of constant array type!"); 9760 size_t TypeSize = T->getSize().getZExtValue(); 9761 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9762 const unsigned numDataArgs = Args.size() - firstDataArg; 9763 9764 if (IgnoreStringsWithoutSpecifiers && 9765 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 9766 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 9767 return; 9768 9769 // Emit a warning if the string literal is truncated and does not contain an 9770 // embedded null character. 9771 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) { 9772 CheckFormatHandler::EmitFormatDiagnostic( 9773 S, inFunctionCall, Args[format_idx], 9774 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 9775 FExpr->getBeginLoc(), 9776 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 9777 return; 9778 } 9779 9780 // CHECK: empty format string? 9781 if (StrLen == 0 && numDataArgs > 0) { 9782 CheckFormatHandler::EmitFormatDiagnostic( 9783 S, inFunctionCall, Args[format_idx], 9784 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 9785 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 9786 return; 9787 } 9788 9789 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 9790 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 9791 Type == Sema::FST_OSTrace) { 9792 CheckPrintfHandler H( 9793 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 9794 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 9795 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 9796 CheckedVarArgs, UncoveredArg); 9797 9798 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 9799 S.getLangOpts(), 9800 S.Context.getTargetInfo(), 9801 Type == Sema::FST_FreeBSDKPrintf)) 9802 H.DoneProcessing(); 9803 } else if (Type == Sema::FST_Scanf) { 9804 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 9805 numDataArgs, Str, HasVAListArg, Args, format_idx, 9806 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 9807 9808 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 9809 S.getLangOpts(), 9810 S.Context.getTargetInfo())) 9811 H.DoneProcessing(); 9812 } // TODO: handle other formats 9813 } 9814 9815 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 9816 // Str - The format string. NOTE: this is NOT null-terminated! 9817 StringRef StrRef = FExpr->getString(); 9818 const char *Str = StrRef.data(); 9819 // Account for cases where the string literal is truncated in a declaration. 9820 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 9821 assert(T && "String literal not of constant array type!"); 9822 size_t TypeSize = T->getSize().getZExtValue(); 9823 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 9824 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 9825 getLangOpts(), 9826 Context.getTargetInfo()); 9827 } 9828 9829 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 9830 9831 // Returns the related absolute value function that is larger, of 0 if one 9832 // does not exist. 9833 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 9834 switch (AbsFunction) { 9835 default: 9836 return 0; 9837 9838 case Builtin::BI__builtin_abs: 9839 return Builtin::BI__builtin_labs; 9840 case Builtin::BI__builtin_labs: 9841 return Builtin::BI__builtin_llabs; 9842 case Builtin::BI__builtin_llabs: 9843 return 0; 9844 9845 case Builtin::BI__builtin_fabsf: 9846 return Builtin::BI__builtin_fabs; 9847 case Builtin::BI__builtin_fabs: 9848 return Builtin::BI__builtin_fabsl; 9849 case Builtin::BI__builtin_fabsl: 9850 return 0; 9851 9852 case Builtin::BI__builtin_cabsf: 9853 return Builtin::BI__builtin_cabs; 9854 case Builtin::BI__builtin_cabs: 9855 return Builtin::BI__builtin_cabsl; 9856 case Builtin::BI__builtin_cabsl: 9857 return 0; 9858 9859 case Builtin::BIabs: 9860 return Builtin::BIlabs; 9861 case Builtin::BIlabs: 9862 return Builtin::BIllabs; 9863 case Builtin::BIllabs: 9864 return 0; 9865 9866 case Builtin::BIfabsf: 9867 return Builtin::BIfabs; 9868 case Builtin::BIfabs: 9869 return Builtin::BIfabsl; 9870 case Builtin::BIfabsl: 9871 return 0; 9872 9873 case Builtin::BIcabsf: 9874 return Builtin::BIcabs; 9875 case Builtin::BIcabs: 9876 return Builtin::BIcabsl; 9877 case Builtin::BIcabsl: 9878 return 0; 9879 } 9880 } 9881 9882 // Returns the argument type of the absolute value function. 9883 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 9884 unsigned AbsType) { 9885 if (AbsType == 0) 9886 return QualType(); 9887 9888 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 9889 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 9890 if (Error != ASTContext::GE_None) 9891 return QualType(); 9892 9893 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 9894 if (!FT) 9895 return QualType(); 9896 9897 if (FT->getNumParams() != 1) 9898 return QualType(); 9899 9900 return FT->getParamType(0); 9901 } 9902 9903 // Returns the best absolute value function, or zero, based on type and 9904 // current absolute value function. 9905 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 9906 unsigned AbsFunctionKind) { 9907 unsigned BestKind = 0; 9908 uint64_t ArgSize = Context.getTypeSize(ArgType); 9909 for (unsigned Kind = AbsFunctionKind; Kind != 0; 9910 Kind = getLargerAbsoluteValueFunction(Kind)) { 9911 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 9912 if (Context.getTypeSize(ParamType) >= ArgSize) { 9913 if (BestKind == 0) 9914 BestKind = Kind; 9915 else if (Context.hasSameType(ParamType, ArgType)) { 9916 BestKind = Kind; 9917 break; 9918 } 9919 } 9920 } 9921 return BestKind; 9922 } 9923 9924 enum AbsoluteValueKind { 9925 AVK_Integer, 9926 AVK_Floating, 9927 AVK_Complex 9928 }; 9929 9930 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9931 if (T->isIntegralOrEnumerationType()) 9932 return AVK_Integer; 9933 if (T->isRealFloatingType()) 9934 return AVK_Floating; 9935 if (T->isAnyComplexType()) 9936 return AVK_Complex; 9937 9938 llvm_unreachable("Type not integer, floating, or complex"); 9939 } 9940 9941 // Changes the absolute value function to a different type. Preserves whether 9942 // the function is a builtin. 9943 static unsigned changeAbsFunction(unsigned AbsKind, 9944 AbsoluteValueKind ValueKind) { 9945 switch (ValueKind) { 9946 case AVK_Integer: 9947 switch (AbsKind) { 9948 default: 9949 return 0; 9950 case Builtin::BI__builtin_fabsf: 9951 case Builtin::BI__builtin_fabs: 9952 case Builtin::BI__builtin_fabsl: 9953 case Builtin::BI__builtin_cabsf: 9954 case Builtin::BI__builtin_cabs: 9955 case Builtin::BI__builtin_cabsl: 9956 return Builtin::BI__builtin_abs; 9957 case Builtin::BIfabsf: 9958 case Builtin::BIfabs: 9959 case Builtin::BIfabsl: 9960 case Builtin::BIcabsf: 9961 case Builtin::BIcabs: 9962 case Builtin::BIcabsl: 9963 return Builtin::BIabs; 9964 } 9965 case AVK_Floating: 9966 switch (AbsKind) { 9967 default: 9968 return 0; 9969 case Builtin::BI__builtin_abs: 9970 case Builtin::BI__builtin_labs: 9971 case Builtin::BI__builtin_llabs: 9972 case Builtin::BI__builtin_cabsf: 9973 case Builtin::BI__builtin_cabs: 9974 case Builtin::BI__builtin_cabsl: 9975 return Builtin::BI__builtin_fabsf; 9976 case Builtin::BIabs: 9977 case Builtin::BIlabs: 9978 case Builtin::BIllabs: 9979 case Builtin::BIcabsf: 9980 case Builtin::BIcabs: 9981 case Builtin::BIcabsl: 9982 return Builtin::BIfabsf; 9983 } 9984 case AVK_Complex: 9985 switch (AbsKind) { 9986 default: 9987 return 0; 9988 case Builtin::BI__builtin_abs: 9989 case Builtin::BI__builtin_labs: 9990 case Builtin::BI__builtin_llabs: 9991 case Builtin::BI__builtin_fabsf: 9992 case Builtin::BI__builtin_fabs: 9993 case Builtin::BI__builtin_fabsl: 9994 return Builtin::BI__builtin_cabsf; 9995 case Builtin::BIabs: 9996 case Builtin::BIlabs: 9997 case Builtin::BIllabs: 9998 case Builtin::BIfabsf: 9999 case Builtin::BIfabs: 10000 case Builtin::BIfabsl: 10001 return Builtin::BIcabsf; 10002 } 10003 } 10004 llvm_unreachable("Unable to convert function"); 10005 } 10006 10007 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 10008 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 10009 if (!FnInfo) 10010 return 0; 10011 10012 switch (FDecl->getBuiltinID()) { 10013 default: 10014 return 0; 10015 case Builtin::BI__builtin_abs: 10016 case Builtin::BI__builtin_fabs: 10017 case Builtin::BI__builtin_fabsf: 10018 case Builtin::BI__builtin_fabsl: 10019 case Builtin::BI__builtin_labs: 10020 case Builtin::BI__builtin_llabs: 10021 case Builtin::BI__builtin_cabs: 10022 case Builtin::BI__builtin_cabsf: 10023 case Builtin::BI__builtin_cabsl: 10024 case Builtin::BIabs: 10025 case Builtin::BIlabs: 10026 case Builtin::BIllabs: 10027 case Builtin::BIfabs: 10028 case Builtin::BIfabsf: 10029 case Builtin::BIfabsl: 10030 case Builtin::BIcabs: 10031 case Builtin::BIcabsf: 10032 case Builtin::BIcabsl: 10033 return FDecl->getBuiltinID(); 10034 } 10035 llvm_unreachable("Unknown Builtin type"); 10036 } 10037 10038 // If the replacement is valid, emit a note with replacement function. 10039 // Additionally, suggest including the proper header if not already included. 10040 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 10041 unsigned AbsKind, QualType ArgType) { 10042 bool EmitHeaderHint = true; 10043 const char *HeaderName = nullptr; 10044 const char *FunctionName = nullptr; 10045 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 10046 FunctionName = "std::abs"; 10047 if (ArgType->isIntegralOrEnumerationType()) { 10048 HeaderName = "cstdlib"; 10049 } else if (ArgType->isRealFloatingType()) { 10050 HeaderName = "cmath"; 10051 } else { 10052 llvm_unreachable("Invalid Type"); 10053 } 10054 10055 // Lookup all std::abs 10056 if (NamespaceDecl *Std = S.getStdNamespace()) { 10057 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 10058 R.suppressDiagnostics(); 10059 S.LookupQualifiedName(R, Std); 10060 10061 for (const auto *I : R) { 10062 const FunctionDecl *FDecl = nullptr; 10063 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 10064 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 10065 } else { 10066 FDecl = dyn_cast<FunctionDecl>(I); 10067 } 10068 if (!FDecl) 10069 continue; 10070 10071 // Found std::abs(), check that they are the right ones. 10072 if (FDecl->getNumParams() != 1) 10073 continue; 10074 10075 // Check that the parameter type can handle the argument. 10076 QualType ParamType = FDecl->getParamDecl(0)->getType(); 10077 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 10078 S.Context.getTypeSize(ArgType) <= 10079 S.Context.getTypeSize(ParamType)) { 10080 // Found a function, don't need the header hint. 10081 EmitHeaderHint = false; 10082 break; 10083 } 10084 } 10085 } 10086 } else { 10087 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 10088 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 10089 10090 if (HeaderName) { 10091 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 10092 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 10093 R.suppressDiagnostics(); 10094 S.LookupName(R, S.getCurScope()); 10095 10096 if (R.isSingleResult()) { 10097 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 10098 if (FD && FD->getBuiltinID() == AbsKind) { 10099 EmitHeaderHint = false; 10100 } else { 10101 return; 10102 } 10103 } else if (!R.empty()) { 10104 return; 10105 } 10106 } 10107 } 10108 10109 S.Diag(Loc, diag::note_replace_abs_function) 10110 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 10111 10112 if (!HeaderName) 10113 return; 10114 10115 if (!EmitHeaderHint) 10116 return; 10117 10118 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 10119 << FunctionName; 10120 } 10121 10122 template <std::size_t StrLen> 10123 static bool IsStdFunction(const FunctionDecl *FDecl, 10124 const char (&Str)[StrLen]) { 10125 if (!FDecl) 10126 return false; 10127 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 10128 return false; 10129 if (!FDecl->isInStdNamespace()) 10130 return false; 10131 10132 return true; 10133 } 10134 10135 // Warn when using the wrong abs() function. 10136 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 10137 const FunctionDecl *FDecl) { 10138 if (Call->getNumArgs() != 1) 10139 return; 10140 10141 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 10142 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 10143 if (AbsKind == 0 && !IsStdAbs) 10144 return; 10145 10146 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10147 QualType ParamType = Call->getArg(0)->getType(); 10148 10149 // Unsigned types cannot be negative. Suggest removing the absolute value 10150 // function call. 10151 if (ArgType->isUnsignedIntegerType()) { 10152 const char *FunctionName = 10153 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 10154 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 10155 Diag(Call->getExprLoc(), diag::note_remove_abs) 10156 << FunctionName 10157 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 10158 return; 10159 } 10160 10161 // Taking the absolute value of a pointer is very suspicious, they probably 10162 // wanted to index into an array, dereference a pointer, call a function, etc. 10163 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 10164 unsigned DiagType = 0; 10165 if (ArgType->isFunctionType()) 10166 DiagType = 1; 10167 else if (ArgType->isArrayType()) 10168 DiagType = 2; 10169 10170 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 10171 return; 10172 } 10173 10174 // std::abs has overloads which prevent most of the absolute value problems 10175 // from occurring. 10176 if (IsStdAbs) 10177 return; 10178 10179 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 10180 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 10181 10182 // The argument and parameter are the same kind. Check if they are the right 10183 // size. 10184 if (ArgValueKind == ParamValueKind) { 10185 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 10186 return; 10187 10188 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 10189 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 10190 << FDecl << ArgType << ParamType; 10191 10192 if (NewAbsKind == 0) 10193 return; 10194 10195 emitReplacement(*this, Call->getExprLoc(), 10196 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10197 return; 10198 } 10199 10200 // ArgValueKind != ParamValueKind 10201 // The wrong type of absolute value function was used. Attempt to find the 10202 // proper one. 10203 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 10204 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 10205 if (NewAbsKind == 0) 10206 return; 10207 10208 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 10209 << FDecl << ParamValueKind << ArgValueKind; 10210 10211 emitReplacement(*this, Call->getExprLoc(), 10212 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 10213 } 10214 10215 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 10216 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 10217 const FunctionDecl *FDecl) { 10218 if (!Call || !FDecl) return; 10219 10220 // Ignore template specializations and macros. 10221 if (inTemplateInstantiation()) return; 10222 if (Call->getExprLoc().isMacroID()) return; 10223 10224 // Only care about the one template argument, two function parameter std::max 10225 if (Call->getNumArgs() != 2) return; 10226 if (!IsStdFunction(FDecl, "max")) return; 10227 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 10228 if (!ArgList) return; 10229 if (ArgList->size() != 1) return; 10230 10231 // Check that template type argument is unsigned integer. 10232 const auto& TA = ArgList->get(0); 10233 if (TA.getKind() != TemplateArgument::Type) return; 10234 QualType ArgType = TA.getAsType(); 10235 if (!ArgType->isUnsignedIntegerType()) return; 10236 10237 // See if either argument is a literal zero. 10238 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 10239 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 10240 if (!MTE) return false; 10241 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 10242 if (!Num) return false; 10243 if (Num->getValue() != 0) return false; 10244 return true; 10245 }; 10246 10247 const Expr *FirstArg = Call->getArg(0); 10248 const Expr *SecondArg = Call->getArg(1); 10249 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 10250 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 10251 10252 // Only warn when exactly one argument is zero. 10253 if (IsFirstArgZero == IsSecondArgZero) return; 10254 10255 SourceRange FirstRange = FirstArg->getSourceRange(); 10256 SourceRange SecondRange = SecondArg->getSourceRange(); 10257 10258 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 10259 10260 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 10261 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 10262 10263 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 10264 SourceRange RemovalRange; 10265 if (IsFirstArgZero) { 10266 RemovalRange = SourceRange(FirstRange.getBegin(), 10267 SecondRange.getBegin().getLocWithOffset(-1)); 10268 } else { 10269 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 10270 SecondRange.getEnd()); 10271 } 10272 10273 Diag(Call->getExprLoc(), diag::note_remove_max_call) 10274 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 10275 << FixItHint::CreateRemoval(RemovalRange); 10276 } 10277 10278 //===--- CHECK: Standard memory functions ---------------------------------===// 10279 10280 /// Takes the expression passed to the size_t parameter of functions 10281 /// such as memcmp, strncat, etc and warns if it's a comparison. 10282 /// 10283 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 10284 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 10285 IdentifierInfo *FnName, 10286 SourceLocation FnLoc, 10287 SourceLocation RParenLoc) { 10288 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 10289 if (!Size) 10290 return false; 10291 10292 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 10293 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 10294 return false; 10295 10296 SourceRange SizeRange = Size->getSourceRange(); 10297 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 10298 << SizeRange << FnName; 10299 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 10300 << FnName 10301 << FixItHint::CreateInsertion( 10302 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 10303 << FixItHint::CreateRemoval(RParenLoc); 10304 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 10305 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 10306 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 10307 ")"); 10308 10309 return true; 10310 } 10311 10312 /// Determine whether the given type is or contains a dynamic class type 10313 /// (e.g., whether it has a vtable). 10314 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 10315 bool &IsContained) { 10316 // Look through array types while ignoring qualifiers. 10317 const Type *Ty = T->getBaseElementTypeUnsafe(); 10318 IsContained = false; 10319 10320 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 10321 RD = RD ? RD->getDefinition() : nullptr; 10322 if (!RD || RD->isInvalidDecl()) 10323 return nullptr; 10324 10325 if (RD->isDynamicClass()) 10326 return RD; 10327 10328 // Check all the fields. If any bases were dynamic, the class is dynamic. 10329 // It's impossible for a class to transitively contain itself by value, so 10330 // infinite recursion is impossible. 10331 for (auto *FD : RD->fields()) { 10332 bool SubContained; 10333 if (const CXXRecordDecl *ContainedRD = 10334 getContainedDynamicClass(FD->getType(), SubContained)) { 10335 IsContained = true; 10336 return ContainedRD; 10337 } 10338 } 10339 10340 return nullptr; 10341 } 10342 10343 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 10344 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 10345 if (Unary->getKind() == UETT_SizeOf) 10346 return Unary; 10347 return nullptr; 10348 } 10349 10350 /// If E is a sizeof expression, returns its argument expression, 10351 /// otherwise returns NULL. 10352 static const Expr *getSizeOfExprArg(const Expr *E) { 10353 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10354 if (!SizeOf->isArgumentType()) 10355 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 10356 return nullptr; 10357 } 10358 10359 /// If E is a sizeof expression, returns its argument type. 10360 static QualType getSizeOfArgType(const Expr *E) { 10361 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 10362 return SizeOf->getTypeOfArgument(); 10363 return QualType(); 10364 } 10365 10366 namespace { 10367 10368 struct SearchNonTrivialToInitializeField 10369 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 10370 using Super = 10371 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 10372 10373 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 10374 10375 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 10376 SourceLocation SL) { 10377 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10378 asDerived().visitArray(PDIK, AT, SL); 10379 return; 10380 } 10381 10382 Super::visitWithKind(PDIK, FT, SL); 10383 } 10384 10385 void visitARCStrong(QualType FT, SourceLocation SL) { 10386 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10387 } 10388 void visitARCWeak(QualType FT, SourceLocation SL) { 10389 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 10390 } 10391 void visitStruct(QualType FT, SourceLocation SL) { 10392 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10393 visit(FD->getType(), FD->getLocation()); 10394 } 10395 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 10396 const ArrayType *AT, SourceLocation SL) { 10397 visit(getContext().getBaseElementType(AT), SL); 10398 } 10399 void visitTrivial(QualType FT, SourceLocation SL) {} 10400 10401 static void diag(QualType RT, const Expr *E, Sema &S) { 10402 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 10403 } 10404 10405 ASTContext &getContext() { return S.getASTContext(); } 10406 10407 const Expr *E; 10408 Sema &S; 10409 }; 10410 10411 struct SearchNonTrivialToCopyField 10412 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 10413 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 10414 10415 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 10416 10417 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 10418 SourceLocation SL) { 10419 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 10420 asDerived().visitArray(PCK, AT, SL); 10421 return; 10422 } 10423 10424 Super::visitWithKind(PCK, FT, SL); 10425 } 10426 10427 void visitARCStrong(QualType FT, SourceLocation SL) { 10428 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10429 } 10430 void visitARCWeak(QualType FT, SourceLocation SL) { 10431 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 10432 } 10433 void visitStruct(QualType FT, SourceLocation SL) { 10434 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 10435 visit(FD->getType(), FD->getLocation()); 10436 } 10437 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 10438 SourceLocation SL) { 10439 visit(getContext().getBaseElementType(AT), SL); 10440 } 10441 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 10442 SourceLocation SL) {} 10443 void visitTrivial(QualType FT, SourceLocation SL) {} 10444 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 10445 10446 static void diag(QualType RT, const Expr *E, Sema &S) { 10447 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 10448 } 10449 10450 ASTContext &getContext() { return S.getASTContext(); } 10451 10452 const Expr *E; 10453 Sema &S; 10454 }; 10455 10456 } 10457 10458 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 10459 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 10460 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 10461 10462 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 10463 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 10464 return false; 10465 10466 return doesExprLikelyComputeSize(BO->getLHS()) || 10467 doesExprLikelyComputeSize(BO->getRHS()); 10468 } 10469 10470 return getAsSizeOfExpr(SizeofExpr) != nullptr; 10471 } 10472 10473 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 10474 /// 10475 /// \code 10476 /// #define MACRO 0 10477 /// foo(MACRO); 10478 /// foo(0); 10479 /// \endcode 10480 /// 10481 /// This should return true for the first call to foo, but not for the second 10482 /// (regardless of whether foo is a macro or function). 10483 static bool isArgumentExpandedFromMacro(SourceManager &SM, 10484 SourceLocation CallLoc, 10485 SourceLocation ArgLoc) { 10486 if (!CallLoc.isMacroID()) 10487 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 10488 10489 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 10490 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 10491 } 10492 10493 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 10494 /// last two arguments transposed. 10495 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 10496 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 10497 return; 10498 10499 const Expr *SizeArg = 10500 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 10501 10502 auto isLiteralZero = [](const Expr *E) { 10503 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 10504 }; 10505 10506 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 10507 SourceLocation CallLoc = Call->getRParenLoc(); 10508 SourceManager &SM = S.getSourceManager(); 10509 if (isLiteralZero(SizeArg) && 10510 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 10511 10512 SourceLocation DiagLoc = SizeArg->getExprLoc(); 10513 10514 // Some platforms #define bzero to __builtin_memset. See if this is the 10515 // case, and if so, emit a better diagnostic. 10516 if (BId == Builtin::BIbzero || 10517 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 10518 CallLoc, SM, S.getLangOpts()) == "bzero")) { 10519 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 10520 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 10521 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 10522 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 10523 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 10524 } 10525 return; 10526 } 10527 10528 // If the second argument to a memset is a sizeof expression and the third 10529 // isn't, this is also likely an error. This should catch 10530 // 'memset(buf, sizeof(buf), 0xff)'. 10531 if (BId == Builtin::BImemset && 10532 doesExprLikelyComputeSize(Call->getArg(1)) && 10533 !doesExprLikelyComputeSize(Call->getArg(2))) { 10534 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 10535 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 10536 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 10537 return; 10538 } 10539 } 10540 10541 /// Check for dangerous or invalid arguments to memset(). 10542 /// 10543 /// This issues warnings on known problematic, dangerous or unspecified 10544 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 10545 /// function calls. 10546 /// 10547 /// \param Call The call expression to diagnose. 10548 void Sema::CheckMemaccessArguments(const CallExpr *Call, 10549 unsigned BId, 10550 IdentifierInfo *FnName) { 10551 assert(BId != 0); 10552 10553 // It is possible to have a non-standard definition of memset. Validate 10554 // we have enough arguments, and if not, abort further checking. 10555 unsigned ExpectedNumArgs = 10556 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 10557 if (Call->getNumArgs() < ExpectedNumArgs) 10558 return; 10559 10560 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 10561 BId == Builtin::BIstrndup ? 1 : 2); 10562 unsigned LenArg = 10563 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 10564 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 10565 10566 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 10567 Call->getBeginLoc(), Call->getRParenLoc())) 10568 return; 10569 10570 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 10571 CheckMemaccessSize(*this, BId, Call); 10572 10573 // We have special checking when the length is a sizeof expression. 10574 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 10575 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 10576 llvm::FoldingSetNodeID SizeOfArgID; 10577 10578 // Although widely used, 'bzero' is not a standard function. Be more strict 10579 // with the argument types before allowing diagnostics and only allow the 10580 // form bzero(ptr, sizeof(...)). 10581 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 10582 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 10583 return; 10584 10585 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 10586 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 10587 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 10588 10589 QualType DestTy = Dest->getType(); 10590 QualType PointeeTy; 10591 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 10592 PointeeTy = DestPtrTy->getPointeeType(); 10593 10594 // Never warn about void type pointers. This can be used to suppress 10595 // false positives. 10596 if (PointeeTy->isVoidType()) 10597 continue; 10598 10599 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 10600 // actually comparing the expressions for equality. Because computing the 10601 // expression IDs can be expensive, we only do this if the diagnostic is 10602 // enabled. 10603 if (SizeOfArg && 10604 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 10605 SizeOfArg->getExprLoc())) { 10606 // We only compute IDs for expressions if the warning is enabled, and 10607 // cache the sizeof arg's ID. 10608 if (SizeOfArgID == llvm::FoldingSetNodeID()) 10609 SizeOfArg->Profile(SizeOfArgID, Context, true); 10610 llvm::FoldingSetNodeID DestID; 10611 Dest->Profile(DestID, Context, true); 10612 if (DestID == SizeOfArgID) { 10613 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 10614 // over sizeof(src) as well. 10615 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 10616 StringRef ReadableName = FnName->getName(); 10617 10618 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 10619 if (UnaryOp->getOpcode() == UO_AddrOf) 10620 ActionIdx = 1; // If its an address-of operator, just remove it. 10621 if (!PointeeTy->isIncompleteType() && 10622 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 10623 ActionIdx = 2; // If the pointee's size is sizeof(char), 10624 // suggest an explicit length. 10625 10626 // If the function is defined as a builtin macro, do not show macro 10627 // expansion. 10628 SourceLocation SL = SizeOfArg->getExprLoc(); 10629 SourceRange DSR = Dest->getSourceRange(); 10630 SourceRange SSR = SizeOfArg->getSourceRange(); 10631 SourceManager &SM = getSourceManager(); 10632 10633 if (SM.isMacroArgExpansion(SL)) { 10634 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 10635 SL = SM.getSpellingLoc(SL); 10636 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 10637 SM.getSpellingLoc(DSR.getEnd())); 10638 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 10639 SM.getSpellingLoc(SSR.getEnd())); 10640 } 10641 10642 DiagRuntimeBehavior(SL, SizeOfArg, 10643 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 10644 << ReadableName 10645 << PointeeTy 10646 << DestTy 10647 << DSR 10648 << SSR); 10649 DiagRuntimeBehavior(SL, SizeOfArg, 10650 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 10651 << ActionIdx 10652 << SSR); 10653 10654 break; 10655 } 10656 } 10657 10658 // Also check for cases where the sizeof argument is the exact same 10659 // type as the memory argument, and where it points to a user-defined 10660 // record type. 10661 if (SizeOfArgTy != QualType()) { 10662 if (PointeeTy->isRecordType() && 10663 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 10664 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 10665 PDiag(diag::warn_sizeof_pointer_type_memaccess) 10666 << FnName << SizeOfArgTy << ArgIdx 10667 << PointeeTy << Dest->getSourceRange() 10668 << LenExpr->getSourceRange()); 10669 break; 10670 } 10671 } 10672 } else if (DestTy->isArrayType()) { 10673 PointeeTy = DestTy; 10674 } 10675 10676 if (PointeeTy == QualType()) 10677 continue; 10678 10679 // Always complain about dynamic classes. 10680 bool IsContained; 10681 if (const CXXRecordDecl *ContainedRD = 10682 getContainedDynamicClass(PointeeTy, IsContained)) { 10683 10684 unsigned OperationType = 0; 10685 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 10686 // "overwritten" if we're warning about the destination for any call 10687 // but memcmp; otherwise a verb appropriate to the call. 10688 if (ArgIdx != 0 || IsCmp) { 10689 if (BId == Builtin::BImemcpy) 10690 OperationType = 1; 10691 else if(BId == Builtin::BImemmove) 10692 OperationType = 2; 10693 else if (IsCmp) 10694 OperationType = 3; 10695 } 10696 10697 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10698 PDiag(diag::warn_dyn_class_memaccess) 10699 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 10700 << IsContained << ContainedRD << OperationType 10701 << Call->getCallee()->getSourceRange()); 10702 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 10703 BId != Builtin::BImemset) 10704 DiagRuntimeBehavior( 10705 Dest->getExprLoc(), Dest, 10706 PDiag(diag::warn_arc_object_memaccess) 10707 << ArgIdx << FnName << PointeeTy 10708 << Call->getCallee()->getSourceRange()); 10709 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 10710 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 10711 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 10712 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10713 PDiag(diag::warn_cstruct_memaccess) 10714 << ArgIdx << FnName << PointeeTy << 0); 10715 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 10716 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 10717 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 10718 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 10719 PDiag(diag::warn_cstruct_memaccess) 10720 << ArgIdx << FnName << PointeeTy << 1); 10721 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 10722 } else { 10723 continue; 10724 } 10725 } else 10726 continue; 10727 10728 DiagRuntimeBehavior( 10729 Dest->getExprLoc(), Dest, 10730 PDiag(diag::note_bad_memaccess_silence) 10731 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 10732 break; 10733 } 10734 } 10735 10736 // A little helper routine: ignore addition and subtraction of integer literals. 10737 // This intentionally does not ignore all integer constant expressions because 10738 // we don't want to remove sizeof(). 10739 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 10740 Ex = Ex->IgnoreParenCasts(); 10741 10742 while (true) { 10743 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 10744 if (!BO || !BO->isAdditiveOp()) 10745 break; 10746 10747 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 10748 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 10749 10750 if (isa<IntegerLiteral>(RHS)) 10751 Ex = LHS; 10752 else if (isa<IntegerLiteral>(LHS)) 10753 Ex = RHS; 10754 else 10755 break; 10756 } 10757 10758 return Ex; 10759 } 10760 10761 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 10762 ASTContext &Context) { 10763 // Only handle constant-sized or VLAs, but not flexible members. 10764 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 10765 // Only issue the FIXIT for arrays of size > 1. 10766 if (CAT->getSize().getSExtValue() <= 1) 10767 return false; 10768 } else if (!Ty->isVariableArrayType()) { 10769 return false; 10770 } 10771 return true; 10772 } 10773 10774 // Warn if the user has made the 'size' argument to strlcpy or strlcat 10775 // be the size of the source, instead of the destination. 10776 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 10777 IdentifierInfo *FnName) { 10778 10779 // Don't crash if the user has the wrong number of arguments 10780 unsigned NumArgs = Call->getNumArgs(); 10781 if ((NumArgs != 3) && (NumArgs != 4)) 10782 return; 10783 10784 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 10785 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 10786 const Expr *CompareWithSrc = nullptr; 10787 10788 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 10789 Call->getBeginLoc(), Call->getRParenLoc())) 10790 return; 10791 10792 // Look for 'strlcpy(dst, x, sizeof(x))' 10793 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 10794 CompareWithSrc = Ex; 10795 else { 10796 // Look for 'strlcpy(dst, x, strlen(x))' 10797 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 10798 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 10799 SizeCall->getNumArgs() == 1) 10800 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 10801 } 10802 } 10803 10804 if (!CompareWithSrc) 10805 return; 10806 10807 // Determine if the argument to sizeof/strlen is equal to the source 10808 // argument. In principle there's all kinds of things you could do 10809 // here, for instance creating an == expression and evaluating it with 10810 // EvaluateAsBooleanCondition, but this uses a more direct technique: 10811 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 10812 if (!SrcArgDRE) 10813 return; 10814 10815 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 10816 if (!CompareWithSrcDRE || 10817 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 10818 return; 10819 10820 const Expr *OriginalSizeArg = Call->getArg(2); 10821 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 10822 << OriginalSizeArg->getSourceRange() << FnName; 10823 10824 // Output a FIXIT hint if the destination is an array (rather than a 10825 // pointer to an array). This could be enhanced to handle some 10826 // pointers if we know the actual size, like if DstArg is 'array+2' 10827 // we could say 'sizeof(array)-2'. 10828 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 10829 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 10830 return; 10831 10832 SmallString<128> sizeString; 10833 llvm::raw_svector_ostream OS(sizeString); 10834 OS << "sizeof("; 10835 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10836 OS << ")"; 10837 10838 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 10839 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 10840 OS.str()); 10841 } 10842 10843 /// Check if two expressions refer to the same declaration. 10844 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 10845 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 10846 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 10847 return D1->getDecl() == D2->getDecl(); 10848 return false; 10849 } 10850 10851 static const Expr *getStrlenExprArg(const Expr *E) { 10852 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 10853 const FunctionDecl *FD = CE->getDirectCallee(); 10854 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 10855 return nullptr; 10856 return CE->getArg(0)->IgnoreParenCasts(); 10857 } 10858 return nullptr; 10859 } 10860 10861 // Warn on anti-patterns as the 'size' argument to strncat. 10862 // The correct size argument should look like following: 10863 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 10864 void Sema::CheckStrncatArguments(const CallExpr *CE, 10865 IdentifierInfo *FnName) { 10866 // Don't crash if the user has the wrong number of arguments. 10867 if (CE->getNumArgs() < 3) 10868 return; 10869 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 10870 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 10871 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 10872 10873 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 10874 CE->getRParenLoc())) 10875 return; 10876 10877 // Identify common expressions, which are wrongly used as the size argument 10878 // to strncat and may lead to buffer overflows. 10879 unsigned PatternType = 0; 10880 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 10881 // - sizeof(dst) 10882 if (referToTheSameDecl(SizeOfArg, DstArg)) 10883 PatternType = 1; 10884 // - sizeof(src) 10885 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 10886 PatternType = 2; 10887 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 10888 if (BE->getOpcode() == BO_Sub) { 10889 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 10890 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 10891 // - sizeof(dst) - strlen(dst) 10892 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 10893 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 10894 PatternType = 1; 10895 // - sizeof(src) - (anything) 10896 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 10897 PatternType = 2; 10898 } 10899 } 10900 10901 if (PatternType == 0) 10902 return; 10903 10904 // Generate the diagnostic. 10905 SourceLocation SL = LenArg->getBeginLoc(); 10906 SourceRange SR = LenArg->getSourceRange(); 10907 SourceManager &SM = getSourceManager(); 10908 10909 // If the function is defined as a builtin macro, do not show macro expansion. 10910 if (SM.isMacroArgExpansion(SL)) { 10911 SL = SM.getSpellingLoc(SL); 10912 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 10913 SM.getSpellingLoc(SR.getEnd())); 10914 } 10915 10916 // Check if the destination is an array (rather than a pointer to an array). 10917 QualType DstTy = DstArg->getType(); 10918 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 10919 Context); 10920 if (!isKnownSizeArray) { 10921 if (PatternType == 1) 10922 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10923 else 10924 Diag(SL, diag::warn_strncat_src_size) << SR; 10925 return; 10926 } 10927 10928 if (PatternType == 1) 10929 Diag(SL, diag::warn_strncat_large_size) << SR; 10930 else 10931 Diag(SL, diag::warn_strncat_src_size) << SR; 10932 10933 SmallString<128> sizeString; 10934 llvm::raw_svector_ostream OS(sizeString); 10935 OS << "sizeof("; 10936 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10937 OS << ") - "; 10938 OS << "strlen("; 10939 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10940 OS << ") - 1"; 10941 10942 Diag(SL, diag::note_strncat_wrong_size) 10943 << FixItHint::CreateReplacement(SR, OS.str()); 10944 } 10945 10946 namespace { 10947 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName, 10948 const UnaryOperator *UnaryExpr, const Decl *D) { 10949 if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) { 10950 S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object) 10951 << CalleeName << 0 /*object: */ << cast<NamedDecl>(D); 10952 return; 10953 } 10954 } 10955 10956 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName, 10957 const UnaryOperator *UnaryExpr) { 10958 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) { 10959 const Decl *D = Lvalue->getDecl(); 10960 if (isa<DeclaratorDecl>(D)) 10961 if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType()) 10962 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D); 10963 } 10964 10965 if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr())) 10966 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, 10967 Lvalue->getMemberDecl()); 10968 } 10969 10970 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName, 10971 const UnaryOperator *UnaryExpr) { 10972 const auto *Lambda = dyn_cast<LambdaExpr>( 10973 UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens()); 10974 if (!Lambda) 10975 return; 10976 10977 S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object) 10978 << CalleeName << 2 /*object: lambda expression*/; 10979 } 10980 10981 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName, 10982 const DeclRefExpr *Lvalue) { 10983 const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()); 10984 if (Var == nullptr) 10985 return; 10986 10987 S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object) 10988 << CalleeName << 0 /*object: */ << Var; 10989 } 10990 10991 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName, 10992 const CastExpr *Cast) { 10993 SmallString<128> SizeString; 10994 llvm::raw_svector_ostream OS(SizeString); 10995 10996 clang::CastKind Kind = Cast->getCastKind(); 10997 if (Kind == clang::CK_BitCast && 10998 !Cast->getSubExpr()->getType()->isFunctionPointerType()) 10999 return; 11000 if (Kind == clang::CK_IntegralToPointer && 11001 !isa<IntegerLiteral>( 11002 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens())) 11003 return; 11004 11005 switch (Cast->getCastKind()) { 11006 case clang::CK_BitCast: 11007 case clang::CK_IntegralToPointer: 11008 case clang::CK_FunctionToPointerDecay: 11009 OS << '\''; 11010 Cast->printPretty(OS, nullptr, S.getPrintingPolicy()); 11011 OS << '\''; 11012 break; 11013 default: 11014 return; 11015 } 11016 11017 S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object) 11018 << CalleeName << 0 /*object: */ << OS.str(); 11019 } 11020 } // namespace 11021 11022 /// Alerts the user that they are attempting to free a non-malloc'd object. 11023 void Sema::CheckFreeArguments(const CallExpr *E) { 11024 const std::string CalleeName = 11025 dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString(); 11026 11027 { // Prefer something that doesn't involve a cast to make things simpler. 11028 const Expr *Arg = E->getArg(0)->IgnoreParenCasts(); 11029 if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg)) 11030 switch (UnaryExpr->getOpcode()) { 11031 case UnaryOperator::Opcode::UO_AddrOf: 11032 return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr); 11033 case UnaryOperator::Opcode::UO_Plus: 11034 return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr); 11035 default: 11036 break; 11037 } 11038 11039 if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg)) 11040 if (Lvalue->getType()->isArrayType()) 11041 return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue); 11042 11043 if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) { 11044 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object) 11045 << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier(); 11046 return; 11047 } 11048 11049 if (isa<BlockExpr>(Arg)) { 11050 Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object) 11051 << CalleeName << 1 /*object: block*/; 11052 return; 11053 } 11054 } 11055 // Maybe the cast was important, check after the other cases. 11056 if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0))) 11057 return CheckFreeArgumentsCast(*this, CalleeName, Cast); 11058 } 11059 11060 void 11061 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 11062 SourceLocation ReturnLoc, 11063 bool isObjCMethod, 11064 const AttrVec *Attrs, 11065 const FunctionDecl *FD) { 11066 // Check if the return value is null but should not be. 11067 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 11068 (!isObjCMethod && isNonNullType(Context, lhsType))) && 11069 CheckNonNullExpr(*this, RetValExp)) 11070 Diag(ReturnLoc, diag::warn_null_ret) 11071 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 11072 11073 // C++11 [basic.stc.dynamic.allocation]p4: 11074 // If an allocation function declared with a non-throwing 11075 // exception-specification fails to allocate storage, it shall return 11076 // a null pointer. Any other allocation function that fails to allocate 11077 // storage shall indicate failure only by throwing an exception [...] 11078 if (FD) { 11079 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 11080 if (Op == OO_New || Op == OO_Array_New) { 11081 const FunctionProtoType *Proto 11082 = FD->getType()->castAs<FunctionProtoType>(); 11083 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 11084 CheckNonNullExpr(*this, RetValExp)) 11085 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 11086 << FD << getLangOpts().CPlusPlus11; 11087 } 11088 } 11089 11090 // PPC MMA non-pointer types are not allowed as return type. Checking the type 11091 // here prevent the user from using a PPC MMA type as trailing return type. 11092 if (Context.getTargetInfo().getTriple().isPPC64()) 11093 CheckPPCMMAType(RetValExp->getType(), ReturnLoc); 11094 } 11095 11096 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 11097 11098 /// Check for comparisons of floating point operands using != and ==. 11099 /// Issue a warning if these are no self-comparisons, as they are not likely 11100 /// to do what the programmer intended. 11101 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 11102 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 11103 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 11104 11105 // Special case: check for x == x (which is OK). 11106 // Do not emit warnings for such cases. 11107 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 11108 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 11109 if (DRL->getDecl() == DRR->getDecl()) 11110 return; 11111 11112 // Special case: check for comparisons against literals that can be exactly 11113 // represented by APFloat. In such cases, do not emit a warning. This 11114 // is a heuristic: often comparison against such literals are used to 11115 // detect if a value in a variable has not changed. This clearly can 11116 // lead to false negatives. 11117 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 11118 if (FLL->isExact()) 11119 return; 11120 } else 11121 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 11122 if (FLR->isExact()) 11123 return; 11124 11125 // Check for comparisons with builtin types. 11126 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 11127 if (CL->getBuiltinCallee()) 11128 return; 11129 11130 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 11131 if (CR->getBuiltinCallee()) 11132 return; 11133 11134 // Emit the diagnostic. 11135 Diag(Loc, diag::warn_floatingpoint_eq) 11136 << LHS->getSourceRange() << RHS->getSourceRange(); 11137 } 11138 11139 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 11140 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 11141 11142 namespace { 11143 11144 /// Structure recording the 'active' range of an integer-valued 11145 /// expression. 11146 struct IntRange { 11147 /// The number of bits active in the int. Note that this includes exactly one 11148 /// sign bit if !NonNegative. 11149 unsigned Width; 11150 11151 /// True if the int is known not to have negative values. If so, all leading 11152 /// bits before Width are known zero, otherwise they are known to be the 11153 /// same as the MSB within Width. 11154 bool NonNegative; 11155 11156 IntRange(unsigned Width, bool NonNegative) 11157 : Width(Width), NonNegative(NonNegative) {} 11158 11159 /// Number of bits excluding the sign bit. 11160 unsigned valueBits() const { 11161 return NonNegative ? Width : Width - 1; 11162 } 11163 11164 /// Returns the range of the bool type. 11165 static IntRange forBoolType() { 11166 return IntRange(1, true); 11167 } 11168 11169 /// Returns the range of an opaque value of the given integral type. 11170 static IntRange forValueOfType(ASTContext &C, QualType T) { 11171 return forValueOfCanonicalType(C, 11172 T->getCanonicalTypeInternal().getTypePtr()); 11173 } 11174 11175 /// Returns the range of an opaque value of a canonical integral type. 11176 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 11177 assert(T->isCanonicalUnqualified()); 11178 11179 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11180 T = VT->getElementType().getTypePtr(); 11181 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11182 T = CT->getElementType().getTypePtr(); 11183 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11184 T = AT->getValueType().getTypePtr(); 11185 11186 if (!C.getLangOpts().CPlusPlus) { 11187 // For enum types in C code, use the underlying datatype. 11188 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11189 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 11190 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 11191 // For enum types in C++, use the known bit width of the enumerators. 11192 EnumDecl *Enum = ET->getDecl(); 11193 // In C++11, enums can have a fixed underlying type. Use this type to 11194 // compute the range. 11195 if (Enum->isFixed()) { 11196 return IntRange(C.getIntWidth(QualType(T, 0)), 11197 !ET->isSignedIntegerOrEnumerationType()); 11198 } 11199 11200 unsigned NumPositive = Enum->getNumPositiveBits(); 11201 unsigned NumNegative = Enum->getNumNegativeBits(); 11202 11203 if (NumNegative == 0) 11204 return IntRange(NumPositive, true/*NonNegative*/); 11205 else 11206 return IntRange(std::max(NumPositive + 1, NumNegative), 11207 false/*NonNegative*/); 11208 } 11209 11210 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11211 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11212 11213 const BuiltinType *BT = cast<BuiltinType>(T); 11214 assert(BT->isInteger()); 11215 11216 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11217 } 11218 11219 /// Returns the "target" range of a canonical integral type, i.e. 11220 /// the range of values expressible in the type. 11221 /// 11222 /// This matches forValueOfCanonicalType except that enums have the 11223 /// full range of their type, not the range of their enumerators. 11224 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 11225 assert(T->isCanonicalUnqualified()); 11226 11227 if (const VectorType *VT = dyn_cast<VectorType>(T)) 11228 T = VT->getElementType().getTypePtr(); 11229 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 11230 T = CT->getElementType().getTypePtr(); 11231 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 11232 T = AT->getValueType().getTypePtr(); 11233 if (const EnumType *ET = dyn_cast<EnumType>(T)) 11234 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 11235 11236 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 11237 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 11238 11239 const BuiltinType *BT = cast<BuiltinType>(T); 11240 assert(BT->isInteger()); 11241 11242 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 11243 } 11244 11245 /// Returns the supremum of two ranges: i.e. their conservative merge. 11246 static IntRange join(IntRange L, IntRange R) { 11247 bool Unsigned = L.NonNegative && R.NonNegative; 11248 return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned, 11249 L.NonNegative && R.NonNegative); 11250 } 11251 11252 /// Return the range of a bitwise-AND of the two ranges. 11253 static IntRange bit_and(IntRange L, IntRange R) { 11254 unsigned Bits = std::max(L.Width, R.Width); 11255 bool NonNegative = false; 11256 if (L.NonNegative) { 11257 Bits = std::min(Bits, L.Width); 11258 NonNegative = true; 11259 } 11260 if (R.NonNegative) { 11261 Bits = std::min(Bits, R.Width); 11262 NonNegative = true; 11263 } 11264 return IntRange(Bits, NonNegative); 11265 } 11266 11267 /// Return the range of a sum of the two ranges. 11268 static IntRange sum(IntRange L, IntRange R) { 11269 bool Unsigned = L.NonNegative && R.NonNegative; 11270 return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned, 11271 Unsigned); 11272 } 11273 11274 /// Return the range of a difference of the two ranges. 11275 static IntRange difference(IntRange L, IntRange R) { 11276 // We need a 1-bit-wider range if: 11277 // 1) LHS can be negative: least value can be reduced. 11278 // 2) RHS can be negative: greatest value can be increased. 11279 bool CanWiden = !L.NonNegative || !R.NonNegative; 11280 bool Unsigned = L.NonNegative && R.Width == 0; 11281 return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden + 11282 !Unsigned, 11283 Unsigned); 11284 } 11285 11286 /// Return the range of a product of the two ranges. 11287 static IntRange product(IntRange L, IntRange R) { 11288 // If both LHS and RHS can be negative, we can form 11289 // -2^L * -2^R = 2^(L + R) 11290 // which requires L + R + 1 value bits to represent. 11291 bool CanWiden = !L.NonNegative && !R.NonNegative; 11292 bool Unsigned = L.NonNegative && R.NonNegative; 11293 return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned, 11294 Unsigned); 11295 } 11296 11297 /// Return the range of a remainder operation between the two ranges. 11298 static IntRange rem(IntRange L, IntRange R) { 11299 // The result of a remainder can't be larger than the result of 11300 // either side. The sign of the result is the sign of the LHS. 11301 bool Unsigned = L.NonNegative; 11302 return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned, 11303 Unsigned); 11304 } 11305 }; 11306 11307 } // namespace 11308 11309 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 11310 unsigned MaxWidth) { 11311 if (value.isSigned() && value.isNegative()) 11312 return IntRange(value.getMinSignedBits(), false); 11313 11314 if (value.getBitWidth() > MaxWidth) 11315 value = value.trunc(MaxWidth); 11316 11317 // isNonNegative() just checks the sign bit without considering 11318 // signedness. 11319 return IntRange(value.getActiveBits(), true); 11320 } 11321 11322 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 11323 unsigned MaxWidth) { 11324 if (result.isInt()) 11325 return GetValueRange(C, result.getInt(), MaxWidth); 11326 11327 if (result.isVector()) { 11328 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 11329 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 11330 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 11331 R = IntRange::join(R, El); 11332 } 11333 return R; 11334 } 11335 11336 if (result.isComplexInt()) { 11337 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 11338 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 11339 return IntRange::join(R, I); 11340 } 11341 11342 // This can happen with lossless casts to intptr_t of "based" lvalues. 11343 // Assume it might use arbitrary bits. 11344 // FIXME: The only reason we need to pass the type in here is to get 11345 // the sign right on this one case. It would be nice if APValue 11346 // preserved this. 11347 assert(result.isLValue() || result.isAddrLabelDiff()); 11348 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 11349 } 11350 11351 static QualType GetExprType(const Expr *E) { 11352 QualType Ty = E->getType(); 11353 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 11354 Ty = AtomicRHS->getValueType(); 11355 return Ty; 11356 } 11357 11358 /// Pseudo-evaluate the given integer expression, estimating the 11359 /// range of values it might take. 11360 /// 11361 /// \param MaxWidth The width to which the value will be truncated. 11362 /// \param Approximate If \c true, return a likely range for the result: in 11363 /// particular, assume that arithmetic on narrower types doesn't leave 11364 /// those types. If \c false, return a range including all possible 11365 /// result values. 11366 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 11367 bool InConstantContext, bool Approximate) { 11368 E = E->IgnoreParens(); 11369 11370 // Try a full evaluation first. 11371 Expr::EvalResult result; 11372 if (E->EvaluateAsRValue(result, C, InConstantContext)) 11373 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 11374 11375 // I think we only want to look through implicit casts here; if the 11376 // user has an explicit widening cast, we should treat the value as 11377 // being of the new, wider type. 11378 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 11379 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 11380 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext, 11381 Approximate); 11382 11383 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 11384 11385 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 11386 CE->getCastKind() == CK_BooleanToSignedIntegral; 11387 11388 // Assume that non-integer casts can span the full range of the type. 11389 if (!isIntegerCast) 11390 return OutputTypeRange; 11391 11392 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 11393 std::min(MaxWidth, OutputTypeRange.Width), 11394 InConstantContext, Approximate); 11395 11396 // Bail out if the subexpr's range is as wide as the cast type. 11397 if (SubRange.Width >= OutputTypeRange.Width) 11398 return OutputTypeRange; 11399 11400 // Otherwise, we take the smaller width, and we're non-negative if 11401 // either the output type or the subexpr is. 11402 return IntRange(SubRange.Width, 11403 SubRange.NonNegative || OutputTypeRange.NonNegative); 11404 } 11405 11406 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11407 // If we can fold the condition, just take that operand. 11408 bool CondResult; 11409 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 11410 return GetExprRange(C, 11411 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 11412 MaxWidth, InConstantContext, Approximate); 11413 11414 // Otherwise, conservatively merge. 11415 // GetExprRange requires an integer expression, but a throw expression 11416 // results in a void type. 11417 Expr *E = CO->getTrueExpr(); 11418 IntRange L = E->getType()->isVoidType() 11419 ? IntRange{0, true} 11420 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11421 E = CO->getFalseExpr(); 11422 IntRange R = E->getType()->isVoidType() 11423 ? IntRange{0, true} 11424 : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate); 11425 return IntRange::join(L, R); 11426 } 11427 11428 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11429 IntRange (*Combine)(IntRange, IntRange) = IntRange::join; 11430 11431 switch (BO->getOpcode()) { 11432 case BO_Cmp: 11433 llvm_unreachable("builtin <=> should have class type"); 11434 11435 // Boolean-valued operations are single-bit and positive. 11436 case BO_LAnd: 11437 case BO_LOr: 11438 case BO_LT: 11439 case BO_GT: 11440 case BO_LE: 11441 case BO_GE: 11442 case BO_EQ: 11443 case BO_NE: 11444 return IntRange::forBoolType(); 11445 11446 // The type of the assignments is the type of the LHS, so the RHS 11447 // is not necessarily the same type. 11448 case BO_MulAssign: 11449 case BO_DivAssign: 11450 case BO_RemAssign: 11451 case BO_AddAssign: 11452 case BO_SubAssign: 11453 case BO_XorAssign: 11454 case BO_OrAssign: 11455 // TODO: bitfields? 11456 return IntRange::forValueOfType(C, GetExprType(E)); 11457 11458 // Simple assignments just pass through the RHS, which will have 11459 // been coerced to the LHS type. 11460 case BO_Assign: 11461 // TODO: bitfields? 11462 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11463 Approximate); 11464 11465 // Operations with opaque sources are black-listed. 11466 case BO_PtrMemD: 11467 case BO_PtrMemI: 11468 return IntRange::forValueOfType(C, GetExprType(E)); 11469 11470 // Bitwise-and uses the *infinum* of the two source ranges. 11471 case BO_And: 11472 case BO_AndAssign: 11473 Combine = IntRange::bit_and; 11474 break; 11475 11476 // Left shift gets black-listed based on a judgement call. 11477 case BO_Shl: 11478 // ...except that we want to treat '1 << (blah)' as logically 11479 // positive. It's an important idiom. 11480 if (IntegerLiteral *I 11481 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 11482 if (I->getValue() == 1) { 11483 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 11484 return IntRange(R.Width, /*NonNegative*/ true); 11485 } 11486 } 11487 LLVM_FALLTHROUGH; 11488 11489 case BO_ShlAssign: 11490 return IntRange::forValueOfType(C, GetExprType(E)); 11491 11492 // Right shift by a constant can narrow its left argument. 11493 case BO_Shr: 11494 case BO_ShrAssign: { 11495 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext, 11496 Approximate); 11497 11498 // If the shift amount is a positive constant, drop the width by 11499 // that much. 11500 if (Optional<llvm::APSInt> shift = 11501 BO->getRHS()->getIntegerConstantExpr(C)) { 11502 if (shift->isNonNegative()) { 11503 unsigned zext = shift->getZExtValue(); 11504 if (zext >= L.Width) 11505 L.Width = (L.NonNegative ? 0 : 1); 11506 else 11507 L.Width -= zext; 11508 } 11509 } 11510 11511 return L; 11512 } 11513 11514 // Comma acts as its right operand. 11515 case BO_Comma: 11516 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext, 11517 Approximate); 11518 11519 case BO_Add: 11520 if (!Approximate) 11521 Combine = IntRange::sum; 11522 break; 11523 11524 case BO_Sub: 11525 if (BO->getLHS()->getType()->isPointerType()) 11526 return IntRange::forValueOfType(C, GetExprType(E)); 11527 if (!Approximate) 11528 Combine = IntRange::difference; 11529 break; 11530 11531 case BO_Mul: 11532 if (!Approximate) 11533 Combine = IntRange::product; 11534 break; 11535 11536 // The width of a division result is mostly determined by the size 11537 // of the LHS. 11538 case BO_Div: { 11539 // Don't 'pre-truncate' the operands. 11540 unsigned opWidth = C.getIntWidth(GetExprType(E)); 11541 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, 11542 Approximate); 11543 11544 // If the divisor is constant, use that. 11545 if (Optional<llvm::APSInt> divisor = 11546 BO->getRHS()->getIntegerConstantExpr(C)) { 11547 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 11548 if (log2 >= L.Width) 11549 L.Width = (L.NonNegative ? 0 : 1); 11550 else 11551 L.Width = std::min(L.Width - log2, MaxWidth); 11552 return L; 11553 } 11554 11555 // Otherwise, just use the LHS's width. 11556 // FIXME: This is wrong if the LHS could be its minimal value and the RHS 11557 // could be -1. 11558 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, 11559 Approximate); 11560 return IntRange(L.Width, L.NonNegative && R.NonNegative); 11561 } 11562 11563 case BO_Rem: 11564 Combine = IntRange::rem; 11565 break; 11566 11567 // The default behavior is okay for these. 11568 case BO_Xor: 11569 case BO_Or: 11570 break; 11571 } 11572 11573 // Combine the two ranges, but limit the result to the type in which we 11574 // performed the computation. 11575 QualType T = GetExprType(E); 11576 unsigned opWidth = C.getIntWidth(T); 11577 IntRange L = 11578 GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate); 11579 IntRange R = 11580 GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate); 11581 IntRange C = Combine(L, R); 11582 C.NonNegative |= T->isUnsignedIntegerOrEnumerationType(); 11583 C.Width = std::min(C.Width, MaxWidth); 11584 return C; 11585 } 11586 11587 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 11588 switch (UO->getOpcode()) { 11589 // Boolean-valued operations are white-listed. 11590 case UO_LNot: 11591 return IntRange::forBoolType(); 11592 11593 // Operations with opaque sources are black-listed. 11594 case UO_Deref: 11595 case UO_AddrOf: // should be impossible 11596 return IntRange::forValueOfType(C, GetExprType(E)); 11597 11598 default: 11599 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext, 11600 Approximate); 11601 } 11602 } 11603 11604 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11605 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext, 11606 Approximate); 11607 11608 if (const auto *BitField = E->getSourceBitField()) 11609 return IntRange(BitField->getBitWidthValue(C), 11610 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 11611 11612 return IntRange::forValueOfType(C, GetExprType(E)); 11613 } 11614 11615 static IntRange GetExprRange(ASTContext &C, const Expr *E, 11616 bool InConstantContext, bool Approximate) { 11617 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext, 11618 Approximate); 11619 } 11620 11621 /// Checks whether the given value, which currently has the given 11622 /// source semantics, has the same value when coerced through the 11623 /// target semantics. 11624 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 11625 const llvm::fltSemantics &Src, 11626 const llvm::fltSemantics &Tgt) { 11627 llvm::APFloat truncated = value; 11628 11629 bool ignored; 11630 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 11631 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 11632 11633 return truncated.bitwiseIsEqual(value); 11634 } 11635 11636 /// Checks whether the given value, which currently has the given 11637 /// source semantics, has the same value when coerced through the 11638 /// target semantics. 11639 /// 11640 /// The value might be a vector of floats (or a complex number). 11641 static bool IsSameFloatAfterCast(const APValue &value, 11642 const llvm::fltSemantics &Src, 11643 const llvm::fltSemantics &Tgt) { 11644 if (value.isFloat()) 11645 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 11646 11647 if (value.isVector()) { 11648 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 11649 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 11650 return false; 11651 return true; 11652 } 11653 11654 assert(value.isComplexFloat()); 11655 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 11656 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 11657 } 11658 11659 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 11660 bool IsListInit = false); 11661 11662 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 11663 // Suppress cases where we are comparing against an enum constant. 11664 if (const DeclRefExpr *DR = 11665 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 11666 if (isa<EnumConstantDecl>(DR->getDecl())) 11667 return true; 11668 11669 // Suppress cases where the value is expanded from a macro, unless that macro 11670 // is how a language represents a boolean literal. This is the case in both C 11671 // and Objective-C. 11672 SourceLocation BeginLoc = E->getBeginLoc(); 11673 if (BeginLoc.isMacroID()) { 11674 StringRef MacroName = Lexer::getImmediateMacroName( 11675 BeginLoc, S.getSourceManager(), S.getLangOpts()); 11676 return MacroName != "YES" && MacroName != "NO" && 11677 MacroName != "true" && MacroName != "false"; 11678 } 11679 11680 return false; 11681 } 11682 11683 static bool isKnownToHaveUnsignedValue(Expr *E) { 11684 return E->getType()->isIntegerType() && 11685 (!E->getType()->isSignedIntegerType() || 11686 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 11687 } 11688 11689 namespace { 11690 /// The promoted range of values of a type. In general this has the 11691 /// following structure: 11692 /// 11693 /// |-----------| . . . |-----------| 11694 /// ^ ^ ^ ^ 11695 /// Min HoleMin HoleMax Max 11696 /// 11697 /// ... where there is only a hole if a signed type is promoted to unsigned 11698 /// (in which case Min and Max are the smallest and largest representable 11699 /// values). 11700 struct PromotedRange { 11701 // Min, or HoleMax if there is a hole. 11702 llvm::APSInt PromotedMin; 11703 // Max, or HoleMin if there is a hole. 11704 llvm::APSInt PromotedMax; 11705 11706 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 11707 if (R.Width == 0) 11708 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 11709 else if (R.Width >= BitWidth && !Unsigned) { 11710 // Promotion made the type *narrower*. This happens when promoting 11711 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 11712 // Treat all values of 'signed int' as being in range for now. 11713 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 11714 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 11715 } else { 11716 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 11717 .extOrTrunc(BitWidth); 11718 PromotedMin.setIsUnsigned(Unsigned); 11719 11720 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 11721 .extOrTrunc(BitWidth); 11722 PromotedMax.setIsUnsigned(Unsigned); 11723 } 11724 } 11725 11726 // Determine whether this range is contiguous (has no hole). 11727 bool isContiguous() const { return PromotedMin <= PromotedMax; } 11728 11729 // Where a constant value is within the range. 11730 enum ComparisonResult { 11731 LT = 0x1, 11732 LE = 0x2, 11733 GT = 0x4, 11734 GE = 0x8, 11735 EQ = 0x10, 11736 NE = 0x20, 11737 InRangeFlag = 0x40, 11738 11739 Less = LE | LT | NE, 11740 Min = LE | InRangeFlag, 11741 InRange = InRangeFlag, 11742 Max = GE | InRangeFlag, 11743 Greater = GE | GT | NE, 11744 11745 OnlyValue = LE | GE | EQ | InRangeFlag, 11746 InHole = NE 11747 }; 11748 11749 ComparisonResult compare(const llvm::APSInt &Value) const { 11750 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 11751 Value.isUnsigned() == PromotedMin.isUnsigned()); 11752 if (!isContiguous()) { 11753 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 11754 if (Value.isMinValue()) return Min; 11755 if (Value.isMaxValue()) return Max; 11756 if (Value >= PromotedMin) return InRange; 11757 if (Value <= PromotedMax) return InRange; 11758 return InHole; 11759 } 11760 11761 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 11762 case -1: return Less; 11763 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 11764 case 1: 11765 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 11766 case -1: return InRange; 11767 case 0: return Max; 11768 case 1: return Greater; 11769 } 11770 } 11771 11772 llvm_unreachable("impossible compare result"); 11773 } 11774 11775 static llvm::Optional<StringRef> 11776 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 11777 if (Op == BO_Cmp) { 11778 ComparisonResult LTFlag = LT, GTFlag = GT; 11779 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 11780 11781 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 11782 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 11783 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 11784 return llvm::None; 11785 } 11786 11787 ComparisonResult TrueFlag, FalseFlag; 11788 if (Op == BO_EQ) { 11789 TrueFlag = EQ; 11790 FalseFlag = NE; 11791 } else if (Op == BO_NE) { 11792 TrueFlag = NE; 11793 FalseFlag = EQ; 11794 } else { 11795 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 11796 TrueFlag = LT; 11797 FalseFlag = GE; 11798 } else { 11799 TrueFlag = GT; 11800 FalseFlag = LE; 11801 } 11802 if (Op == BO_GE || Op == BO_LE) 11803 std::swap(TrueFlag, FalseFlag); 11804 } 11805 if (R & TrueFlag) 11806 return StringRef("true"); 11807 if (R & FalseFlag) 11808 return StringRef("false"); 11809 return llvm::None; 11810 } 11811 }; 11812 } 11813 11814 static bool HasEnumType(Expr *E) { 11815 // Strip off implicit integral promotions. 11816 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 11817 if (ICE->getCastKind() != CK_IntegralCast && 11818 ICE->getCastKind() != CK_NoOp) 11819 break; 11820 E = ICE->getSubExpr(); 11821 } 11822 11823 return E->getType()->isEnumeralType(); 11824 } 11825 11826 static int classifyConstantValue(Expr *Constant) { 11827 // The values of this enumeration are used in the diagnostics 11828 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 11829 enum ConstantValueKind { 11830 Miscellaneous = 0, 11831 LiteralTrue, 11832 LiteralFalse 11833 }; 11834 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 11835 return BL->getValue() ? ConstantValueKind::LiteralTrue 11836 : ConstantValueKind::LiteralFalse; 11837 return ConstantValueKind::Miscellaneous; 11838 } 11839 11840 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 11841 Expr *Constant, Expr *Other, 11842 const llvm::APSInt &Value, 11843 bool RhsConstant) { 11844 if (S.inTemplateInstantiation()) 11845 return false; 11846 11847 Expr *OriginalOther = Other; 11848 11849 Constant = Constant->IgnoreParenImpCasts(); 11850 Other = Other->IgnoreParenImpCasts(); 11851 11852 // Suppress warnings on tautological comparisons between values of the same 11853 // enumeration type. There are only two ways we could warn on this: 11854 // - If the constant is outside the range of representable values of 11855 // the enumeration. In such a case, we should warn about the cast 11856 // to enumeration type, not about the comparison. 11857 // - If the constant is the maximum / minimum in-range value. For an 11858 // enumeratin type, such comparisons can be meaningful and useful. 11859 if (Constant->getType()->isEnumeralType() && 11860 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 11861 return false; 11862 11863 IntRange OtherValueRange = GetExprRange( 11864 S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false); 11865 11866 QualType OtherT = Other->getType(); 11867 if (const auto *AT = OtherT->getAs<AtomicType>()) 11868 OtherT = AT->getValueType(); 11869 IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT); 11870 11871 // Special case for ObjC BOOL on targets where its a typedef for a signed char 11872 // (Namely, macOS). FIXME: IntRange::forValueOfType should do this. 11873 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 11874 S.NSAPIObj->isObjCBOOLType(OtherT) && 11875 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 11876 11877 // Whether we're treating Other as being a bool because of the form of 11878 // expression despite it having another type (typically 'int' in C). 11879 bool OtherIsBooleanDespiteType = 11880 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 11881 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 11882 OtherTypeRange = OtherValueRange = IntRange::forBoolType(); 11883 11884 // Check if all values in the range of possible values of this expression 11885 // lead to the same comparison outcome. 11886 PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(), 11887 Value.isUnsigned()); 11888 auto Cmp = OtherPromotedValueRange.compare(Value); 11889 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 11890 if (!Result) 11891 return false; 11892 11893 // Also consider the range determined by the type alone. This allows us to 11894 // classify the warning under the proper diagnostic group. 11895 bool TautologicalTypeCompare = false; 11896 { 11897 PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(), 11898 Value.isUnsigned()); 11899 auto TypeCmp = OtherPromotedTypeRange.compare(Value); 11900 if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp, 11901 RhsConstant)) { 11902 TautologicalTypeCompare = true; 11903 Cmp = TypeCmp; 11904 Result = TypeResult; 11905 } 11906 } 11907 11908 // Don't warn if the non-constant operand actually always evaluates to the 11909 // same value. 11910 if (!TautologicalTypeCompare && OtherValueRange.Width == 0) 11911 return false; 11912 11913 // Suppress the diagnostic for an in-range comparison if the constant comes 11914 // from a macro or enumerator. We don't want to diagnose 11915 // 11916 // some_long_value <= INT_MAX 11917 // 11918 // when sizeof(int) == sizeof(long). 11919 bool InRange = Cmp & PromotedRange::InRangeFlag; 11920 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 11921 return false; 11922 11923 // A comparison of an unsigned bit-field against 0 is really a type problem, 11924 // even though at the type level the bit-field might promote to 'signed int'. 11925 if (Other->refersToBitField() && InRange && Value == 0 && 11926 Other->getType()->isUnsignedIntegerOrEnumerationType()) 11927 TautologicalTypeCompare = true; 11928 11929 // If this is a comparison to an enum constant, include that 11930 // constant in the diagnostic. 11931 const EnumConstantDecl *ED = nullptr; 11932 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 11933 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 11934 11935 // Should be enough for uint128 (39 decimal digits) 11936 SmallString<64> PrettySourceValue; 11937 llvm::raw_svector_ostream OS(PrettySourceValue); 11938 if (ED) { 11939 OS << '\'' << *ED << "' (" << Value << ")"; 11940 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 11941 Constant->IgnoreParenImpCasts())) { 11942 OS << (BL->getValue() ? "YES" : "NO"); 11943 } else { 11944 OS << Value; 11945 } 11946 11947 if (!TautologicalTypeCompare) { 11948 S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range) 11949 << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative 11950 << E->getOpcodeStr() << OS.str() << *Result 11951 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11952 return true; 11953 } 11954 11955 if (IsObjCSignedCharBool) { 11956 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 11957 S.PDiag(diag::warn_tautological_compare_objc_bool) 11958 << OS.str() << *Result); 11959 return true; 11960 } 11961 11962 // FIXME: We use a somewhat different formatting for the in-range cases and 11963 // cases involving boolean values for historical reasons. We should pick a 11964 // consistent way of presenting these diagnostics. 11965 if (!InRange || Other->isKnownToHaveBooleanValue()) { 11966 11967 S.DiagRuntimeBehavior( 11968 E->getOperatorLoc(), E, 11969 S.PDiag(!InRange ? diag::warn_out_of_range_compare 11970 : diag::warn_tautological_bool_compare) 11971 << OS.str() << classifyConstantValue(Constant) << OtherT 11972 << OtherIsBooleanDespiteType << *Result 11973 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 11974 } else { 11975 bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy; 11976 unsigned Diag = 11977 (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 11978 ? (HasEnumType(OriginalOther) 11979 ? diag::warn_unsigned_enum_always_true_comparison 11980 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison 11981 : diag::warn_unsigned_always_true_comparison) 11982 : diag::warn_tautological_constant_compare; 11983 11984 S.Diag(E->getOperatorLoc(), Diag) 11985 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 11986 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 11987 } 11988 11989 return true; 11990 } 11991 11992 /// Analyze the operands of the given comparison. Implements the 11993 /// fallback case from AnalyzeComparison. 11994 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 11995 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11996 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11997 } 11998 11999 /// Implements -Wsign-compare. 12000 /// 12001 /// \param E the binary operator to check for warnings 12002 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 12003 // The type the comparison is being performed in. 12004 QualType T = E->getLHS()->getType(); 12005 12006 // Only analyze comparison operators where both sides have been converted to 12007 // the same type. 12008 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 12009 return AnalyzeImpConvsInComparison(S, E); 12010 12011 // Don't analyze value-dependent comparisons directly. 12012 if (E->isValueDependent()) 12013 return AnalyzeImpConvsInComparison(S, E); 12014 12015 Expr *LHS = E->getLHS(); 12016 Expr *RHS = E->getRHS(); 12017 12018 if (T->isIntegralType(S.Context)) { 12019 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 12020 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 12021 12022 // We don't care about expressions whose result is a constant. 12023 if (RHSValue && LHSValue) 12024 return AnalyzeImpConvsInComparison(S, E); 12025 12026 // We only care about expressions where just one side is literal 12027 if ((bool)RHSValue ^ (bool)LHSValue) { 12028 // Is the constant on the RHS or LHS? 12029 const bool RhsConstant = (bool)RHSValue; 12030 Expr *Const = RhsConstant ? RHS : LHS; 12031 Expr *Other = RhsConstant ? LHS : RHS; 12032 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 12033 12034 // Check whether an integer constant comparison results in a value 12035 // of 'true' or 'false'. 12036 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 12037 return AnalyzeImpConvsInComparison(S, E); 12038 } 12039 } 12040 12041 if (!T->hasUnsignedIntegerRepresentation()) { 12042 // We don't do anything special if this isn't an unsigned integral 12043 // comparison: we're only interested in integral comparisons, and 12044 // signed comparisons only happen in cases we don't care to warn about. 12045 return AnalyzeImpConvsInComparison(S, E); 12046 } 12047 12048 LHS = LHS->IgnoreParenImpCasts(); 12049 RHS = RHS->IgnoreParenImpCasts(); 12050 12051 if (!S.getLangOpts().CPlusPlus) { 12052 // Avoid warning about comparison of integers with different signs when 12053 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 12054 // the type of `E`. 12055 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 12056 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12057 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 12058 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 12059 } 12060 12061 // Check to see if one of the (unmodified) operands is of different 12062 // signedness. 12063 Expr *signedOperand, *unsignedOperand; 12064 if (LHS->getType()->hasSignedIntegerRepresentation()) { 12065 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 12066 "unsigned comparison between two signed integer expressions?"); 12067 signedOperand = LHS; 12068 unsignedOperand = RHS; 12069 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 12070 signedOperand = RHS; 12071 unsignedOperand = LHS; 12072 } else { 12073 return AnalyzeImpConvsInComparison(S, E); 12074 } 12075 12076 // Otherwise, calculate the effective range of the signed operand. 12077 IntRange signedRange = GetExprRange( 12078 S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true); 12079 12080 // Go ahead and analyze implicit conversions in the operands. Note 12081 // that we skip the implicit conversions on both sides. 12082 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 12083 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 12084 12085 // If the signed range is non-negative, -Wsign-compare won't fire. 12086 if (signedRange.NonNegative) 12087 return; 12088 12089 // For (in)equality comparisons, if the unsigned operand is a 12090 // constant which cannot collide with a overflowed signed operand, 12091 // then reinterpreting the signed operand as unsigned will not 12092 // change the result of the comparison. 12093 if (E->isEqualityOp()) { 12094 unsigned comparisonWidth = S.Context.getIntWidth(T); 12095 IntRange unsignedRange = 12096 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(), 12097 /*Approximate*/ true); 12098 12099 // We should never be unable to prove that the unsigned operand is 12100 // non-negative. 12101 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 12102 12103 if (unsignedRange.Width < comparisonWidth) 12104 return; 12105 } 12106 12107 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 12108 S.PDiag(diag::warn_mixed_sign_comparison) 12109 << LHS->getType() << RHS->getType() 12110 << LHS->getSourceRange() << RHS->getSourceRange()); 12111 } 12112 12113 /// Analyzes an attempt to assign the given value to a bitfield. 12114 /// 12115 /// Returns true if there was something fishy about the attempt. 12116 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 12117 SourceLocation InitLoc) { 12118 assert(Bitfield->isBitField()); 12119 if (Bitfield->isInvalidDecl()) 12120 return false; 12121 12122 // White-list bool bitfields. 12123 QualType BitfieldType = Bitfield->getType(); 12124 if (BitfieldType->isBooleanType()) 12125 return false; 12126 12127 if (BitfieldType->isEnumeralType()) { 12128 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 12129 // If the underlying enum type was not explicitly specified as an unsigned 12130 // type and the enum contain only positive values, MSVC++ will cause an 12131 // inconsistency by storing this as a signed type. 12132 if (S.getLangOpts().CPlusPlus11 && 12133 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 12134 BitfieldEnumDecl->getNumPositiveBits() > 0 && 12135 BitfieldEnumDecl->getNumNegativeBits() == 0) { 12136 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 12137 << BitfieldEnumDecl; 12138 } 12139 } 12140 12141 if (Bitfield->getType()->isBooleanType()) 12142 return false; 12143 12144 // Ignore value- or type-dependent expressions. 12145 if (Bitfield->getBitWidth()->isValueDependent() || 12146 Bitfield->getBitWidth()->isTypeDependent() || 12147 Init->isValueDependent() || 12148 Init->isTypeDependent()) 12149 return false; 12150 12151 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 12152 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 12153 12154 Expr::EvalResult Result; 12155 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 12156 Expr::SE_AllowSideEffects)) { 12157 // The RHS is not constant. If the RHS has an enum type, make sure the 12158 // bitfield is wide enough to hold all the values of the enum without 12159 // truncation. 12160 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 12161 EnumDecl *ED = EnumTy->getDecl(); 12162 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 12163 12164 // Enum types are implicitly signed on Windows, so check if there are any 12165 // negative enumerators to see if the enum was intended to be signed or 12166 // not. 12167 bool SignedEnum = ED->getNumNegativeBits() > 0; 12168 12169 // Check for surprising sign changes when assigning enum values to a 12170 // bitfield of different signedness. If the bitfield is signed and we 12171 // have exactly the right number of bits to store this unsigned enum, 12172 // suggest changing the enum to an unsigned type. This typically happens 12173 // on Windows where unfixed enums always use an underlying type of 'int'. 12174 unsigned DiagID = 0; 12175 if (SignedEnum && !SignedBitfield) { 12176 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 12177 } else if (SignedBitfield && !SignedEnum && 12178 ED->getNumPositiveBits() == FieldWidth) { 12179 DiagID = diag::warn_signed_bitfield_enum_conversion; 12180 } 12181 12182 if (DiagID) { 12183 S.Diag(InitLoc, DiagID) << Bitfield << ED; 12184 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 12185 SourceRange TypeRange = 12186 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 12187 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 12188 << SignedEnum << TypeRange; 12189 } 12190 12191 // Compute the required bitwidth. If the enum has negative values, we need 12192 // one more bit than the normal number of positive bits to represent the 12193 // sign bit. 12194 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 12195 ED->getNumNegativeBits()) 12196 : ED->getNumPositiveBits(); 12197 12198 // Check the bitwidth. 12199 if (BitsNeeded > FieldWidth) { 12200 Expr *WidthExpr = Bitfield->getBitWidth(); 12201 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 12202 << Bitfield << ED; 12203 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 12204 << BitsNeeded << ED << WidthExpr->getSourceRange(); 12205 } 12206 } 12207 12208 return false; 12209 } 12210 12211 llvm::APSInt Value = Result.Val.getInt(); 12212 12213 unsigned OriginalWidth = Value.getBitWidth(); 12214 12215 if (!Value.isSigned() || Value.isNegative()) 12216 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 12217 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 12218 OriginalWidth = Value.getMinSignedBits(); 12219 12220 if (OriginalWidth <= FieldWidth) 12221 return false; 12222 12223 // Compute the value which the bitfield will contain. 12224 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 12225 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 12226 12227 // Check whether the stored value is equal to the original value. 12228 TruncatedValue = TruncatedValue.extend(OriginalWidth); 12229 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 12230 return false; 12231 12232 // Special-case bitfields of width 1: booleans are naturally 0/1, and 12233 // therefore don't strictly fit into a signed bitfield of width 1. 12234 if (FieldWidth == 1 && Value == 1) 12235 return false; 12236 12237 std::string PrettyValue = toString(Value, 10); 12238 std::string PrettyTrunc = toString(TruncatedValue, 10); 12239 12240 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 12241 << PrettyValue << PrettyTrunc << OriginalInit->getType() 12242 << Init->getSourceRange(); 12243 12244 return true; 12245 } 12246 12247 /// Analyze the given simple or compound assignment for warning-worthy 12248 /// operations. 12249 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 12250 // Just recurse on the LHS. 12251 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12252 12253 // We want to recurse on the RHS as normal unless we're assigning to 12254 // a bitfield. 12255 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 12256 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 12257 E->getOperatorLoc())) { 12258 // Recurse, ignoring any implicit conversions on the RHS. 12259 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 12260 E->getOperatorLoc()); 12261 } 12262 } 12263 12264 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12265 12266 // Diagnose implicitly sequentially-consistent atomic assignment. 12267 if (E->getLHS()->getType()->isAtomicType()) 12268 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12269 } 12270 12271 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12272 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 12273 SourceLocation CContext, unsigned diag, 12274 bool pruneControlFlow = false) { 12275 if (pruneControlFlow) { 12276 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12277 S.PDiag(diag) 12278 << SourceType << T << E->getSourceRange() 12279 << SourceRange(CContext)); 12280 return; 12281 } 12282 S.Diag(E->getExprLoc(), diag) 12283 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 12284 } 12285 12286 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 12287 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 12288 SourceLocation CContext, 12289 unsigned diag, bool pruneControlFlow = false) { 12290 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 12291 } 12292 12293 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 12294 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 12295 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 12296 } 12297 12298 static void adornObjCBoolConversionDiagWithTernaryFixit( 12299 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 12300 Expr *Ignored = SourceExpr->IgnoreImplicit(); 12301 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 12302 Ignored = OVE->getSourceExpr(); 12303 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 12304 isa<BinaryOperator>(Ignored) || 12305 isa<CXXOperatorCallExpr>(Ignored); 12306 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 12307 if (NeedsParens) 12308 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 12309 << FixItHint::CreateInsertion(EndLoc, ")"); 12310 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 12311 } 12312 12313 /// Diagnose an implicit cast from a floating point value to an integer value. 12314 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 12315 SourceLocation CContext) { 12316 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 12317 const bool PruneWarnings = S.inTemplateInstantiation(); 12318 12319 Expr *InnerE = E->IgnoreParenImpCasts(); 12320 // We also want to warn on, e.g., "int i = -1.234" 12321 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 12322 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 12323 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 12324 12325 const bool IsLiteral = 12326 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 12327 12328 llvm::APFloat Value(0.0); 12329 bool IsConstant = 12330 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 12331 if (!IsConstant) { 12332 if (isObjCSignedCharBool(S, T)) { 12333 return adornObjCBoolConversionDiagWithTernaryFixit( 12334 S, E, 12335 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 12336 << E->getType()); 12337 } 12338 12339 return DiagnoseImpCast(S, E, T, CContext, 12340 diag::warn_impcast_float_integer, PruneWarnings); 12341 } 12342 12343 bool isExact = false; 12344 12345 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 12346 T->hasUnsignedIntegerRepresentation()); 12347 llvm::APFloat::opStatus Result = Value.convertToInteger( 12348 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 12349 12350 // FIXME: Force the precision of the source value down so we don't print 12351 // digits which are usually useless (we don't really care here if we 12352 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 12353 // would automatically print the shortest representation, but it's a bit 12354 // tricky to implement. 12355 SmallString<16> PrettySourceValue; 12356 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 12357 precision = (precision * 59 + 195) / 196; 12358 Value.toString(PrettySourceValue, precision); 12359 12360 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 12361 return adornObjCBoolConversionDiagWithTernaryFixit( 12362 S, E, 12363 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 12364 << PrettySourceValue); 12365 } 12366 12367 if (Result == llvm::APFloat::opOK && isExact) { 12368 if (IsLiteral) return; 12369 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 12370 PruneWarnings); 12371 } 12372 12373 // Conversion of a floating-point value to a non-bool integer where the 12374 // integral part cannot be represented by the integer type is undefined. 12375 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 12376 return DiagnoseImpCast( 12377 S, E, T, CContext, 12378 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 12379 : diag::warn_impcast_float_to_integer_out_of_range, 12380 PruneWarnings); 12381 12382 unsigned DiagID = 0; 12383 if (IsLiteral) { 12384 // Warn on floating point literal to integer. 12385 DiagID = diag::warn_impcast_literal_float_to_integer; 12386 } else if (IntegerValue == 0) { 12387 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 12388 return DiagnoseImpCast(S, E, T, CContext, 12389 diag::warn_impcast_float_integer, PruneWarnings); 12390 } 12391 // Warn on non-zero to zero conversion. 12392 DiagID = diag::warn_impcast_float_to_integer_zero; 12393 } else { 12394 if (IntegerValue.isUnsigned()) { 12395 if (!IntegerValue.isMaxValue()) { 12396 return DiagnoseImpCast(S, E, T, CContext, 12397 diag::warn_impcast_float_integer, PruneWarnings); 12398 } 12399 } else { // IntegerValue.isSigned() 12400 if (!IntegerValue.isMaxSignedValue() && 12401 !IntegerValue.isMinSignedValue()) { 12402 return DiagnoseImpCast(S, E, T, CContext, 12403 diag::warn_impcast_float_integer, PruneWarnings); 12404 } 12405 } 12406 // Warn on evaluatable floating point expression to integer conversion. 12407 DiagID = diag::warn_impcast_float_to_integer; 12408 } 12409 12410 SmallString<16> PrettyTargetValue; 12411 if (IsBool) 12412 PrettyTargetValue = Value.isZero() ? "false" : "true"; 12413 else 12414 IntegerValue.toString(PrettyTargetValue); 12415 12416 if (PruneWarnings) { 12417 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12418 S.PDiag(DiagID) 12419 << E->getType() << T.getUnqualifiedType() 12420 << PrettySourceValue << PrettyTargetValue 12421 << E->getSourceRange() << SourceRange(CContext)); 12422 } else { 12423 S.Diag(E->getExprLoc(), DiagID) 12424 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 12425 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 12426 } 12427 } 12428 12429 /// Analyze the given compound assignment for the possible losing of 12430 /// floating-point precision. 12431 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 12432 assert(isa<CompoundAssignOperator>(E) && 12433 "Must be compound assignment operation"); 12434 // Recurse on the LHS and RHS in here 12435 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 12436 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 12437 12438 if (E->getLHS()->getType()->isAtomicType()) 12439 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 12440 12441 // Now check the outermost expression 12442 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 12443 const auto *RBT = cast<CompoundAssignOperator>(E) 12444 ->getComputationResultType() 12445 ->getAs<BuiltinType>(); 12446 12447 // The below checks assume source is floating point. 12448 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 12449 12450 // If source is floating point but target is an integer. 12451 if (ResultBT->isInteger()) 12452 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 12453 E->getExprLoc(), diag::warn_impcast_float_integer); 12454 12455 if (!ResultBT->isFloatingPoint()) 12456 return; 12457 12458 // If both source and target are floating points, warn about losing precision. 12459 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12460 QualType(ResultBT, 0), QualType(RBT, 0)); 12461 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 12462 // warn about dropping FP rank. 12463 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 12464 diag::warn_impcast_float_result_precision); 12465 } 12466 12467 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 12468 IntRange Range) { 12469 if (!Range.Width) return "0"; 12470 12471 llvm::APSInt ValueInRange = Value; 12472 ValueInRange.setIsSigned(!Range.NonNegative); 12473 ValueInRange = ValueInRange.trunc(Range.Width); 12474 return toString(ValueInRange, 10); 12475 } 12476 12477 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 12478 if (!isa<ImplicitCastExpr>(Ex)) 12479 return false; 12480 12481 Expr *InnerE = Ex->IgnoreParenImpCasts(); 12482 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 12483 const Type *Source = 12484 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 12485 if (Target->isDependentType()) 12486 return false; 12487 12488 const BuiltinType *FloatCandidateBT = 12489 dyn_cast<BuiltinType>(ToBool ? Source : Target); 12490 const Type *BoolCandidateType = ToBool ? Target : Source; 12491 12492 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 12493 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 12494 } 12495 12496 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 12497 SourceLocation CC) { 12498 unsigned NumArgs = TheCall->getNumArgs(); 12499 for (unsigned i = 0; i < NumArgs; ++i) { 12500 Expr *CurrA = TheCall->getArg(i); 12501 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 12502 continue; 12503 12504 bool IsSwapped = ((i > 0) && 12505 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 12506 IsSwapped |= ((i < (NumArgs - 1)) && 12507 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 12508 if (IsSwapped) { 12509 // Warn on this floating-point to bool conversion. 12510 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 12511 CurrA->getType(), CC, 12512 diag::warn_impcast_floating_point_to_bool); 12513 } 12514 } 12515 } 12516 12517 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 12518 SourceLocation CC) { 12519 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 12520 E->getExprLoc())) 12521 return; 12522 12523 // Don't warn on functions which have return type nullptr_t. 12524 if (isa<CallExpr>(E)) 12525 return; 12526 12527 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 12528 const Expr::NullPointerConstantKind NullKind = 12529 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 12530 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 12531 return; 12532 12533 // Return if target type is a safe conversion. 12534 if (T->isAnyPointerType() || T->isBlockPointerType() || 12535 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 12536 return; 12537 12538 SourceLocation Loc = E->getSourceRange().getBegin(); 12539 12540 // Venture through the macro stacks to get to the source of macro arguments. 12541 // The new location is a better location than the complete location that was 12542 // passed in. 12543 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 12544 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 12545 12546 // __null is usually wrapped in a macro. Go up a macro if that is the case. 12547 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 12548 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 12549 Loc, S.SourceMgr, S.getLangOpts()); 12550 if (MacroName == "NULL") 12551 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 12552 } 12553 12554 // Only warn if the null and context location are in the same macro expansion. 12555 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 12556 return; 12557 12558 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 12559 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 12560 << FixItHint::CreateReplacement(Loc, 12561 S.getFixItZeroLiteralForType(T, Loc)); 12562 } 12563 12564 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12565 ObjCArrayLiteral *ArrayLiteral); 12566 12567 static void 12568 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12569 ObjCDictionaryLiteral *DictionaryLiteral); 12570 12571 /// Check a single element within a collection literal against the 12572 /// target element type. 12573 static void checkObjCCollectionLiteralElement(Sema &S, 12574 QualType TargetElementType, 12575 Expr *Element, 12576 unsigned ElementKind) { 12577 // Skip a bitcast to 'id' or qualified 'id'. 12578 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 12579 if (ICE->getCastKind() == CK_BitCast && 12580 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 12581 Element = ICE->getSubExpr(); 12582 } 12583 12584 QualType ElementType = Element->getType(); 12585 ExprResult ElementResult(Element); 12586 if (ElementType->getAs<ObjCObjectPointerType>() && 12587 S.CheckSingleAssignmentConstraints(TargetElementType, 12588 ElementResult, 12589 false, false) 12590 != Sema::Compatible) { 12591 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 12592 << ElementType << ElementKind << TargetElementType 12593 << Element->getSourceRange(); 12594 } 12595 12596 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 12597 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 12598 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 12599 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 12600 } 12601 12602 /// Check an Objective-C array literal being converted to the given 12603 /// target type. 12604 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 12605 ObjCArrayLiteral *ArrayLiteral) { 12606 if (!S.NSArrayDecl) 12607 return; 12608 12609 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12610 if (!TargetObjCPtr) 12611 return; 12612 12613 if (TargetObjCPtr->isUnspecialized() || 12614 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12615 != S.NSArrayDecl->getCanonicalDecl()) 12616 return; 12617 12618 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12619 if (TypeArgs.size() != 1) 12620 return; 12621 12622 QualType TargetElementType = TypeArgs[0]; 12623 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 12624 checkObjCCollectionLiteralElement(S, TargetElementType, 12625 ArrayLiteral->getElement(I), 12626 0); 12627 } 12628 } 12629 12630 /// Check an Objective-C dictionary literal being converted to the given 12631 /// target type. 12632 static void 12633 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 12634 ObjCDictionaryLiteral *DictionaryLiteral) { 12635 if (!S.NSDictionaryDecl) 12636 return; 12637 12638 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 12639 if (!TargetObjCPtr) 12640 return; 12641 12642 if (TargetObjCPtr->isUnspecialized() || 12643 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 12644 != S.NSDictionaryDecl->getCanonicalDecl()) 12645 return; 12646 12647 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 12648 if (TypeArgs.size() != 2) 12649 return; 12650 12651 QualType TargetKeyType = TypeArgs[0]; 12652 QualType TargetObjectType = TypeArgs[1]; 12653 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 12654 auto Element = DictionaryLiteral->getKeyValueElement(I); 12655 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 12656 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 12657 } 12658 } 12659 12660 // Helper function to filter out cases for constant width constant conversion. 12661 // Don't warn on char array initialization or for non-decimal values. 12662 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 12663 SourceLocation CC) { 12664 // If initializing from a constant, and the constant starts with '0', 12665 // then it is a binary, octal, or hexadecimal. Allow these constants 12666 // to fill all the bits, even if there is a sign change. 12667 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 12668 const char FirstLiteralCharacter = 12669 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 12670 if (FirstLiteralCharacter == '0') 12671 return false; 12672 } 12673 12674 // If the CC location points to a '{', and the type is char, then assume 12675 // assume it is an array initialization. 12676 if (CC.isValid() && T->isCharType()) { 12677 const char FirstContextCharacter = 12678 S.getSourceManager().getCharacterData(CC)[0]; 12679 if (FirstContextCharacter == '{') 12680 return false; 12681 } 12682 12683 return true; 12684 } 12685 12686 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 12687 const auto *IL = dyn_cast<IntegerLiteral>(E); 12688 if (!IL) { 12689 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 12690 if (UO->getOpcode() == UO_Minus) 12691 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 12692 } 12693 } 12694 12695 return IL; 12696 } 12697 12698 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 12699 E = E->IgnoreParenImpCasts(); 12700 SourceLocation ExprLoc = E->getExprLoc(); 12701 12702 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 12703 BinaryOperator::Opcode Opc = BO->getOpcode(); 12704 Expr::EvalResult Result; 12705 // Do not diagnose unsigned shifts. 12706 if (Opc == BO_Shl) { 12707 const auto *LHS = getIntegerLiteral(BO->getLHS()); 12708 const auto *RHS = getIntegerLiteral(BO->getRHS()); 12709 if (LHS && LHS->getValue() == 0) 12710 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 12711 else if (!E->isValueDependent() && LHS && RHS && 12712 RHS->getValue().isNonNegative() && 12713 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 12714 S.Diag(ExprLoc, diag::warn_left_shift_always) 12715 << (Result.Val.getInt() != 0); 12716 else if (E->getType()->isSignedIntegerType()) 12717 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 12718 } 12719 } 12720 12721 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 12722 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 12723 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 12724 if (!LHS || !RHS) 12725 return; 12726 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 12727 (RHS->getValue() == 0 || RHS->getValue() == 1)) 12728 // Do not diagnose common idioms. 12729 return; 12730 if (LHS->getValue() != 0 && RHS->getValue() != 0) 12731 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 12732 } 12733 } 12734 12735 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 12736 SourceLocation CC, 12737 bool *ICContext = nullptr, 12738 bool IsListInit = false) { 12739 if (E->isTypeDependent() || E->isValueDependent()) return; 12740 12741 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 12742 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 12743 if (Source == Target) return; 12744 if (Target->isDependentType()) return; 12745 12746 // If the conversion context location is invalid don't complain. We also 12747 // don't want to emit a warning if the issue occurs from the expansion of 12748 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 12749 // delay this check as long as possible. Once we detect we are in that 12750 // scenario, we just return. 12751 if (CC.isInvalid()) 12752 return; 12753 12754 if (Source->isAtomicType()) 12755 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 12756 12757 // Diagnose implicit casts to bool. 12758 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 12759 if (isa<StringLiteral>(E)) 12760 // Warn on string literal to bool. Checks for string literals in logical 12761 // and expressions, for instance, assert(0 && "error here"), are 12762 // prevented by a check in AnalyzeImplicitConversions(). 12763 return DiagnoseImpCast(S, E, T, CC, 12764 diag::warn_impcast_string_literal_to_bool); 12765 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 12766 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 12767 // This covers the literal expressions that evaluate to Objective-C 12768 // objects. 12769 return DiagnoseImpCast(S, E, T, CC, 12770 diag::warn_impcast_objective_c_literal_to_bool); 12771 } 12772 if (Source->isPointerType() || Source->canDecayToPointerType()) { 12773 // Warn on pointer to bool conversion that is always true. 12774 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 12775 SourceRange(CC)); 12776 } 12777 } 12778 12779 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 12780 // is a typedef for signed char (macOS), then that constant value has to be 1 12781 // or 0. 12782 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 12783 Expr::EvalResult Result; 12784 if (E->EvaluateAsInt(Result, S.getASTContext(), 12785 Expr::SE_AllowSideEffects)) { 12786 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 12787 adornObjCBoolConversionDiagWithTernaryFixit( 12788 S, E, 12789 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 12790 << toString(Result.Val.getInt(), 10)); 12791 } 12792 return; 12793 } 12794 } 12795 12796 // Check implicit casts from Objective-C collection literals to specialized 12797 // collection types, e.g., NSArray<NSString *> *. 12798 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 12799 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 12800 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 12801 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 12802 12803 // Strip vector types. 12804 if (isa<VectorType>(Source)) { 12805 if (Target->isVLSTBuiltinType() && 12806 (S.Context.areCompatibleSveTypes(QualType(Target, 0), 12807 QualType(Source, 0)) || 12808 S.Context.areLaxCompatibleSveTypes(QualType(Target, 0), 12809 QualType(Source, 0)))) 12810 return; 12811 12812 if (!isa<VectorType>(Target)) { 12813 if (S.SourceMgr.isInSystemMacro(CC)) 12814 return; 12815 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 12816 } 12817 12818 // If the vector cast is cast between two vectors of the same size, it is 12819 // a bitcast, not a conversion. 12820 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 12821 return; 12822 12823 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 12824 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 12825 } 12826 if (auto VecTy = dyn_cast<VectorType>(Target)) 12827 Target = VecTy->getElementType().getTypePtr(); 12828 12829 // Strip complex types. 12830 if (isa<ComplexType>(Source)) { 12831 if (!isa<ComplexType>(Target)) { 12832 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 12833 return; 12834 12835 return DiagnoseImpCast(S, E, T, CC, 12836 S.getLangOpts().CPlusPlus 12837 ? diag::err_impcast_complex_scalar 12838 : diag::warn_impcast_complex_scalar); 12839 } 12840 12841 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 12842 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 12843 } 12844 12845 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 12846 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 12847 12848 // If the source is floating point... 12849 if (SourceBT && SourceBT->isFloatingPoint()) { 12850 // ...and the target is floating point... 12851 if (TargetBT && TargetBT->isFloatingPoint()) { 12852 // ...then warn if we're dropping FP rank. 12853 12854 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 12855 QualType(SourceBT, 0), QualType(TargetBT, 0)); 12856 if (Order > 0) { 12857 // Don't warn about float constants that are precisely 12858 // representable in the target type. 12859 Expr::EvalResult result; 12860 if (E->EvaluateAsRValue(result, S.Context)) { 12861 // Value might be a float, a float vector, or a float complex. 12862 if (IsSameFloatAfterCast(result.Val, 12863 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 12864 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 12865 return; 12866 } 12867 12868 if (S.SourceMgr.isInSystemMacro(CC)) 12869 return; 12870 12871 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 12872 } 12873 // ... or possibly if we're increasing rank, too 12874 else if (Order < 0) { 12875 if (S.SourceMgr.isInSystemMacro(CC)) 12876 return; 12877 12878 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 12879 } 12880 return; 12881 } 12882 12883 // If the target is integral, always warn. 12884 if (TargetBT && TargetBT->isInteger()) { 12885 if (S.SourceMgr.isInSystemMacro(CC)) 12886 return; 12887 12888 DiagnoseFloatingImpCast(S, E, T, CC); 12889 } 12890 12891 // Detect the case where a call result is converted from floating-point to 12892 // to bool, and the final argument to the call is converted from bool, to 12893 // discover this typo: 12894 // 12895 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 12896 // 12897 // FIXME: This is an incredibly special case; is there some more general 12898 // way to detect this class of misplaced-parentheses bug? 12899 if (Target->isBooleanType() && isa<CallExpr>(E)) { 12900 // Check last argument of function call to see if it is an 12901 // implicit cast from a type matching the type the result 12902 // is being cast to. 12903 CallExpr *CEx = cast<CallExpr>(E); 12904 if (unsigned NumArgs = CEx->getNumArgs()) { 12905 Expr *LastA = CEx->getArg(NumArgs - 1); 12906 Expr *InnerE = LastA->IgnoreParenImpCasts(); 12907 if (isa<ImplicitCastExpr>(LastA) && 12908 InnerE->getType()->isBooleanType()) { 12909 // Warn on this floating-point to bool conversion 12910 DiagnoseImpCast(S, E, T, CC, 12911 diag::warn_impcast_floating_point_to_bool); 12912 } 12913 } 12914 } 12915 return; 12916 } 12917 12918 // Valid casts involving fixed point types should be accounted for here. 12919 if (Source->isFixedPointType()) { 12920 if (Target->isUnsaturatedFixedPointType()) { 12921 Expr::EvalResult Result; 12922 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 12923 S.isConstantEvaluated())) { 12924 llvm::APFixedPoint Value = Result.Val.getFixedPoint(); 12925 llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 12926 llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T); 12927 if (Value > MaxVal || Value < MinVal) { 12928 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12929 S.PDiag(diag::warn_impcast_fixed_point_range) 12930 << Value.toString() << T 12931 << E->getSourceRange() 12932 << clang::SourceRange(CC)); 12933 return; 12934 } 12935 } 12936 } else if (Target->isIntegerType()) { 12937 Expr::EvalResult Result; 12938 if (!S.isConstantEvaluated() && 12939 E->EvaluateAsFixedPoint(Result, S.Context, 12940 Expr::SE_AllowSideEffects)) { 12941 llvm::APFixedPoint FXResult = Result.Val.getFixedPoint(); 12942 12943 bool Overflowed; 12944 llvm::APSInt IntResult = FXResult.convertToInt( 12945 S.Context.getIntWidth(T), 12946 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 12947 12948 if (Overflowed) { 12949 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12950 S.PDiag(diag::warn_impcast_fixed_point_range) 12951 << FXResult.toString() << T 12952 << E->getSourceRange() 12953 << clang::SourceRange(CC)); 12954 return; 12955 } 12956 } 12957 } 12958 } else if (Target->isUnsaturatedFixedPointType()) { 12959 if (Source->isIntegerType()) { 12960 Expr::EvalResult Result; 12961 if (!S.isConstantEvaluated() && 12962 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 12963 llvm::APSInt Value = Result.Val.getInt(); 12964 12965 bool Overflowed; 12966 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue( 12967 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 12968 12969 if (Overflowed) { 12970 S.DiagRuntimeBehavior(E->getExprLoc(), E, 12971 S.PDiag(diag::warn_impcast_fixed_point_range) 12972 << toString(Value, /*Radix=*/10) << T 12973 << E->getSourceRange() 12974 << clang::SourceRange(CC)); 12975 return; 12976 } 12977 } 12978 } 12979 } 12980 12981 // If we are casting an integer type to a floating point type without 12982 // initialization-list syntax, we might lose accuracy if the floating 12983 // point type has a narrower significand than the integer type. 12984 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 12985 TargetBT->isFloatingType() && !IsListInit) { 12986 // Determine the number of precision bits in the source integer type. 12987 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(), 12988 /*Approximate*/ true); 12989 unsigned int SourcePrecision = SourceRange.Width; 12990 12991 // Determine the number of precision bits in the 12992 // target floating point type. 12993 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 12994 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 12995 12996 if (SourcePrecision > 0 && TargetPrecision > 0 && 12997 SourcePrecision > TargetPrecision) { 12998 12999 if (Optional<llvm::APSInt> SourceInt = 13000 E->getIntegerConstantExpr(S.Context)) { 13001 // If the source integer is a constant, convert it to the target 13002 // floating point type. Issue a warning if the value changes 13003 // during the whole conversion. 13004 llvm::APFloat TargetFloatValue( 13005 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 13006 llvm::APFloat::opStatus ConversionStatus = 13007 TargetFloatValue.convertFromAPInt( 13008 *SourceInt, SourceBT->isSignedInteger(), 13009 llvm::APFloat::rmNearestTiesToEven); 13010 13011 if (ConversionStatus != llvm::APFloat::opOK) { 13012 SmallString<32> PrettySourceValue; 13013 SourceInt->toString(PrettySourceValue, 10); 13014 SmallString<32> PrettyTargetValue; 13015 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 13016 13017 S.DiagRuntimeBehavior( 13018 E->getExprLoc(), E, 13019 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 13020 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13021 << E->getSourceRange() << clang::SourceRange(CC)); 13022 } 13023 } else { 13024 // Otherwise, the implicit conversion may lose precision. 13025 DiagnoseImpCast(S, E, T, CC, 13026 diag::warn_impcast_integer_float_precision); 13027 } 13028 } 13029 } 13030 13031 DiagnoseNullConversion(S, E, T, CC); 13032 13033 S.DiscardMisalignedMemberAddress(Target, E); 13034 13035 if (Target->isBooleanType()) 13036 DiagnoseIntInBoolContext(S, E); 13037 13038 if (!Source->isIntegerType() || !Target->isIntegerType()) 13039 return; 13040 13041 // TODO: remove this early return once the false positives for constant->bool 13042 // in templates, macros, etc, are reduced or removed. 13043 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 13044 return; 13045 13046 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 13047 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 13048 return adornObjCBoolConversionDiagWithTernaryFixit( 13049 S, E, 13050 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 13051 << E->getType()); 13052 } 13053 13054 IntRange SourceTypeRange = 13055 IntRange::forTargetOfCanonicalType(S.Context, Source); 13056 IntRange LikelySourceRange = 13057 GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true); 13058 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 13059 13060 if (LikelySourceRange.Width > TargetRange.Width) { 13061 // If the source is a constant, use a default-on diagnostic. 13062 // TODO: this should happen for bitfield stores, too. 13063 Expr::EvalResult Result; 13064 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 13065 S.isConstantEvaluated())) { 13066 llvm::APSInt Value(32); 13067 Value = Result.Val.getInt(); 13068 13069 if (S.SourceMgr.isInSystemMacro(CC)) 13070 return; 13071 13072 std::string PrettySourceValue = toString(Value, 10); 13073 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13074 13075 S.DiagRuntimeBehavior( 13076 E->getExprLoc(), E, 13077 S.PDiag(diag::warn_impcast_integer_precision_constant) 13078 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13079 << E->getSourceRange() << SourceRange(CC)); 13080 return; 13081 } 13082 13083 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 13084 if (S.SourceMgr.isInSystemMacro(CC)) 13085 return; 13086 13087 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 13088 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 13089 /* pruneControlFlow */ true); 13090 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 13091 } 13092 13093 if (TargetRange.Width > SourceTypeRange.Width) { 13094 if (auto *UO = dyn_cast<UnaryOperator>(E)) 13095 if (UO->getOpcode() == UO_Minus) 13096 if (Source->isUnsignedIntegerType()) { 13097 if (Target->isUnsignedIntegerType()) 13098 return DiagnoseImpCast(S, E, T, CC, 13099 diag::warn_impcast_high_order_zero_bits); 13100 if (Target->isSignedIntegerType()) 13101 return DiagnoseImpCast(S, E, T, CC, 13102 diag::warn_impcast_nonnegative_result); 13103 } 13104 } 13105 13106 if (TargetRange.Width == LikelySourceRange.Width && 13107 !TargetRange.NonNegative && LikelySourceRange.NonNegative && 13108 Source->isSignedIntegerType()) { 13109 // Warn when doing a signed to signed conversion, warn if the positive 13110 // source value is exactly the width of the target type, which will 13111 // cause a negative value to be stored. 13112 13113 Expr::EvalResult Result; 13114 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 13115 !S.SourceMgr.isInSystemMacro(CC)) { 13116 llvm::APSInt Value = Result.Val.getInt(); 13117 if (isSameWidthConstantConversion(S, E, T, CC)) { 13118 std::string PrettySourceValue = toString(Value, 10); 13119 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 13120 13121 S.DiagRuntimeBehavior( 13122 E->getExprLoc(), E, 13123 S.PDiag(diag::warn_impcast_integer_precision_constant) 13124 << PrettySourceValue << PrettyTargetValue << E->getType() << T 13125 << E->getSourceRange() << SourceRange(CC)); 13126 return; 13127 } 13128 } 13129 13130 // Fall through for non-constants to give a sign conversion warning. 13131 } 13132 13133 if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) || 13134 (!TargetRange.NonNegative && LikelySourceRange.NonNegative && 13135 LikelySourceRange.Width == TargetRange.Width)) { 13136 if (S.SourceMgr.isInSystemMacro(CC)) 13137 return; 13138 13139 unsigned DiagID = diag::warn_impcast_integer_sign; 13140 13141 // Traditionally, gcc has warned about this under -Wsign-compare. 13142 // We also want to warn about it in -Wconversion. 13143 // So if -Wconversion is off, use a completely identical diagnostic 13144 // in the sign-compare group. 13145 // The conditional-checking code will 13146 if (ICContext) { 13147 DiagID = diag::warn_impcast_integer_sign_conditional; 13148 *ICContext = true; 13149 } 13150 13151 return DiagnoseImpCast(S, E, T, CC, DiagID); 13152 } 13153 13154 // Diagnose conversions between different enumeration types. 13155 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 13156 // type, to give us better diagnostics. 13157 QualType SourceType = E->getType(); 13158 if (!S.getLangOpts().CPlusPlus) { 13159 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13160 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 13161 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 13162 SourceType = S.Context.getTypeDeclType(Enum); 13163 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 13164 } 13165 } 13166 13167 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 13168 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 13169 if (SourceEnum->getDecl()->hasNameForLinkage() && 13170 TargetEnum->getDecl()->hasNameForLinkage() && 13171 SourceEnum != TargetEnum) { 13172 if (S.SourceMgr.isInSystemMacro(CC)) 13173 return; 13174 13175 return DiagnoseImpCast(S, E, SourceType, T, CC, 13176 diag::warn_impcast_different_enum_types); 13177 } 13178 } 13179 13180 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13181 SourceLocation CC, QualType T); 13182 13183 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 13184 SourceLocation CC, bool &ICContext) { 13185 E = E->IgnoreParenImpCasts(); 13186 13187 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 13188 return CheckConditionalOperator(S, CO, CC, T); 13189 13190 AnalyzeImplicitConversions(S, E, CC); 13191 if (E->getType() != T) 13192 return CheckImplicitConversion(S, E, T, CC, &ICContext); 13193 } 13194 13195 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 13196 SourceLocation CC, QualType T) { 13197 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 13198 13199 Expr *TrueExpr = E->getTrueExpr(); 13200 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 13201 TrueExpr = BCO->getCommon(); 13202 13203 bool Suspicious = false; 13204 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 13205 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 13206 13207 if (T->isBooleanType()) 13208 DiagnoseIntInBoolContext(S, E); 13209 13210 // If -Wconversion would have warned about either of the candidates 13211 // for a signedness conversion to the context type... 13212 if (!Suspicious) return; 13213 13214 // ...but it's currently ignored... 13215 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 13216 return; 13217 13218 // ...then check whether it would have warned about either of the 13219 // candidates for a signedness conversion to the condition type. 13220 if (E->getType() == T) return; 13221 13222 Suspicious = false; 13223 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 13224 E->getType(), CC, &Suspicious); 13225 if (!Suspicious) 13226 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 13227 E->getType(), CC, &Suspicious); 13228 } 13229 13230 /// Check conversion of given expression to boolean. 13231 /// Input argument E is a logical expression. 13232 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 13233 if (S.getLangOpts().Bool) 13234 return; 13235 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 13236 return; 13237 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 13238 } 13239 13240 namespace { 13241 struct AnalyzeImplicitConversionsWorkItem { 13242 Expr *E; 13243 SourceLocation CC; 13244 bool IsListInit; 13245 }; 13246 } 13247 13248 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 13249 /// that should be visited are added to WorkList. 13250 static void AnalyzeImplicitConversions( 13251 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 13252 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 13253 Expr *OrigE = Item.E; 13254 SourceLocation CC = Item.CC; 13255 13256 QualType T = OrigE->getType(); 13257 Expr *E = OrigE->IgnoreParenImpCasts(); 13258 13259 // Propagate whether we are in a C++ list initialization expression. 13260 // If so, we do not issue warnings for implicit int-float conversion 13261 // precision loss, because C++11 narrowing already handles it. 13262 bool IsListInit = Item.IsListInit || 13263 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 13264 13265 if (E->isTypeDependent() || E->isValueDependent()) 13266 return; 13267 13268 Expr *SourceExpr = E; 13269 // Examine, but don't traverse into the source expression of an 13270 // OpaqueValueExpr, since it may have multiple parents and we don't want to 13271 // emit duplicate diagnostics. Its fine to examine the form or attempt to 13272 // evaluate it in the context of checking the specific conversion to T though. 13273 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 13274 if (auto *Src = OVE->getSourceExpr()) 13275 SourceExpr = Src; 13276 13277 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 13278 if (UO->getOpcode() == UO_Not && 13279 UO->getSubExpr()->isKnownToHaveBooleanValue()) 13280 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 13281 << OrigE->getSourceRange() << T->isBooleanType() 13282 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 13283 13284 if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) 13285 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) && 13286 BO->getLHS()->isKnownToHaveBooleanValue() && 13287 BO->getRHS()->isKnownToHaveBooleanValue() && 13288 BO->getLHS()->HasSideEffects(S.Context) && 13289 BO->getRHS()->HasSideEffects(S.Context)) { 13290 S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical) 13291 << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange() 13292 << FixItHint::CreateReplacement( 13293 BO->getOperatorLoc(), 13294 (BO->getOpcode() == BO_And ? "&&" : "||")); 13295 S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int); 13296 } 13297 13298 // For conditional operators, we analyze the arguments as if they 13299 // were being fed directly into the output. 13300 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 13301 CheckConditionalOperator(S, CO, CC, T); 13302 return; 13303 } 13304 13305 // Check implicit argument conversions for function calls. 13306 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 13307 CheckImplicitArgumentConversions(S, Call, CC); 13308 13309 // Go ahead and check any implicit conversions we might have skipped. 13310 // The non-canonical typecheck is just an optimization; 13311 // CheckImplicitConversion will filter out dead implicit conversions. 13312 if (SourceExpr->getType() != T) 13313 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 13314 13315 // Now continue drilling into this expression. 13316 13317 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 13318 // The bound subexpressions in a PseudoObjectExpr are not reachable 13319 // as transitive children. 13320 // FIXME: Use a more uniform representation for this. 13321 for (auto *SE : POE->semantics()) 13322 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 13323 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 13324 } 13325 13326 // Skip past explicit casts. 13327 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 13328 E = CE->getSubExpr()->IgnoreParenImpCasts(); 13329 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 13330 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 13331 WorkList.push_back({E, CC, IsListInit}); 13332 return; 13333 } 13334 13335 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13336 // Do a somewhat different check with comparison operators. 13337 if (BO->isComparisonOp()) 13338 return AnalyzeComparison(S, BO); 13339 13340 // And with simple assignments. 13341 if (BO->getOpcode() == BO_Assign) 13342 return AnalyzeAssignment(S, BO); 13343 // And with compound assignments. 13344 if (BO->isAssignmentOp()) 13345 return AnalyzeCompoundAssignment(S, BO); 13346 } 13347 13348 // These break the otherwise-useful invariant below. Fortunately, 13349 // we don't really need to recurse into them, because any internal 13350 // expressions should have been analyzed already when they were 13351 // built into statements. 13352 if (isa<StmtExpr>(E)) return; 13353 13354 // Don't descend into unevaluated contexts. 13355 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 13356 13357 // Now just recurse over the expression's children. 13358 CC = E->getExprLoc(); 13359 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 13360 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 13361 for (Stmt *SubStmt : E->children()) { 13362 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 13363 if (!ChildExpr) 13364 continue; 13365 13366 if (IsLogicalAndOperator && 13367 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 13368 // Ignore checking string literals that are in logical and operators. 13369 // This is a common pattern for asserts. 13370 continue; 13371 WorkList.push_back({ChildExpr, CC, IsListInit}); 13372 } 13373 13374 if (BO && BO->isLogicalOp()) { 13375 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 13376 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13377 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13378 13379 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 13380 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 13381 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 13382 } 13383 13384 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 13385 if (U->getOpcode() == UO_LNot) { 13386 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 13387 } else if (U->getOpcode() != UO_AddrOf) { 13388 if (U->getSubExpr()->getType()->isAtomicType()) 13389 S.Diag(U->getSubExpr()->getBeginLoc(), 13390 diag::warn_atomic_implicit_seq_cst); 13391 } 13392 } 13393 } 13394 13395 /// AnalyzeImplicitConversions - Find and report any interesting 13396 /// implicit conversions in the given expression. There are a couple 13397 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 13398 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 13399 bool IsListInit/*= false*/) { 13400 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 13401 WorkList.push_back({OrigE, CC, IsListInit}); 13402 while (!WorkList.empty()) 13403 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 13404 } 13405 13406 /// Diagnose integer type and any valid implicit conversion to it. 13407 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 13408 // Taking into account implicit conversions, 13409 // allow any integer. 13410 if (!E->getType()->isIntegerType()) { 13411 S.Diag(E->getBeginLoc(), 13412 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 13413 return true; 13414 } 13415 // Potentially emit standard warnings for implicit conversions if enabled 13416 // using -Wconversion. 13417 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 13418 return false; 13419 } 13420 13421 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 13422 // Returns true when emitting a warning about taking the address of a reference. 13423 static bool CheckForReference(Sema &SemaRef, const Expr *E, 13424 const PartialDiagnostic &PD) { 13425 E = E->IgnoreParenImpCasts(); 13426 13427 const FunctionDecl *FD = nullptr; 13428 13429 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 13430 if (!DRE->getDecl()->getType()->isReferenceType()) 13431 return false; 13432 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13433 if (!M->getMemberDecl()->getType()->isReferenceType()) 13434 return false; 13435 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 13436 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 13437 return false; 13438 FD = Call->getDirectCallee(); 13439 } else { 13440 return false; 13441 } 13442 13443 SemaRef.Diag(E->getExprLoc(), PD); 13444 13445 // If possible, point to location of function. 13446 if (FD) { 13447 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 13448 } 13449 13450 return true; 13451 } 13452 13453 // Returns true if the SourceLocation is expanded from any macro body. 13454 // Returns false if the SourceLocation is invalid, is from not in a macro 13455 // expansion, or is from expanded from a top-level macro argument. 13456 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 13457 if (Loc.isInvalid()) 13458 return false; 13459 13460 while (Loc.isMacroID()) { 13461 if (SM.isMacroBodyExpansion(Loc)) 13462 return true; 13463 Loc = SM.getImmediateMacroCallerLoc(Loc); 13464 } 13465 13466 return false; 13467 } 13468 13469 /// Diagnose pointers that are always non-null. 13470 /// \param E the expression containing the pointer 13471 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 13472 /// compared to a null pointer 13473 /// \param IsEqual True when the comparison is equal to a null pointer 13474 /// \param Range Extra SourceRange to highlight in the diagnostic 13475 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 13476 Expr::NullPointerConstantKind NullKind, 13477 bool IsEqual, SourceRange Range) { 13478 if (!E) 13479 return; 13480 13481 // Don't warn inside macros. 13482 if (E->getExprLoc().isMacroID()) { 13483 const SourceManager &SM = getSourceManager(); 13484 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 13485 IsInAnyMacroBody(SM, Range.getBegin())) 13486 return; 13487 } 13488 E = E->IgnoreImpCasts(); 13489 13490 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 13491 13492 if (isa<CXXThisExpr>(E)) { 13493 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 13494 : diag::warn_this_bool_conversion; 13495 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 13496 return; 13497 } 13498 13499 bool IsAddressOf = false; 13500 13501 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13502 if (UO->getOpcode() != UO_AddrOf) 13503 return; 13504 IsAddressOf = true; 13505 E = UO->getSubExpr(); 13506 } 13507 13508 if (IsAddressOf) { 13509 unsigned DiagID = IsCompare 13510 ? diag::warn_address_of_reference_null_compare 13511 : diag::warn_address_of_reference_bool_conversion; 13512 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 13513 << IsEqual; 13514 if (CheckForReference(*this, E, PD)) { 13515 return; 13516 } 13517 } 13518 13519 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 13520 bool IsParam = isa<NonNullAttr>(NonnullAttr); 13521 std::string Str; 13522 llvm::raw_string_ostream S(Str); 13523 E->printPretty(S, nullptr, getPrintingPolicy()); 13524 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 13525 : diag::warn_cast_nonnull_to_bool; 13526 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 13527 << E->getSourceRange() << Range << IsEqual; 13528 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 13529 }; 13530 13531 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 13532 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 13533 if (auto *Callee = Call->getDirectCallee()) { 13534 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 13535 ComplainAboutNonnullParamOrCall(A); 13536 return; 13537 } 13538 } 13539 } 13540 13541 // Expect to find a single Decl. Skip anything more complicated. 13542 ValueDecl *D = nullptr; 13543 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 13544 D = R->getDecl(); 13545 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 13546 D = M->getMemberDecl(); 13547 } 13548 13549 // Weak Decls can be null. 13550 if (!D || D->isWeak()) 13551 return; 13552 13553 // Check for parameter decl with nonnull attribute 13554 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 13555 if (getCurFunction() && 13556 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 13557 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 13558 ComplainAboutNonnullParamOrCall(A); 13559 return; 13560 } 13561 13562 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 13563 // Skip function template not specialized yet. 13564 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 13565 return; 13566 auto ParamIter = llvm::find(FD->parameters(), PV); 13567 assert(ParamIter != FD->param_end()); 13568 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 13569 13570 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 13571 if (!NonNull->args_size()) { 13572 ComplainAboutNonnullParamOrCall(NonNull); 13573 return; 13574 } 13575 13576 for (const ParamIdx &ArgNo : NonNull->args()) { 13577 if (ArgNo.getASTIndex() == ParamNo) { 13578 ComplainAboutNonnullParamOrCall(NonNull); 13579 return; 13580 } 13581 } 13582 } 13583 } 13584 } 13585 } 13586 13587 QualType T = D->getType(); 13588 const bool IsArray = T->isArrayType(); 13589 const bool IsFunction = T->isFunctionType(); 13590 13591 // Address of function is used to silence the function warning. 13592 if (IsAddressOf && IsFunction) { 13593 return; 13594 } 13595 13596 // Found nothing. 13597 if (!IsAddressOf && !IsFunction && !IsArray) 13598 return; 13599 13600 // Pretty print the expression for the diagnostic. 13601 std::string Str; 13602 llvm::raw_string_ostream S(Str); 13603 E->printPretty(S, nullptr, getPrintingPolicy()); 13604 13605 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 13606 : diag::warn_impcast_pointer_to_bool; 13607 enum { 13608 AddressOf, 13609 FunctionPointer, 13610 ArrayPointer 13611 } DiagType; 13612 if (IsAddressOf) 13613 DiagType = AddressOf; 13614 else if (IsFunction) 13615 DiagType = FunctionPointer; 13616 else if (IsArray) 13617 DiagType = ArrayPointer; 13618 else 13619 llvm_unreachable("Could not determine diagnostic."); 13620 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 13621 << Range << IsEqual; 13622 13623 if (!IsFunction) 13624 return; 13625 13626 // Suggest '&' to silence the function warning. 13627 Diag(E->getExprLoc(), diag::note_function_warning_silence) 13628 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 13629 13630 // Check to see if '()' fixit should be emitted. 13631 QualType ReturnType; 13632 UnresolvedSet<4> NonTemplateOverloads; 13633 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 13634 if (ReturnType.isNull()) 13635 return; 13636 13637 if (IsCompare) { 13638 // There are two cases here. If there is null constant, the only suggest 13639 // for a pointer return type. If the null is 0, then suggest if the return 13640 // type is a pointer or an integer type. 13641 if (!ReturnType->isPointerType()) { 13642 if (NullKind == Expr::NPCK_ZeroExpression || 13643 NullKind == Expr::NPCK_ZeroLiteral) { 13644 if (!ReturnType->isIntegerType()) 13645 return; 13646 } else { 13647 return; 13648 } 13649 } 13650 } else { // !IsCompare 13651 // For function to bool, only suggest if the function pointer has bool 13652 // return type. 13653 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 13654 return; 13655 } 13656 Diag(E->getExprLoc(), diag::note_function_to_function_call) 13657 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 13658 } 13659 13660 /// Diagnoses "dangerous" implicit conversions within the given 13661 /// expression (which is a full expression). Implements -Wconversion 13662 /// and -Wsign-compare. 13663 /// 13664 /// \param CC the "context" location of the implicit conversion, i.e. 13665 /// the most location of the syntactic entity requiring the implicit 13666 /// conversion 13667 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 13668 // Don't diagnose in unevaluated contexts. 13669 if (isUnevaluatedContext()) 13670 return; 13671 13672 // Don't diagnose for value- or type-dependent expressions. 13673 if (E->isTypeDependent() || E->isValueDependent()) 13674 return; 13675 13676 // Check for array bounds violations in cases where the check isn't triggered 13677 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 13678 // ArraySubscriptExpr is on the RHS of a variable initialization. 13679 CheckArrayAccess(E); 13680 13681 // This is not the right CC for (e.g.) a variable initialization. 13682 AnalyzeImplicitConversions(*this, E, CC); 13683 } 13684 13685 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 13686 /// Input argument E is a logical expression. 13687 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 13688 ::CheckBoolLikeConversion(*this, E, CC); 13689 } 13690 13691 /// Diagnose when expression is an integer constant expression and its evaluation 13692 /// results in integer overflow 13693 void Sema::CheckForIntOverflow (Expr *E) { 13694 // Use a work list to deal with nested struct initializers. 13695 SmallVector<Expr *, 2> Exprs(1, E); 13696 13697 do { 13698 Expr *OriginalE = Exprs.pop_back_val(); 13699 Expr *E = OriginalE->IgnoreParenCasts(); 13700 13701 if (isa<BinaryOperator>(E)) { 13702 E->EvaluateForOverflow(Context); 13703 continue; 13704 } 13705 13706 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 13707 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 13708 else if (isa<ObjCBoxedExpr>(OriginalE)) 13709 E->EvaluateForOverflow(Context); 13710 else if (auto Call = dyn_cast<CallExpr>(E)) 13711 Exprs.append(Call->arg_begin(), Call->arg_end()); 13712 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 13713 Exprs.append(Message->arg_begin(), Message->arg_end()); 13714 } while (!Exprs.empty()); 13715 } 13716 13717 namespace { 13718 13719 /// Visitor for expressions which looks for unsequenced operations on the 13720 /// same object. 13721 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 13722 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 13723 13724 /// A tree of sequenced regions within an expression. Two regions are 13725 /// unsequenced if one is an ancestor or a descendent of the other. When we 13726 /// finish processing an expression with sequencing, such as a comma 13727 /// expression, we fold its tree nodes into its parent, since they are 13728 /// unsequenced with respect to nodes we will visit later. 13729 class SequenceTree { 13730 struct Value { 13731 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 13732 unsigned Parent : 31; 13733 unsigned Merged : 1; 13734 }; 13735 SmallVector<Value, 8> Values; 13736 13737 public: 13738 /// A region within an expression which may be sequenced with respect 13739 /// to some other region. 13740 class Seq { 13741 friend class SequenceTree; 13742 13743 unsigned Index; 13744 13745 explicit Seq(unsigned N) : Index(N) {} 13746 13747 public: 13748 Seq() : Index(0) {} 13749 }; 13750 13751 SequenceTree() { Values.push_back(Value(0)); } 13752 Seq root() const { return Seq(0); } 13753 13754 /// Create a new sequence of operations, which is an unsequenced 13755 /// subset of \p Parent. This sequence of operations is sequenced with 13756 /// respect to other children of \p Parent. 13757 Seq allocate(Seq Parent) { 13758 Values.push_back(Value(Parent.Index)); 13759 return Seq(Values.size() - 1); 13760 } 13761 13762 /// Merge a sequence of operations into its parent. 13763 void merge(Seq S) { 13764 Values[S.Index].Merged = true; 13765 } 13766 13767 /// Determine whether two operations are unsequenced. This operation 13768 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 13769 /// should have been merged into its parent as appropriate. 13770 bool isUnsequenced(Seq Cur, Seq Old) { 13771 unsigned C = representative(Cur.Index); 13772 unsigned Target = representative(Old.Index); 13773 while (C >= Target) { 13774 if (C == Target) 13775 return true; 13776 C = Values[C].Parent; 13777 } 13778 return false; 13779 } 13780 13781 private: 13782 /// Pick a representative for a sequence. 13783 unsigned representative(unsigned K) { 13784 if (Values[K].Merged) 13785 // Perform path compression as we go. 13786 return Values[K].Parent = representative(Values[K].Parent); 13787 return K; 13788 } 13789 }; 13790 13791 /// An object for which we can track unsequenced uses. 13792 using Object = const NamedDecl *; 13793 13794 /// Different flavors of object usage which we track. We only track the 13795 /// least-sequenced usage of each kind. 13796 enum UsageKind { 13797 /// A read of an object. Multiple unsequenced reads are OK. 13798 UK_Use, 13799 13800 /// A modification of an object which is sequenced before the value 13801 /// computation of the expression, such as ++n in C++. 13802 UK_ModAsValue, 13803 13804 /// A modification of an object which is not sequenced before the value 13805 /// computation of the expression, such as n++. 13806 UK_ModAsSideEffect, 13807 13808 UK_Count = UK_ModAsSideEffect + 1 13809 }; 13810 13811 /// Bundle together a sequencing region and the expression corresponding 13812 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 13813 struct Usage { 13814 const Expr *UsageExpr; 13815 SequenceTree::Seq Seq; 13816 13817 Usage() : UsageExpr(nullptr), Seq() {} 13818 }; 13819 13820 struct UsageInfo { 13821 Usage Uses[UK_Count]; 13822 13823 /// Have we issued a diagnostic for this object already? 13824 bool Diagnosed; 13825 13826 UsageInfo() : Uses(), Diagnosed(false) {} 13827 }; 13828 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 13829 13830 Sema &SemaRef; 13831 13832 /// Sequenced regions within the expression. 13833 SequenceTree Tree; 13834 13835 /// Declaration modifications and references which we have seen. 13836 UsageInfoMap UsageMap; 13837 13838 /// The region we are currently within. 13839 SequenceTree::Seq Region; 13840 13841 /// Filled in with declarations which were modified as a side-effect 13842 /// (that is, post-increment operations). 13843 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 13844 13845 /// Expressions to check later. We defer checking these to reduce 13846 /// stack usage. 13847 SmallVectorImpl<const Expr *> &WorkList; 13848 13849 /// RAII object wrapping the visitation of a sequenced subexpression of an 13850 /// expression. At the end of this process, the side-effects of the evaluation 13851 /// become sequenced with respect to the value computation of the result, so 13852 /// we downgrade any UK_ModAsSideEffect within the evaluation to 13853 /// UK_ModAsValue. 13854 struct SequencedSubexpression { 13855 SequencedSubexpression(SequenceChecker &Self) 13856 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 13857 Self.ModAsSideEffect = &ModAsSideEffect; 13858 } 13859 13860 ~SequencedSubexpression() { 13861 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 13862 // Add a new usage with usage kind UK_ModAsValue, and then restore 13863 // the previous usage with UK_ModAsSideEffect (thus clearing it if 13864 // the previous one was empty). 13865 UsageInfo &UI = Self.UsageMap[M.first]; 13866 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 13867 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 13868 SideEffectUsage = M.second; 13869 } 13870 Self.ModAsSideEffect = OldModAsSideEffect; 13871 } 13872 13873 SequenceChecker &Self; 13874 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 13875 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 13876 }; 13877 13878 /// RAII object wrapping the visitation of a subexpression which we might 13879 /// choose to evaluate as a constant. If any subexpression is evaluated and 13880 /// found to be non-constant, this allows us to suppress the evaluation of 13881 /// the outer expression. 13882 class EvaluationTracker { 13883 public: 13884 EvaluationTracker(SequenceChecker &Self) 13885 : Self(Self), Prev(Self.EvalTracker) { 13886 Self.EvalTracker = this; 13887 } 13888 13889 ~EvaluationTracker() { 13890 Self.EvalTracker = Prev; 13891 if (Prev) 13892 Prev->EvalOK &= EvalOK; 13893 } 13894 13895 bool evaluate(const Expr *E, bool &Result) { 13896 if (!EvalOK || E->isValueDependent()) 13897 return false; 13898 EvalOK = E->EvaluateAsBooleanCondition( 13899 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 13900 return EvalOK; 13901 } 13902 13903 private: 13904 SequenceChecker &Self; 13905 EvaluationTracker *Prev; 13906 bool EvalOK = true; 13907 } *EvalTracker = nullptr; 13908 13909 /// Find the object which is produced by the specified expression, 13910 /// if any. 13911 Object getObject(const Expr *E, bool Mod) const { 13912 E = E->IgnoreParenCasts(); 13913 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 13914 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 13915 return getObject(UO->getSubExpr(), Mod); 13916 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 13917 if (BO->getOpcode() == BO_Comma) 13918 return getObject(BO->getRHS(), Mod); 13919 if (Mod && BO->isAssignmentOp()) 13920 return getObject(BO->getLHS(), Mod); 13921 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 13922 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 13923 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 13924 return ME->getMemberDecl(); 13925 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 13926 // FIXME: If this is a reference, map through to its value. 13927 return DRE->getDecl(); 13928 return nullptr; 13929 } 13930 13931 /// Note that an object \p O was modified or used by an expression 13932 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 13933 /// the object \p O as obtained via the \p UsageMap. 13934 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 13935 // Get the old usage for the given object and usage kind. 13936 Usage &U = UI.Uses[UK]; 13937 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 13938 // If we have a modification as side effect and are in a sequenced 13939 // subexpression, save the old Usage so that we can restore it later 13940 // in SequencedSubexpression::~SequencedSubexpression. 13941 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 13942 ModAsSideEffect->push_back(std::make_pair(O, U)); 13943 // Then record the new usage with the current sequencing region. 13944 U.UsageExpr = UsageExpr; 13945 U.Seq = Region; 13946 } 13947 } 13948 13949 /// Check whether a modification or use of an object \p O in an expression 13950 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 13951 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 13952 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 13953 /// usage and false we are checking for a mod-use unsequenced usage. 13954 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 13955 UsageKind OtherKind, bool IsModMod) { 13956 if (UI.Diagnosed) 13957 return; 13958 13959 const Usage &U = UI.Uses[OtherKind]; 13960 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 13961 return; 13962 13963 const Expr *Mod = U.UsageExpr; 13964 const Expr *ModOrUse = UsageExpr; 13965 if (OtherKind == UK_Use) 13966 std::swap(Mod, ModOrUse); 13967 13968 SemaRef.DiagRuntimeBehavior( 13969 Mod->getExprLoc(), {Mod, ModOrUse}, 13970 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 13971 : diag::warn_unsequenced_mod_use) 13972 << O << SourceRange(ModOrUse->getExprLoc())); 13973 UI.Diagnosed = true; 13974 } 13975 13976 // A note on note{Pre, Post}{Use, Mod}: 13977 // 13978 // (It helps to follow the algorithm with an expression such as 13979 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 13980 // operations before C++17 and both are well-defined in C++17). 13981 // 13982 // When visiting a node which uses/modify an object we first call notePreUse 13983 // or notePreMod before visiting its sub-expression(s). At this point the 13984 // children of the current node have not yet been visited and so the eventual 13985 // uses/modifications resulting from the children of the current node have not 13986 // been recorded yet. 13987 // 13988 // We then visit the children of the current node. After that notePostUse or 13989 // notePostMod is called. These will 1) detect an unsequenced modification 13990 // as side effect (as in "k++ + k") and 2) add a new usage with the 13991 // appropriate usage kind. 13992 // 13993 // We also have to be careful that some operation sequences modification as 13994 // side effect as well (for example: || or ,). To account for this we wrap 13995 // the visitation of such a sub-expression (for example: the LHS of || or ,) 13996 // with SequencedSubexpression. SequencedSubexpression is an RAII object 13997 // which record usages which are modifications as side effect, and then 13998 // downgrade them (or more accurately restore the previous usage which was a 13999 // modification as side effect) when exiting the scope of the sequenced 14000 // subexpression. 14001 14002 void notePreUse(Object O, const Expr *UseExpr) { 14003 UsageInfo &UI = UsageMap[O]; 14004 // Uses conflict with other modifications. 14005 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 14006 } 14007 14008 void notePostUse(Object O, const Expr *UseExpr) { 14009 UsageInfo &UI = UsageMap[O]; 14010 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 14011 /*IsModMod=*/false); 14012 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 14013 } 14014 14015 void notePreMod(Object O, const Expr *ModExpr) { 14016 UsageInfo &UI = UsageMap[O]; 14017 // Modifications conflict with other modifications and with uses. 14018 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 14019 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 14020 } 14021 14022 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 14023 UsageInfo &UI = UsageMap[O]; 14024 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 14025 /*IsModMod=*/true); 14026 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 14027 } 14028 14029 public: 14030 SequenceChecker(Sema &S, const Expr *E, 14031 SmallVectorImpl<const Expr *> &WorkList) 14032 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 14033 Visit(E); 14034 // Silence a -Wunused-private-field since WorkList is now unused. 14035 // TODO: Evaluate if it can be used, and if not remove it. 14036 (void)this->WorkList; 14037 } 14038 14039 void VisitStmt(const Stmt *S) { 14040 // Skip all statements which aren't expressions for now. 14041 } 14042 14043 void VisitExpr(const Expr *E) { 14044 // By default, just recurse to evaluated subexpressions. 14045 Base::VisitStmt(E); 14046 } 14047 14048 void VisitCastExpr(const CastExpr *E) { 14049 Object O = Object(); 14050 if (E->getCastKind() == CK_LValueToRValue) 14051 O = getObject(E->getSubExpr(), false); 14052 14053 if (O) 14054 notePreUse(O, E); 14055 VisitExpr(E); 14056 if (O) 14057 notePostUse(O, E); 14058 } 14059 14060 void VisitSequencedExpressions(const Expr *SequencedBefore, 14061 const Expr *SequencedAfter) { 14062 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 14063 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 14064 SequenceTree::Seq OldRegion = Region; 14065 14066 { 14067 SequencedSubexpression SeqBefore(*this); 14068 Region = BeforeRegion; 14069 Visit(SequencedBefore); 14070 } 14071 14072 Region = AfterRegion; 14073 Visit(SequencedAfter); 14074 14075 Region = OldRegion; 14076 14077 Tree.merge(BeforeRegion); 14078 Tree.merge(AfterRegion); 14079 } 14080 14081 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 14082 // C++17 [expr.sub]p1: 14083 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 14084 // expression E1 is sequenced before the expression E2. 14085 if (SemaRef.getLangOpts().CPlusPlus17) 14086 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 14087 else { 14088 Visit(ASE->getLHS()); 14089 Visit(ASE->getRHS()); 14090 } 14091 } 14092 14093 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14094 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 14095 void VisitBinPtrMem(const BinaryOperator *BO) { 14096 // C++17 [expr.mptr.oper]p4: 14097 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 14098 // the expression E1 is sequenced before the expression E2. 14099 if (SemaRef.getLangOpts().CPlusPlus17) 14100 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14101 else { 14102 Visit(BO->getLHS()); 14103 Visit(BO->getRHS()); 14104 } 14105 } 14106 14107 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14108 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 14109 void VisitBinShlShr(const BinaryOperator *BO) { 14110 // C++17 [expr.shift]p4: 14111 // The expression E1 is sequenced before the expression E2. 14112 if (SemaRef.getLangOpts().CPlusPlus17) 14113 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14114 else { 14115 Visit(BO->getLHS()); 14116 Visit(BO->getRHS()); 14117 } 14118 } 14119 14120 void VisitBinComma(const BinaryOperator *BO) { 14121 // C++11 [expr.comma]p1: 14122 // Every value computation and side effect associated with the left 14123 // expression is sequenced before every value computation and side 14124 // effect associated with the right expression. 14125 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 14126 } 14127 14128 void VisitBinAssign(const BinaryOperator *BO) { 14129 SequenceTree::Seq RHSRegion; 14130 SequenceTree::Seq LHSRegion; 14131 if (SemaRef.getLangOpts().CPlusPlus17) { 14132 RHSRegion = Tree.allocate(Region); 14133 LHSRegion = Tree.allocate(Region); 14134 } else { 14135 RHSRegion = Region; 14136 LHSRegion = Region; 14137 } 14138 SequenceTree::Seq OldRegion = Region; 14139 14140 // C++11 [expr.ass]p1: 14141 // [...] the assignment is sequenced after the value computation 14142 // of the right and left operands, [...] 14143 // 14144 // so check it before inspecting the operands and update the 14145 // map afterwards. 14146 Object O = getObject(BO->getLHS(), /*Mod=*/true); 14147 if (O) 14148 notePreMod(O, BO); 14149 14150 if (SemaRef.getLangOpts().CPlusPlus17) { 14151 // C++17 [expr.ass]p1: 14152 // [...] The right operand is sequenced before the left operand. [...] 14153 { 14154 SequencedSubexpression SeqBefore(*this); 14155 Region = RHSRegion; 14156 Visit(BO->getRHS()); 14157 } 14158 14159 Region = LHSRegion; 14160 Visit(BO->getLHS()); 14161 14162 if (O && isa<CompoundAssignOperator>(BO)) 14163 notePostUse(O, BO); 14164 14165 } else { 14166 // C++11 does not specify any sequencing between the LHS and RHS. 14167 Region = LHSRegion; 14168 Visit(BO->getLHS()); 14169 14170 if (O && isa<CompoundAssignOperator>(BO)) 14171 notePostUse(O, BO); 14172 14173 Region = RHSRegion; 14174 Visit(BO->getRHS()); 14175 } 14176 14177 // C++11 [expr.ass]p1: 14178 // the assignment is sequenced [...] before the value computation of the 14179 // assignment expression. 14180 // C11 6.5.16/3 has no such rule. 14181 Region = OldRegion; 14182 if (O) 14183 notePostMod(O, BO, 14184 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14185 : UK_ModAsSideEffect); 14186 if (SemaRef.getLangOpts().CPlusPlus17) { 14187 Tree.merge(RHSRegion); 14188 Tree.merge(LHSRegion); 14189 } 14190 } 14191 14192 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 14193 VisitBinAssign(CAO); 14194 } 14195 14196 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14197 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 14198 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 14199 Object O = getObject(UO->getSubExpr(), true); 14200 if (!O) 14201 return VisitExpr(UO); 14202 14203 notePreMod(O, UO); 14204 Visit(UO->getSubExpr()); 14205 // C++11 [expr.pre.incr]p1: 14206 // the expression ++x is equivalent to x+=1 14207 notePostMod(O, UO, 14208 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 14209 : UK_ModAsSideEffect); 14210 } 14211 14212 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14213 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 14214 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 14215 Object O = getObject(UO->getSubExpr(), true); 14216 if (!O) 14217 return VisitExpr(UO); 14218 14219 notePreMod(O, UO); 14220 Visit(UO->getSubExpr()); 14221 notePostMod(O, UO, UK_ModAsSideEffect); 14222 } 14223 14224 void VisitBinLOr(const BinaryOperator *BO) { 14225 // C++11 [expr.log.or]p2: 14226 // If the second expression is evaluated, every value computation and 14227 // side effect associated with the first expression is sequenced before 14228 // every value computation and side effect associated with the 14229 // second expression. 14230 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14231 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14232 SequenceTree::Seq OldRegion = Region; 14233 14234 EvaluationTracker Eval(*this); 14235 { 14236 SequencedSubexpression Sequenced(*this); 14237 Region = LHSRegion; 14238 Visit(BO->getLHS()); 14239 } 14240 14241 // C++11 [expr.log.or]p1: 14242 // [...] the second operand is not evaluated if the first operand 14243 // evaluates to true. 14244 bool EvalResult = false; 14245 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14246 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 14247 if (ShouldVisitRHS) { 14248 Region = RHSRegion; 14249 Visit(BO->getRHS()); 14250 } 14251 14252 Region = OldRegion; 14253 Tree.merge(LHSRegion); 14254 Tree.merge(RHSRegion); 14255 } 14256 14257 void VisitBinLAnd(const BinaryOperator *BO) { 14258 // C++11 [expr.log.and]p2: 14259 // If the second expression is evaluated, every value computation and 14260 // side effect associated with the first expression is sequenced before 14261 // every value computation and side effect associated with the 14262 // second expression. 14263 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 14264 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 14265 SequenceTree::Seq OldRegion = Region; 14266 14267 EvaluationTracker Eval(*this); 14268 { 14269 SequencedSubexpression Sequenced(*this); 14270 Region = LHSRegion; 14271 Visit(BO->getLHS()); 14272 } 14273 14274 // C++11 [expr.log.and]p1: 14275 // [...] the second operand is not evaluated if the first operand is false. 14276 bool EvalResult = false; 14277 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 14278 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 14279 if (ShouldVisitRHS) { 14280 Region = RHSRegion; 14281 Visit(BO->getRHS()); 14282 } 14283 14284 Region = OldRegion; 14285 Tree.merge(LHSRegion); 14286 Tree.merge(RHSRegion); 14287 } 14288 14289 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 14290 // C++11 [expr.cond]p1: 14291 // [...] Every value computation and side effect associated with the first 14292 // expression is sequenced before every value computation and side effect 14293 // associated with the second or third expression. 14294 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 14295 14296 // No sequencing is specified between the true and false expression. 14297 // However since exactly one of both is going to be evaluated we can 14298 // consider them to be sequenced. This is needed to avoid warning on 14299 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 14300 // both the true and false expressions because we can't evaluate x. 14301 // This will still allow us to detect an expression like (pre C++17) 14302 // "(x ? y += 1 : y += 2) = y". 14303 // 14304 // We don't wrap the visitation of the true and false expression with 14305 // SequencedSubexpression because we don't want to downgrade modifications 14306 // as side effect in the true and false expressions after the visition 14307 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 14308 // not warn between the two "y++", but we should warn between the "y++" 14309 // and the "y". 14310 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 14311 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 14312 SequenceTree::Seq OldRegion = Region; 14313 14314 EvaluationTracker Eval(*this); 14315 { 14316 SequencedSubexpression Sequenced(*this); 14317 Region = ConditionRegion; 14318 Visit(CO->getCond()); 14319 } 14320 14321 // C++11 [expr.cond]p1: 14322 // [...] The first expression is contextually converted to bool (Clause 4). 14323 // It is evaluated and if it is true, the result of the conditional 14324 // expression is the value of the second expression, otherwise that of the 14325 // third expression. Only one of the second and third expressions is 14326 // evaluated. [...] 14327 bool EvalResult = false; 14328 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 14329 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 14330 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 14331 if (ShouldVisitTrueExpr) { 14332 Region = TrueRegion; 14333 Visit(CO->getTrueExpr()); 14334 } 14335 if (ShouldVisitFalseExpr) { 14336 Region = FalseRegion; 14337 Visit(CO->getFalseExpr()); 14338 } 14339 14340 Region = OldRegion; 14341 Tree.merge(ConditionRegion); 14342 Tree.merge(TrueRegion); 14343 Tree.merge(FalseRegion); 14344 } 14345 14346 void VisitCallExpr(const CallExpr *CE) { 14347 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 14348 14349 if (CE->isUnevaluatedBuiltinCall(Context)) 14350 return; 14351 14352 // C++11 [intro.execution]p15: 14353 // When calling a function [...], every value computation and side effect 14354 // associated with any argument expression, or with the postfix expression 14355 // designating the called function, is sequenced before execution of every 14356 // expression or statement in the body of the function [and thus before 14357 // the value computation of its result]. 14358 SequencedSubexpression Sequenced(*this); 14359 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 14360 // C++17 [expr.call]p5 14361 // The postfix-expression is sequenced before each expression in the 14362 // expression-list and any default argument. [...] 14363 SequenceTree::Seq CalleeRegion; 14364 SequenceTree::Seq OtherRegion; 14365 if (SemaRef.getLangOpts().CPlusPlus17) { 14366 CalleeRegion = Tree.allocate(Region); 14367 OtherRegion = Tree.allocate(Region); 14368 } else { 14369 CalleeRegion = Region; 14370 OtherRegion = Region; 14371 } 14372 SequenceTree::Seq OldRegion = Region; 14373 14374 // Visit the callee expression first. 14375 Region = CalleeRegion; 14376 if (SemaRef.getLangOpts().CPlusPlus17) { 14377 SequencedSubexpression Sequenced(*this); 14378 Visit(CE->getCallee()); 14379 } else { 14380 Visit(CE->getCallee()); 14381 } 14382 14383 // Then visit the argument expressions. 14384 Region = OtherRegion; 14385 for (const Expr *Argument : CE->arguments()) 14386 Visit(Argument); 14387 14388 Region = OldRegion; 14389 if (SemaRef.getLangOpts().CPlusPlus17) { 14390 Tree.merge(CalleeRegion); 14391 Tree.merge(OtherRegion); 14392 } 14393 }); 14394 } 14395 14396 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 14397 // C++17 [over.match.oper]p2: 14398 // [...] the operator notation is first transformed to the equivalent 14399 // function-call notation as summarized in Table 12 (where @ denotes one 14400 // of the operators covered in the specified subclause). However, the 14401 // operands are sequenced in the order prescribed for the built-in 14402 // operator (Clause 8). 14403 // 14404 // From the above only overloaded binary operators and overloaded call 14405 // operators have sequencing rules in C++17 that we need to handle 14406 // separately. 14407 if (!SemaRef.getLangOpts().CPlusPlus17 || 14408 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 14409 return VisitCallExpr(CXXOCE); 14410 14411 enum { 14412 NoSequencing, 14413 LHSBeforeRHS, 14414 RHSBeforeLHS, 14415 LHSBeforeRest 14416 } SequencingKind; 14417 switch (CXXOCE->getOperator()) { 14418 case OO_Equal: 14419 case OO_PlusEqual: 14420 case OO_MinusEqual: 14421 case OO_StarEqual: 14422 case OO_SlashEqual: 14423 case OO_PercentEqual: 14424 case OO_CaretEqual: 14425 case OO_AmpEqual: 14426 case OO_PipeEqual: 14427 case OO_LessLessEqual: 14428 case OO_GreaterGreaterEqual: 14429 SequencingKind = RHSBeforeLHS; 14430 break; 14431 14432 case OO_LessLess: 14433 case OO_GreaterGreater: 14434 case OO_AmpAmp: 14435 case OO_PipePipe: 14436 case OO_Comma: 14437 case OO_ArrowStar: 14438 case OO_Subscript: 14439 SequencingKind = LHSBeforeRHS; 14440 break; 14441 14442 case OO_Call: 14443 SequencingKind = LHSBeforeRest; 14444 break; 14445 14446 default: 14447 SequencingKind = NoSequencing; 14448 break; 14449 } 14450 14451 if (SequencingKind == NoSequencing) 14452 return VisitCallExpr(CXXOCE); 14453 14454 // This is a call, so all subexpressions are sequenced before the result. 14455 SequencedSubexpression Sequenced(*this); 14456 14457 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 14458 assert(SemaRef.getLangOpts().CPlusPlus17 && 14459 "Should only get there with C++17 and above!"); 14460 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 14461 "Should only get there with an overloaded binary operator" 14462 " or an overloaded call operator!"); 14463 14464 if (SequencingKind == LHSBeforeRest) { 14465 assert(CXXOCE->getOperator() == OO_Call && 14466 "We should only have an overloaded call operator here!"); 14467 14468 // This is very similar to VisitCallExpr, except that we only have the 14469 // C++17 case. The postfix-expression is the first argument of the 14470 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 14471 // are in the following arguments. 14472 // 14473 // Note that we intentionally do not visit the callee expression since 14474 // it is just a decayed reference to a function. 14475 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 14476 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 14477 SequenceTree::Seq OldRegion = Region; 14478 14479 assert(CXXOCE->getNumArgs() >= 1 && 14480 "An overloaded call operator must have at least one argument" 14481 " for the postfix-expression!"); 14482 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 14483 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 14484 CXXOCE->getNumArgs() - 1); 14485 14486 // Visit the postfix-expression first. 14487 { 14488 Region = PostfixExprRegion; 14489 SequencedSubexpression Sequenced(*this); 14490 Visit(PostfixExpr); 14491 } 14492 14493 // Then visit the argument expressions. 14494 Region = ArgsRegion; 14495 for (const Expr *Arg : Args) 14496 Visit(Arg); 14497 14498 Region = OldRegion; 14499 Tree.merge(PostfixExprRegion); 14500 Tree.merge(ArgsRegion); 14501 } else { 14502 assert(CXXOCE->getNumArgs() == 2 && 14503 "Should only have two arguments here!"); 14504 assert((SequencingKind == LHSBeforeRHS || 14505 SequencingKind == RHSBeforeLHS) && 14506 "Unexpected sequencing kind!"); 14507 14508 // We do not visit the callee expression since it is just a decayed 14509 // reference to a function. 14510 const Expr *E1 = CXXOCE->getArg(0); 14511 const Expr *E2 = CXXOCE->getArg(1); 14512 if (SequencingKind == RHSBeforeLHS) 14513 std::swap(E1, E2); 14514 14515 return VisitSequencedExpressions(E1, E2); 14516 } 14517 }); 14518 } 14519 14520 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 14521 // This is a call, so all subexpressions are sequenced before the result. 14522 SequencedSubexpression Sequenced(*this); 14523 14524 if (!CCE->isListInitialization()) 14525 return VisitExpr(CCE); 14526 14527 // In C++11, list initializations are sequenced. 14528 SmallVector<SequenceTree::Seq, 32> Elts; 14529 SequenceTree::Seq Parent = Region; 14530 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 14531 E = CCE->arg_end(); 14532 I != E; ++I) { 14533 Region = Tree.allocate(Parent); 14534 Elts.push_back(Region); 14535 Visit(*I); 14536 } 14537 14538 // Forget that the initializers are sequenced. 14539 Region = Parent; 14540 for (unsigned I = 0; I < Elts.size(); ++I) 14541 Tree.merge(Elts[I]); 14542 } 14543 14544 void VisitInitListExpr(const InitListExpr *ILE) { 14545 if (!SemaRef.getLangOpts().CPlusPlus11) 14546 return VisitExpr(ILE); 14547 14548 // In C++11, list initializations are sequenced. 14549 SmallVector<SequenceTree::Seq, 32> Elts; 14550 SequenceTree::Seq Parent = Region; 14551 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 14552 const Expr *E = ILE->getInit(I); 14553 if (!E) 14554 continue; 14555 Region = Tree.allocate(Parent); 14556 Elts.push_back(Region); 14557 Visit(E); 14558 } 14559 14560 // Forget that the initializers are sequenced. 14561 Region = Parent; 14562 for (unsigned I = 0; I < Elts.size(); ++I) 14563 Tree.merge(Elts[I]); 14564 } 14565 }; 14566 14567 } // namespace 14568 14569 void Sema::CheckUnsequencedOperations(const Expr *E) { 14570 SmallVector<const Expr *, 8> WorkList; 14571 WorkList.push_back(E); 14572 while (!WorkList.empty()) { 14573 const Expr *Item = WorkList.pop_back_val(); 14574 SequenceChecker(*this, Item, WorkList); 14575 } 14576 } 14577 14578 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 14579 bool IsConstexpr) { 14580 llvm::SaveAndRestore<bool> ConstantContext( 14581 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 14582 CheckImplicitConversions(E, CheckLoc); 14583 if (!E->isInstantiationDependent()) 14584 CheckUnsequencedOperations(E); 14585 if (!IsConstexpr && !E->isValueDependent()) 14586 CheckForIntOverflow(E); 14587 DiagnoseMisalignedMembers(); 14588 } 14589 14590 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 14591 FieldDecl *BitField, 14592 Expr *Init) { 14593 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 14594 } 14595 14596 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 14597 SourceLocation Loc) { 14598 if (!PType->isVariablyModifiedType()) 14599 return; 14600 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 14601 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 14602 return; 14603 } 14604 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 14605 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 14606 return; 14607 } 14608 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 14609 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 14610 return; 14611 } 14612 14613 const ArrayType *AT = S.Context.getAsArrayType(PType); 14614 if (!AT) 14615 return; 14616 14617 if (AT->getSizeModifier() != ArrayType::Star) { 14618 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 14619 return; 14620 } 14621 14622 S.Diag(Loc, diag::err_array_star_in_function_definition); 14623 } 14624 14625 /// CheckParmsForFunctionDef - Check that the parameters of the given 14626 /// function are appropriate for the definition of a function. This 14627 /// takes care of any checks that cannot be performed on the 14628 /// declaration itself, e.g., that the types of each of the function 14629 /// parameters are complete. 14630 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 14631 bool CheckParameterNames) { 14632 bool HasInvalidParm = false; 14633 for (ParmVarDecl *Param : Parameters) { 14634 // C99 6.7.5.3p4: the parameters in a parameter type list in a 14635 // function declarator that is part of a function definition of 14636 // that function shall not have incomplete type. 14637 // 14638 // This is also C++ [dcl.fct]p6. 14639 if (!Param->isInvalidDecl() && 14640 RequireCompleteType(Param->getLocation(), Param->getType(), 14641 diag::err_typecheck_decl_incomplete_type)) { 14642 Param->setInvalidDecl(); 14643 HasInvalidParm = true; 14644 } 14645 14646 // C99 6.9.1p5: If the declarator includes a parameter type list, the 14647 // declaration of each parameter shall include an identifier. 14648 if (CheckParameterNames && Param->getIdentifier() == nullptr && 14649 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 14650 // Diagnose this as an extension in C17 and earlier. 14651 if (!getLangOpts().C2x) 14652 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 14653 } 14654 14655 // C99 6.7.5.3p12: 14656 // If the function declarator is not part of a definition of that 14657 // function, parameters may have incomplete type and may use the [*] 14658 // notation in their sequences of declarator specifiers to specify 14659 // variable length array types. 14660 QualType PType = Param->getOriginalType(); 14661 // FIXME: This diagnostic should point the '[*]' if source-location 14662 // information is added for it. 14663 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 14664 14665 // If the parameter is a c++ class type and it has to be destructed in the 14666 // callee function, declare the destructor so that it can be called by the 14667 // callee function. Do not perform any direct access check on the dtor here. 14668 if (!Param->isInvalidDecl()) { 14669 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 14670 if (!ClassDecl->isInvalidDecl() && 14671 !ClassDecl->hasIrrelevantDestructor() && 14672 !ClassDecl->isDependentContext() && 14673 ClassDecl->isParamDestroyedInCallee()) { 14674 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 14675 MarkFunctionReferenced(Param->getLocation(), Destructor); 14676 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 14677 } 14678 } 14679 } 14680 14681 // Parameters with the pass_object_size attribute only need to be marked 14682 // constant at function definitions. Because we lack information about 14683 // whether we're on a declaration or definition when we're instantiating the 14684 // attribute, we need to check for constness here. 14685 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 14686 if (!Param->getType().isConstQualified()) 14687 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 14688 << Attr->getSpelling() << 1; 14689 14690 // Check for parameter names shadowing fields from the class. 14691 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 14692 // The owning context for the parameter should be the function, but we 14693 // want to see if this function's declaration context is a record. 14694 DeclContext *DC = Param->getDeclContext(); 14695 if (DC && DC->isFunctionOrMethod()) { 14696 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 14697 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 14698 RD, /*DeclIsField*/ false); 14699 } 14700 } 14701 } 14702 14703 return HasInvalidParm; 14704 } 14705 14706 Optional<std::pair<CharUnits, CharUnits>> 14707 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 14708 14709 /// Compute the alignment and offset of the base class object given the 14710 /// derived-to-base cast expression and the alignment and offset of the derived 14711 /// class object. 14712 static std::pair<CharUnits, CharUnits> 14713 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 14714 CharUnits BaseAlignment, CharUnits Offset, 14715 ASTContext &Ctx) { 14716 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 14717 ++PathI) { 14718 const CXXBaseSpecifier *Base = *PathI; 14719 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 14720 if (Base->isVirtual()) { 14721 // The complete object may have a lower alignment than the non-virtual 14722 // alignment of the base, in which case the base may be misaligned. Choose 14723 // the smaller of the non-virtual alignment and BaseAlignment, which is a 14724 // conservative lower bound of the complete object alignment. 14725 CharUnits NonVirtualAlignment = 14726 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 14727 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 14728 Offset = CharUnits::Zero(); 14729 } else { 14730 const ASTRecordLayout &RL = 14731 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 14732 Offset += RL.getBaseClassOffset(BaseDecl); 14733 } 14734 DerivedType = Base->getType(); 14735 } 14736 14737 return std::make_pair(BaseAlignment, Offset); 14738 } 14739 14740 /// Compute the alignment and offset of a binary additive operator. 14741 static Optional<std::pair<CharUnits, CharUnits>> 14742 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 14743 bool IsSub, ASTContext &Ctx) { 14744 QualType PointeeType = PtrE->getType()->getPointeeType(); 14745 14746 if (!PointeeType->isConstantSizeType()) 14747 return llvm::None; 14748 14749 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 14750 14751 if (!P) 14752 return llvm::None; 14753 14754 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 14755 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 14756 CharUnits Offset = EltSize * IdxRes->getExtValue(); 14757 if (IsSub) 14758 Offset = -Offset; 14759 return std::make_pair(P->first, P->second + Offset); 14760 } 14761 14762 // If the integer expression isn't a constant expression, compute the lower 14763 // bound of the alignment using the alignment and offset of the pointer 14764 // expression and the element size. 14765 return std::make_pair( 14766 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 14767 CharUnits::Zero()); 14768 } 14769 14770 /// This helper function takes an lvalue expression and returns the alignment of 14771 /// a VarDecl and a constant offset from the VarDecl. 14772 Optional<std::pair<CharUnits, CharUnits>> 14773 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 14774 E = E->IgnoreParens(); 14775 switch (E->getStmtClass()) { 14776 default: 14777 break; 14778 case Stmt::CStyleCastExprClass: 14779 case Stmt::CXXStaticCastExprClass: 14780 case Stmt::ImplicitCastExprClass: { 14781 auto *CE = cast<CastExpr>(E); 14782 const Expr *From = CE->getSubExpr(); 14783 switch (CE->getCastKind()) { 14784 default: 14785 break; 14786 case CK_NoOp: 14787 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14788 case CK_UncheckedDerivedToBase: 14789 case CK_DerivedToBase: { 14790 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14791 if (!P) 14792 break; 14793 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 14794 P->second, Ctx); 14795 } 14796 } 14797 break; 14798 } 14799 case Stmt::ArraySubscriptExprClass: { 14800 auto *ASE = cast<ArraySubscriptExpr>(E); 14801 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 14802 false, Ctx); 14803 } 14804 case Stmt::DeclRefExprClass: { 14805 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 14806 // FIXME: If VD is captured by copy or is an escaping __block variable, 14807 // use the alignment of VD's type. 14808 if (!VD->getType()->isReferenceType()) 14809 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 14810 if (VD->hasInit()) 14811 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 14812 } 14813 break; 14814 } 14815 case Stmt::MemberExprClass: { 14816 auto *ME = cast<MemberExpr>(E); 14817 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 14818 if (!FD || FD->getType()->isReferenceType() || 14819 FD->getParent()->isInvalidDecl()) 14820 break; 14821 Optional<std::pair<CharUnits, CharUnits>> P; 14822 if (ME->isArrow()) 14823 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 14824 else 14825 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 14826 if (!P) 14827 break; 14828 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 14829 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 14830 return std::make_pair(P->first, 14831 P->second + CharUnits::fromQuantity(Offset)); 14832 } 14833 case Stmt::UnaryOperatorClass: { 14834 auto *UO = cast<UnaryOperator>(E); 14835 switch (UO->getOpcode()) { 14836 default: 14837 break; 14838 case UO_Deref: 14839 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 14840 } 14841 break; 14842 } 14843 case Stmt::BinaryOperatorClass: { 14844 auto *BO = cast<BinaryOperator>(E); 14845 auto Opcode = BO->getOpcode(); 14846 switch (Opcode) { 14847 default: 14848 break; 14849 case BO_Comma: 14850 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 14851 } 14852 break; 14853 } 14854 } 14855 return llvm::None; 14856 } 14857 14858 /// This helper function takes a pointer expression and returns the alignment of 14859 /// a VarDecl and a constant offset from the VarDecl. 14860 Optional<std::pair<CharUnits, CharUnits>> 14861 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 14862 E = E->IgnoreParens(); 14863 switch (E->getStmtClass()) { 14864 default: 14865 break; 14866 case Stmt::CStyleCastExprClass: 14867 case Stmt::CXXStaticCastExprClass: 14868 case Stmt::ImplicitCastExprClass: { 14869 auto *CE = cast<CastExpr>(E); 14870 const Expr *From = CE->getSubExpr(); 14871 switch (CE->getCastKind()) { 14872 default: 14873 break; 14874 case CK_NoOp: 14875 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14876 case CK_ArrayToPointerDecay: 14877 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 14878 case CK_UncheckedDerivedToBase: 14879 case CK_DerivedToBase: { 14880 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 14881 if (!P) 14882 break; 14883 return getDerivedToBaseAlignmentAndOffset( 14884 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 14885 } 14886 } 14887 break; 14888 } 14889 case Stmt::CXXThisExprClass: { 14890 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 14891 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 14892 return std::make_pair(Alignment, CharUnits::Zero()); 14893 } 14894 case Stmt::UnaryOperatorClass: { 14895 auto *UO = cast<UnaryOperator>(E); 14896 if (UO->getOpcode() == UO_AddrOf) 14897 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 14898 break; 14899 } 14900 case Stmt::BinaryOperatorClass: { 14901 auto *BO = cast<BinaryOperator>(E); 14902 auto Opcode = BO->getOpcode(); 14903 switch (Opcode) { 14904 default: 14905 break; 14906 case BO_Add: 14907 case BO_Sub: { 14908 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 14909 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 14910 std::swap(LHS, RHS); 14911 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 14912 Ctx); 14913 } 14914 case BO_Comma: 14915 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 14916 } 14917 break; 14918 } 14919 } 14920 return llvm::None; 14921 } 14922 14923 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 14924 // See if we can compute the alignment of a VarDecl and an offset from it. 14925 Optional<std::pair<CharUnits, CharUnits>> P = 14926 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 14927 14928 if (P) 14929 return P->first.alignmentAtOffset(P->second); 14930 14931 // If that failed, return the type's alignment. 14932 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 14933 } 14934 14935 /// CheckCastAlign - Implements -Wcast-align, which warns when a 14936 /// pointer cast increases the alignment requirements. 14937 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 14938 // This is actually a lot of work to potentially be doing on every 14939 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 14940 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 14941 return; 14942 14943 // Ignore dependent types. 14944 if (T->isDependentType() || Op->getType()->isDependentType()) 14945 return; 14946 14947 // Require that the destination be a pointer type. 14948 const PointerType *DestPtr = T->getAs<PointerType>(); 14949 if (!DestPtr) return; 14950 14951 // If the destination has alignment 1, we're done. 14952 QualType DestPointee = DestPtr->getPointeeType(); 14953 if (DestPointee->isIncompleteType()) return; 14954 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 14955 if (DestAlign.isOne()) return; 14956 14957 // Require that the source be a pointer type. 14958 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 14959 if (!SrcPtr) return; 14960 QualType SrcPointee = SrcPtr->getPointeeType(); 14961 14962 // Explicitly allow casts from cv void*. We already implicitly 14963 // allowed casts to cv void*, since they have alignment 1. 14964 // Also allow casts involving incomplete types, which implicitly 14965 // includes 'void'. 14966 if (SrcPointee->isIncompleteType()) return; 14967 14968 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 14969 14970 if (SrcAlign >= DestAlign) return; 14971 14972 Diag(TRange.getBegin(), diag::warn_cast_align) 14973 << Op->getType() << T 14974 << static_cast<unsigned>(SrcAlign.getQuantity()) 14975 << static_cast<unsigned>(DestAlign.getQuantity()) 14976 << TRange << Op->getSourceRange(); 14977 } 14978 14979 /// Check whether this array fits the idiom of a size-one tail padded 14980 /// array member of a struct. 14981 /// 14982 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 14983 /// commonly used to emulate flexible arrays in C89 code. 14984 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 14985 const NamedDecl *ND) { 14986 if (Size != 1 || !ND) return false; 14987 14988 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 14989 if (!FD) return false; 14990 14991 // Don't consider sizes resulting from macro expansions or template argument 14992 // substitution to form C89 tail-padded arrays. 14993 14994 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 14995 while (TInfo) { 14996 TypeLoc TL = TInfo->getTypeLoc(); 14997 // Look through typedefs. 14998 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 14999 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 15000 TInfo = TDL->getTypeSourceInfo(); 15001 continue; 15002 } 15003 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 15004 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 15005 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 15006 return false; 15007 } 15008 break; 15009 } 15010 15011 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 15012 if (!RD) return false; 15013 if (RD->isUnion()) return false; 15014 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 15015 if (!CRD->isStandardLayout()) return false; 15016 } 15017 15018 // See if this is the last field decl in the record. 15019 const Decl *D = FD; 15020 while ((D = D->getNextDeclInContext())) 15021 if (isa<FieldDecl>(D)) 15022 return false; 15023 return true; 15024 } 15025 15026 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 15027 const ArraySubscriptExpr *ASE, 15028 bool AllowOnePastEnd, bool IndexNegated) { 15029 // Already diagnosed by the constant evaluator. 15030 if (isConstantEvaluated()) 15031 return; 15032 15033 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 15034 if (IndexExpr->isValueDependent()) 15035 return; 15036 15037 const Type *EffectiveType = 15038 BaseExpr->getType()->getPointeeOrArrayElementType(); 15039 BaseExpr = BaseExpr->IgnoreParenCasts(); 15040 const ConstantArrayType *ArrayTy = 15041 Context.getAsConstantArrayType(BaseExpr->getType()); 15042 15043 const Type *BaseType = 15044 ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr(); 15045 bool IsUnboundedArray = (BaseType == nullptr); 15046 if (EffectiveType->isDependentType() || 15047 (!IsUnboundedArray && BaseType->isDependentType())) 15048 return; 15049 15050 Expr::EvalResult Result; 15051 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 15052 return; 15053 15054 llvm::APSInt index = Result.Val.getInt(); 15055 if (IndexNegated) { 15056 index.setIsUnsigned(false); 15057 index = -index; 15058 } 15059 15060 const NamedDecl *ND = nullptr; 15061 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15062 ND = DRE->getDecl(); 15063 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 15064 ND = ME->getMemberDecl(); 15065 15066 if (IsUnboundedArray) { 15067 if (index.isUnsigned() || !index.isNegative()) { 15068 const auto &ASTC = getASTContext(); 15069 unsigned AddrBits = 15070 ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace( 15071 EffectiveType->getCanonicalTypeInternal())); 15072 if (index.getBitWidth() < AddrBits) 15073 index = index.zext(AddrBits); 15074 Optional<CharUnits> ElemCharUnits = 15075 ASTC.getTypeSizeInCharsIfKnown(EffectiveType); 15076 // PR50741 - If EffectiveType has unknown size (e.g., if it's a void 15077 // pointer) bounds-checking isn't meaningful. 15078 if (!ElemCharUnits) 15079 return; 15080 llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity()); 15081 // If index has more active bits than address space, we already know 15082 // we have a bounds violation to warn about. Otherwise, compute 15083 // address of (index + 1)th element, and warn about bounds violation 15084 // only if that address exceeds address space. 15085 if (index.getActiveBits() <= AddrBits) { 15086 bool Overflow; 15087 llvm::APInt Product(index); 15088 Product += 1; 15089 Product = Product.umul_ov(ElemBytes, Overflow); 15090 if (!Overflow && Product.getActiveBits() <= AddrBits) 15091 return; 15092 } 15093 15094 // Need to compute max possible elements in address space, since that 15095 // is included in diag message. 15096 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits); 15097 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth())); 15098 MaxElems += 1; 15099 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth()); 15100 MaxElems = MaxElems.udiv(ElemBytes); 15101 15102 unsigned DiagID = 15103 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds 15104 : diag::warn_ptr_arith_exceeds_max_addressable_bounds; 15105 15106 // Diag message shows element size in bits and in "bytes" (platform- 15107 // dependent CharUnits) 15108 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15109 PDiag(DiagID) 15110 << toString(index, 10, true) << AddrBits 15111 << (unsigned)ASTC.toBits(*ElemCharUnits) 15112 << toString(ElemBytes, 10, false) 15113 << toString(MaxElems, 10, false) 15114 << (unsigned)MaxElems.getLimitedValue(~0U) 15115 << IndexExpr->getSourceRange()); 15116 15117 if (!ND) { 15118 // Try harder to find a NamedDecl to point at in the note. 15119 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15120 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15121 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15122 ND = DRE->getDecl(); 15123 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15124 ND = ME->getMemberDecl(); 15125 } 15126 15127 if (ND) 15128 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15129 PDiag(diag::note_array_declared_here) << ND); 15130 } 15131 return; 15132 } 15133 15134 if (index.isUnsigned() || !index.isNegative()) { 15135 // It is possible that the type of the base expression after 15136 // IgnoreParenCasts is incomplete, even though the type of the base 15137 // expression before IgnoreParenCasts is complete (see PR39746 for an 15138 // example). In this case we have no information about whether the array 15139 // access exceeds the array bounds. However we can still diagnose an array 15140 // access which precedes the array bounds. 15141 if (BaseType->isIncompleteType()) 15142 return; 15143 15144 llvm::APInt size = ArrayTy->getSize(); 15145 if (!size.isStrictlyPositive()) 15146 return; 15147 15148 if (BaseType != EffectiveType) { 15149 // Make sure we're comparing apples to apples when comparing index to size 15150 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 15151 uint64_t array_typesize = Context.getTypeSize(BaseType); 15152 // Handle ptrarith_typesize being zero, such as when casting to void* 15153 if (!ptrarith_typesize) ptrarith_typesize = 1; 15154 if (ptrarith_typesize != array_typesize) { 15155 // There's a cast to a different size type involved 15156 uint64_t ratio = array_typesize / ptrarith_typesize; 15157 // TODO: Be smarter about handling cases where array_typesize is not a 15158 // multiple of ptrarith_typesize 15159 if (ptrarith_typesize * ratio == array_typesize) 15160 size *= llvm::APInt(size.getBitWidth(), ratio); 15161 } 15162 } 15163 15164 if (size.getBitWidth() > index.getBitWidth()) 15165 index = index.zext(size.getBitWidth()); 15166 else if (size.getBitWidth() < index.getBitWidth()) 15167 size = size.zext(index.getBitWidth()); 15168 15169 // For array subscripting the index must be less than size, but for pointer 15170 // arithmetic also allow the index (offset) to be equal to size since 15171 // computing the next address after the end of the array is legal and 15172 // commonly done e.g. in C++ iterators and range-based for loops. 15173 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 15174 return; 15175 15176 // Also don't warn for arrays of size 1 which are members of some 15177 // structure. These are often used to approximate flexible arrays in C89 15178 // code. 15179 if (IsTailPaddedMemberArray(*this, size, ND)) 15180 return; 15181 15182 // Suppress the warning if the subscript expression (as identified by the 15183 // ']' location) and the index expression are both from macro expansions 15184 // within a system header. 15185 if (ASE) { 15186 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 15187 ASE->getRBracketLoc()); 15188 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 15189 SourceLocation IndexLoc = 15190 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 15191 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 15192 return; 15193 } 15194 } 15195 15196 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds 15197 : diag::warn_ptr_arith_exceeds_bounds; 15198 15199 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15200 PDiag(DiagID) << toString(index, 10, true) 15201 << toString(size, 10, true) 15202 << (unsigned)size.getLimitedValue(~0U) 15203 << IndexExpr->getSourceRange()); 15204 } else { 15205 unsigned DiagID = diag::warn_array_index_precedes_bounds; 15206 if (!ASE) { 15207 DiagID = diag::warn_ptr_arith_precedes_bounds; 15208 if (index.isNegative()) index = -index; 15209 } 15210 15211 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 15212 PDiag(DiagID) << toString(index, 10, true) 15213 << IndexExpr->getSourceRange()); 15214 } 15215 15216 if (!ND) { 15217 // Try harder to find a NamedDecl to point at in the note. 15218 while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr)) 15219 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 15220 if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 15221 ND = DRE->getDecl(); 15222 if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr)) 15223 ND = ME->getMemberDecl(); 15224 } 15225 15226 if (ND) 15227 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 15228 PDiag(diag::note_array_declared_here) << ND); 15229 } 15230 15231 void Sema::CheckArrayAccess(const Expr *expr) { 15232 int AllowOnePastEnd = 0; 15233 while (expr) { 15234 expr = expr->IgnoreParenImpCasts(); 15235 switch (expr->getStmtClass()) { 15236 case Stmt::ArraySubscriptExprClass: { 15237 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 15238 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 15239 AllowOnePastEnd > 0); 15240 expr = ASE->getBase(); 15241 break; 15242 } 15243 case Stmt::MemberExprClass: { 15244 expr = cast<MemberExpr>(expr)->getBase(); 15245 break; 15246 } 15247 case Stmt::OMPArraySectionExprClass: { 15248 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 15249 if (ASE->getLowerBound()) 15250 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 15251 /*ASE=*/nullptr, AllowOnePastEnd > 0); 15252 return; 15253 } 15254 case Stmt::UnaryOperatorClass: { 15255 // Only unwrap the * and & unary operators 15256 const UnaryOperator *UO = cast<UnaryOperator>(expr); 15257 expr = UO->getSubExpr(); 15258 switch (UO->getOpcode()) { 15259 case UO_AddrOf: 15260 AllowOnePastEnd++; 15261 break; 15262 case UO_Deref: 15263 AllowOnePastEnd--; 15264 break; 15265 default: 15266 return; 15267 } 15268 break; 15269 } 15270 case Stmt::ConditionalOperatorClass: { 15271 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 15272 if (const Expr *lhs = cond->getLHS()) 15273 CheckArrayAccess(lhs); 15274 if (const Expr *rhs = cond->getRHS()) 15275 CheckArrayAccess(rhs); 15276 return; 15277 } 15278 case Stmt::CXXOperatorCallExprClass: { 15279 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 15280 for (const auto *Arg : OCE->arguments()) 15281 CheckArrayAccess(Arg); 15282 return; 15283 } 15284 default: 15285 return; 15286 } 15287 } 15288 } 15289 15290 //===--- CHECK: Objective-C retain cycles ----------------------------------// 15291 15292 namespace { 15293 15294 struct RetainCycleOwner { 15295 VarDecl *Variable = nullptr; 15296 SourceRange Range; 15297 SourceLocation Loc; 15298 bool Indirect = false; 15299 15300 RetainCycleOwner() = default; 15301 15302 void setLocsFrom(Expr *e) { 15303 Loc = e->getExprLoc(); 15304 Range = e->getSourceRange(); 15305 } 15306 }; 15307 15308 } // namespace 15309 15310 /// Consider whether capturing the given variable can possibly lead to 15311 /// a retain cycle. 15312 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 15313 // In ARC, it's captured strongly iff the variable has __strong 15314 // lifetime. In MRR, it's captured strongly if the variable is 15315 // __block and has an appropriate type. 15316 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15317 return false; 15318 15319 owner.Variable = var; 15320 if (ref) 15321 owner.setLocsFrom(ref); 15322 return true; 15323 } 15324 15325 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 15326 while (true) { 15327 e = e->IgnoreParens(); 15328 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 15329 switch (cast->getCastKind()) { 15330 case CK_BitCast: 15331 case CK_LValueBitCast: 15332 case CK_LValueToRValue: 15333 case CK_ARCReclaimReturnedObject: 15334 e = cast->getSubExpr(); 15335 continue; 15336 15337 default: 15338 return false; 15339 } 15340 } 15341 15342 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 15343 ObjCIvarDecl *ivar = ref->getDecl(); 15344 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 15345 return false; 15346 15347 // Try to find a retain cycle in the base. 15348 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 15349 return false; 15350 15351 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 15352 owner.Indirect = true; 15353 return true; 15354 } 15355 15356 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 15357 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 15358 if (!var) return false; 15359 return considerVariable(var, ref, owner); 15360 } 15361 15362 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 15363 if (member->isArrow()) return false; 15364 15365 // Don't count this as an indirect ownership. 15366 e = member->getBase(); 15367 continue; 15368 } 15369 15370 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 15371 // Only pay attention to pseudo-objects on property references. 15372 ObjCPropertyRefExpr *pre 15373 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 15374 ->IgnoreParens()); 15375 if (!pre) return false; 15376 if (pre->isImplicitProperty()) return false; 15377 ObjCPropertyDecl *property = pre->getExplicitProperty(); 15378 if (!property->isRetaining() && 15379 !(property->getPropertyIvarDecl() && 15380 property->getPropertyIvarDecl()->getType() 15381 .getObjCLifetime() == Qualifiers::OCL_Strong)) 15382 return false; 15383 15384 owner.Indirect = true; 15385 if (pre->isSuperReceiver()) { 15386 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 15387 if (!owner.Variable) 15388 return false; 15389 owner.Loc = pre->getLocation(); 15390 owner.Range = pre->getSourceRange(); 15391 return true; 15392 } 15393 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 15394 ->getSourceExpr()); 15395 continue; 15396 } 15397 15398 // Array ivars? 15399 15400 return false; 15401 } 15402 } 15403 15404 namespace { 15405 15406 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 15407 ASTContext &Context; 15408 VarDecl *Variable; 15409 Expr *Capturer = nullptr; 15410 bool VarWillBeReased = false; 15411 15412 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 15413 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 15414 Context(Context), Variable(variable) {} 15415 15416 void VisitDeclRefExpr(DeclRefExpr *ref) { 15417 if (ref->getDecl() == Variable && !Capturer) 15418 Capturer = ref; 15419 } 15420 15421 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 15422 if (Capturer) return; 15423 Visit(ref->getBase()); 15424 if (Capturer && ref->isFreeIvar()) 15425 Capturer = ref; 15426 } 15427 15428 void VisitBlockExpr(BlockExpr *block) { 15429 // Look inside nested blocks 15430 if (block->getBlockDecl()->capturesVariable(Variable)) 15431 Visit(block->getBlockDecl()->getBody()); 15432 } 15433 15434 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 15435 if (Capturer) return; 15436 if (OVE->getSourceExpr()) 15437 Visit(OVE->getSourceExpr()); 15438 } 15439 15440 void VisitBinaryOperator(BinaryOperator *BinOp) { 15441 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 15442 return; 15443 Expr *LHS = BinOp->getLHS(); 15444 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 15445 if (DRE->getDecl() != Variable) 15446 return; 15447 if (Expr *RHS = BinOp->getRHS()) { 15448 RHS = RHS->IgnoreParenCasts(); 15449 Optional<llvm::APSInt> Value; 15450 VarWillBeReased = 15451 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 15452 *Value == 0); 15453 } 15454 } 15455 } 15456 }; 15457 15458 } // namespace 15459 15460 /// Check whether the given argument is a block which captures a 15461 /// variable. 15462 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 15463 assert(owner.Variable && owner.Loc.isValid()); 15464 15465 e = e->IgnoreParenCasts(); 15466 15467 // Look through [^{...} copy] and Block_copy(^{...}). 15468 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 15469 Selector Cmd = ME->getSelector(); 15470 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 15471 e = ME->getInstanceReceiver(); 15472 if (!e) 15473 return nullptr; 15474 e = e->IgnoreParenCasts(); 15475 } 15476 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 15477 if (CE->getNumArgs() == 1) { 15478 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 15479 if (Fn) { 15480 const IdentifierInfo *FnI = Fn->getIdentifier(); 15481 if (FnI && FnI->isStr("_Block_copy")) { 15482 e = CE->getArg(0)->IgnoreParenCasts(); 15483 } 15484 } 15485 } 15486 } 15487 15488 BlockExpr *block = dyn_cast<BlockExpr>(e); 15489 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 15490 return nullptr; 15491 15492 FindCaptureVisitor visitor(S.Context, owner.Variable); 15493 visitor.Visit(block->getBlockDecl()->getBody()); 15494 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 15495 } 15496 15497 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 15498 RetainCycleOwner &owner) { 15499 assert(capturer); 15500 assert(owner.Variable && owner.Loc.isValid()); 15501 15502 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 15503 << owner.Variable << capturer->getSourceRange(); 15504 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 15505 << owner.Indirect << owner.Range; 15506 } 15507 15508 /// Check for a keyword selector that starts with the word 'add' or 15509 /// 'set'. 15510 static bool isSetterLikeSelector(Selector sel) { 15511 if (sel.isUnarySelector()) return false; 15512 15513 StringRef str = sel.getNameForSlot(0); 15514 while (!str.empty() && str.front() == '_') str = str.substr(1); 15515 if (str.startswith("set")) 15516 str = str.substr(3); 15517 else if (str.startswith("add")) { 15518 // Specially allow 'addOperationWithBlock:'. 15519 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 15520 return false; 15521 str = str.substr(3); 15522 } 15523 else 15524 return false; 15525 15526 if (str.empty()) return true; 15527 return !isLowercase(str.front()); 15528 } 15529 15530 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 15531 ObjCMessageExpr *Message) { 15532 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 15533 Message->getReceiverInterface(), 15534 NSAPI::ClassId_NSMutableArray); 15535 if (!IsMutableArray) { 15536 return None; 15537 } 15538 15539 Selector Sel = Message->getSelector(); 15540 15541 Optional<NSAPI::NSArrayMethodKind> MKOpt = 15542 S.NSAPIObj->getNSArrayMethodKind(Sel); 15543 if (!MKOpt) { 15544 return None; 15545 } 15546 15547 NSAPI::NSArrayMethodKind MK = *MKOpt; 15548 15549 switch (MK) { 15550 case NSAPI::NSMutableArr_addObject: 15551 case NSAPI::NSMutableArr_insertObjectAtIndex: 15552 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 15553 return 0; 15554 case NSAPI::NSMutableArr_replaceObjectAtIndex: 15555 return 1; 15556 15557 default: 15558 return None; 15559 } 15560 15561 return None; 15562 } 15563 15564 static 15565 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 15566 ObjCMessageExpr *Message) { 15567 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 15568 Message->getReceiverInterface(), 15569 NSAPI::ClassId_NSMutableDictionary); 15570 if (!IsMutableDictionary) { 15571 return None; 15572 } 15573 15574 Selector Sel = Message->getSelector(); 15575 15576 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 15577 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 15578 if (!MKOpt) { 15579 return None; 15580 } 15581 15582 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 15583 15584 switch (MK) { 15585 case NSAPI::NSMutableDict_setObjectForKey: 15586 case NSAPI::NSMutableDict_setValueForKey: 15587 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 15588 return 0; 15589 15590 default: 15591 return None; 15592 } 15593 15594 return None; 15595 } 15596 15597 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 15598 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 15599 Message->getReceiverInterface(), 15600 NSAPI::ClassId_NSMutableSet); 15601 15602 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 15603 Message->getReceiverInterface(), 15604 NSAPI::ClassId_NSMutableOrderedSet); 15605 if (!IsMutableSet && !IsMutableOrderedSet) { 15606 return None; 15607 } 15608 15609 Selector Sel = Message->getSelector(); 15610 15611 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 15612 if (!MKOpt) { 15613 return None; 15614 } 15615 15616 NSAPI::NSSetMethodKind MK = *MKOpt; 15617 15618 switch (MK) { 15619 case NSAPI::NSMutableSet_addObject: 15620 case NSAPI::NSOrderedSet_setObjectAtIndex: 15621 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 15622 case NSAPI::NSOrderedSet_insertObjectAtIndex: 15623 return 0; 15624 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 15625 return 1; 15626 } 15627 15628 return None; 15629 } 15630 15631 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 15632 if (!Message->isInstanceMessage()) { 15633 return; 15634 } 15635 15636 Optional<int> ArgOpt; 15637 15638 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 15639 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 15640 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 15641 return; 15642 } 15643 15644 int ArgIndex = *ArgOpt; 15645 15646 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 15647 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 15648 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 15649 } 15650 15651 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 15652 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15653 if (ArgRE->isObjCSelfExpr()) { 15654 Diag(Message->getSourceRange().getBegin(), 15655 diag::warn_objc_circular_container) 15656 << ArgRE->getDecl() << StringRef("'super'"); 15657 } 15658 } 15659 } else { 15660 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 15661 15662 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 15663 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 15664 } 15665 15666 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 15667 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 15668 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 15669 ValueDecl *Decl = ReceiverRE->getDecl(); 15670 Diag(Message->getSourceRange().getBegin(), 15671 diag::warn_objc_circular_container) 15672 << Decl << Decl; 15673 if (!ArgRE->isObjCSelfExpr()) { 15674 Diag(Decl->getLocation(), 15675 diag::note_objc_circular_container_declared_here) 15676 << Decl; 15677 } 15678 } 15679 } 15680 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 15681 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 15682 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 15683 ObjCIvarDecl *Decl = IvarRE->getDecl(); 15684 Diag(Message->getSourceRange().getBegin(), 15685 diag::warn_objc_circular_container) 15686 << Decl << Decl; 15687 Diag(Decl->getLocation(), 15688 diag::note_objc_circular_container_declared_here) 15689 << Decl; 15690 } 15691 } 15692 } 15693 } 15694 } 15695 15696 /// Check a message send to see if it's likely to cause a retain cycle. 15697 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 15698 // Only check instance methods whose selector looks like a setter. 15699 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 15700 return; 15701 15702 // Try to find a variable that the receiver is strongly owned by. 15703 RetainCycleOwner owner; 15704 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 15705 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 15706 return; 15707 } else { 15708 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 15709 owner.Variable = getCurMethodDecl()->getSelfDecl(); 15710 owner.Loc = msg->getSuperLoc(); 15711 owner.Range = msg->getSuperLoc(); 15712 } 15713 15714 // Check whether the receiver is captured by any of the arguments. 15715 const ObjCMethodDecl *MD = msg->getMethodDecl(); 15716 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 15717 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 15718 // noescape blocks should not be retained by the method. 15719 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 15720 continue; 15721 return diagnoseRetainCycle(*this, capturer, owner); 15722 } 15723 } 15724 } 15725 15726 /// Check a property assign to see if it's likely to cause a retain cycle. 15727 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 15728 RetainCycleOwner owner; 15729 if (!findRetainCycleOwner(*this, receiver, owner)) 15730 return; 15731 15732 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 15733 diagnoseRetainCycle(*this, capturer, owner); 15734 } 15735 15736 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 15737 RetainCycleOwner Owner; 15738 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 15739 return; 15740 15741 // Because we don't have an expression for the variable, we have to set the 15742 // location explicitly here. 15743 Owner.Loc = Var->getLocation(); 15744 Owner.Range = Var->getSourceRange(); 15745 15746 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 15747 diagnoseRetainCycle(*this, Capturer, Owner); 15748 } 15749 15750 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 15751 Expr *RHS, bool isProperty) { 15752 // Check if RHS is an Objective-C object literal, which also can get 15753 // immediately zapped in a weak reference. Note that we explicitly 15754 // allow ObjCStringLiterals, since those are designed to never really die. 15755 RHS = RHS->IgnoreParenImpCasts(); 15756 15757 // This enum needs to match with the 'select' in 15758 // warn_objc_arc_literal_assign (off-by-1). 15759 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 15760 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 15761 return false; 15762 15763 S.Diag(Loc, diag::warn_arc_literal_assign) 15764 << (unsigned) Kind 15765 << (isProperty ? 0 : 1) 15766 << RHS->getSourceRange(); 15767 15768 return true; 15769 } 15770 15771 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 15772 Qualifiers::ObjCLifetime LT, 15773 Expr *RHS, bool isProperty) { 15774 // Strip off any implicit cast added to get to the one ARC-specific. 15775 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15776 if (cast->getCastKind() == CK_ARCConsumeObject) { 15777 S.Diag(Loc, diag::warn_arc_retained_assign) 15778 << (LT == Qualifiers::OCL_ExplicitNone) 15779 << (isProperty ? 0 : 1) 15780 << RHS->getSourceRange(); 15781 return true; 15782 } 15783 RHS = cast->getSubExpr(); 15784 } 15785 15786 if (LT == Qualifiers::OCL_Weak && 15787 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 15788 return true; 15789 15790 return false; 15791 } 15792 15793 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 15794 QualType LHS, Expr *RHS) { 15795 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 15796 15797 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 15798 return false; 15799 15800 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 15801 return true; 15802 15803 return false; 15804 } 15805 15806 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 15807 Expr *LHS, Expr *RHS) { 15808 QualType LHSType; 15809 // PropertyRef on LHS type need be directly obtained from 15810 // its declaration as it has a PseudoType. 15811 ObjCPropertyRefExpr *PRE 15812 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 15813 if (PRE && !PRE->isImplicitProperty()) { 15814 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15815 if (PD) 15816 LHSType = PD->getType(); 15817 } 15818 15819 if (LHSType.isNull()) 15820 LHSType = LHS->getType(); 15821 15822 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 15823 15824 if (LT == Qualifiers::OCL_Weak) { 15825 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 15826 getCurFunction()->markSafeWeakUse(LHS); 15827 } 15828 15829 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 15830 return; 15831 15832 // FIXME. Check for other life times. 15833 if (LT != Qualifiers::OCL_None) 15834 return; 15835 15836 if (PRE) { 15837 if (PRE->isImplicitProperty()) 15838 return; 15839 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 15840 if (!PD) 15841 return; 15842 15843 unsigned Attributes = PD->getPropertyAttributes(); 15844 if (Attributes & ObjCPropertyAttribute::kind_assign) { 15845 // when 'assign' attribute was not explicitly specified 15846 // by user, ignore it and rely on property type itself 15847 // for lifetime info. 15848 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 15849 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 15850 LHSType->isObjCRetainableType()) 15851 return; 15852 15853 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 15854 if (cast->getCastKind() == CK_ARCConsumeObject) { 15855 Diag(Loc, diag::warn_arc_retained_property_assign) 15856 << RHS->getSourceRange(); 15857 return; 15858 } 15859 RHS = cast->getSubExpr(); 15860 } 15861 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 15862 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 15863 return; 15864 } 15865 } 15866 } 15867 15868 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 15869 15870 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 15871 SourceLocation StmtLoc, 15872 const NullStmt *Body) { 15873 // Do not warn if the body is a macro that expands to nothing, e.g: 15874 // 15875 // #define CALL(x) 15876 // if (condition) 15877 // CALL(0); 15878 if (Body->hasLeadingEmptyMacro()) 15879 return false; 15880 15881 // Get line numbers of statement and body. 15882 bool StmtLineInvalid; 15883 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 15884 &StmtLineInvalid); 15885 if (StmtLineInvalid) 15886 return false; 15887 15888 bool BodyLineInvalid; 15889 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 15890 &BodyLineInvalid); 15891 if (BodyLineInvalid) 15892 return false; 15893 15894 // Warn if null statement and body are on the same line. 15895 if (StmtLine != BodyLine) 15896 return false; 15897 15898 return true; 15899 } 15900 15901 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 15902 const Stmt *Body, 15903 unsigned DiagID) { 15904 // Since this is a syntactic check, don't emit diagnostic for template 15905 // instantiations, this just adds noise. 15906 if (CurrentInstantiationScope) 15907 return; 15908 15909 // The body should be a null statement. 15910 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15911 if (!NBody) 15912 return; 15913 15914 // Do the usual checks. 15915 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15916 return; 15917 15918 Diag(NBody->getSemiLoc(), DiagID); 15919 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15920 } 15921 15922 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 15923 const Stmt *PossibleBody) { 15924 assert(!CurrentInstantiationScope); // Ensured by caller 15925 15926 SourceLocation StmtLoc; 15927 const Stmt *Body; 15928 unsigned DiagID; 15929 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 15930 StmtLoc = FS->getRParenLoc(); 15931 Body = FS->getBody(); 15932 DiagID = diag::warn_empty_for_body; 15933 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 15934 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 15935 Body = WS->getBody(); 15936 DiagID = diag::warn_empty_while_body; 15937 } else 15938 return; // Neither `for' nor `while'. 15939 15940 // The body should be a null statement. 15941 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 15942 if (!NBody) 15943 return; 15944 15945 // Skip expensive checks if diagnostic is disabled. 15946 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 15947 return; 15948 15949 // Do the usual checks. 15950 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 15951 return; 15952 15953 // `for(...);' and `while(...);' are popular idioms, so in order to keep 15954 // noise level low, emit diagnostics only if for/while is followed by a 15955 // CompoundStmt, e.g.: 15956 // for (int i = 0; i < n; i++); 15957 // { 15958 // a(i); 15959 // } 15960 // or if for/while is followed by a statement with more indentation 15961 // than for/while itself: 15962 // for (int i = 0; i < n; i++); 15963 // a(i); 15964 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 15965 if (!ProbableTypo) { 15966 bool BodyColInvalid; 15967 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 15968 PossibleBody->getBeginLoc(), &BodyColInvalid); 15969 if (BodyColInvalid) 15970 return; 15971 15972 bool StmtColInvalid; 15973 unsigned StmtCol = 15974 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 15975 if (StmtColInvalid) 15976 return; 15977 15978 if (BodyCol > StmtCol) 15979 ProbableTypo = true; 15980 } 15981 15982 if (ProbableTypo) { 15983 Diag(NBody->getSemiLoc(), DiagID); 15984 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 15985 } 15986 } 15987 15988 //===--- CHECK: Warn on self move with std::move. -------------------------===// 15989 15990 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 15991 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 15992 SourceLocation OpLoc) { 15993 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 15994 return; 15995 15996 if (inTemplateInstantiation()) 15997 return; 15998 15999 // Strip parens and casts away. 16000 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 16001 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 16002 16003 // Check for a call expression 16004 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 16005 if (!CE || CE->getNumArgs() != 1) 16006 return; 16007 16008 // Check for a call to std::move 16009 if (!CE->isCallToStdMove()) 16010 return; 16011 16012 // Get argument from std::move 16013 RHSExpr = CE->getArg(0); 16014 16015 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 16016 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 16017 16018 // Two DeclRefExpr's, check that the decls are the same. 16019 if (LHSDeclRef && RHSDeclRef) { 16020 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16021 return; 16022 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16023 RHSDeclRef->getDecl()->getCanonicalDecl()) 16024 return; 16025 16026 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16027 << LHSExpr->getSourceRange() 16028 << RHSExpr->getSourceRange(); 16029 return; 16030 } 16031 16032 // Member variables require a different approach to check for self moves. 16033 // MemberExpr's are the same if every nested MemberExpr refers to the same 16034 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 16035 // the base Expr's are CXXThisExpr's. 16036 const Expr *LHSBase = LHSExpr; 16037 const Expr *RHSBase = RHSExpr; 16038 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 16039 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 16040 if (!LHSME || !RHSME) 16041 return; 16042 16043 while (LHSME && RHSME) { 16044 if (LHSME->getMemberDecl()->getCanonicalDecl() != 16045 RHSME->getMemberDecl()->getCanonicalDecl()) 16046 return; 16047 16048 LHSBase = LHSME->getBase(); 16049 RHSBase = RHSME->getBase(); 16050 LHSME = dyn_cast<MemberExpr>(LHSBase); 16051 RHSME = dyn_cast<MemberExpr>(RHSBase); 16052 } 16053 16054 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 16055 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 16056 if (LHSDeclRef && RHSDeclRef) { 16057 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 16058 return; 16059 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 16060 RHSDeclRef->getDecl()->getCanonicalDecl()) 16061 return; 16062 16063 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16064 << LHSExpr->getSourceRange() 16065 << RHSExpr->getSourceRange(); 16066 return; 16067 } 16068 16069 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 16070 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 16071 << LHSExpr->getSourceRange() 16072 << RHSExpr->getSourceRange(); 16073 } 16074 16075 //===--- Layout compatibility ----------------------------------------------// 16076 16077 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 16078 16079 /// Check if two enumeration types are layout-compatible. 16080 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 16081 // C++11 [dcl.enum] p8: 16082 // Two enumeration types are layout-compatible if they have the same 16083 // underlying type. 16084 return ED1->isComplete() && ED2->isComplete() && 16085 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 16086 } 16087 16088 /// Check if two fields are layout-compatible. 16089 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 16090 FieldDecl *Field2) { 16091 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 16092 return false; 16093 16094 if (Field1->isBitField() != Field2->isBitField()) 16095 return false; 16096 16097 if (Field1->isBitField()) { 16098 // Make sure that the bit-fields are the same length. 16099 unsigned Bits1 = Field1->getBitWidthValue(C); 16100 unsigned Bits2 = Field2->getBitWidthValue(C); 16101 16102 if (Bits1 != Bits2) 16103 return false; 16104 } 16105 16106 return true; 16107 } 16108 16109 /// Check if two standard-layout structs are layout-compatible. 16110 /// (C++11 [class.mem] p17) 16111 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 16112 RecordDecl *RD2) { 16113 // If both records are C++ classes, check that base classes match. 16114 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 16115 // If one of records is a CXXRecordDecl we are in C++ mode, 16116 // thus the other one is a CXXRecordDecl, too. 16117 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 16118 // Check number of base classes. 16119 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 16120 return false; 16121 16122 // Check the base classes. 16123 for (CXXRecordDecl::base_class_const_iterator 16124 Base1 = D1CXX->bases_begin(), 16125 BaseEnd1 = D1CXX->bases_end(), 16126 Base2 = D2CXX->bases_begin(); 16127 Base1 != BaseEnd1; 16128 ++Base1, ++Base2) { 16129 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 16130 return false; 16131 } 16132 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 16133 // If only RD2 is a C++ class, it should have zero base classes. 16134 if (D2CXX->getNumBases() > 0) 16135 return false; 16136 } 16137 16138 // Check the fields. 16139 RecordDecl::field_iterator Field2 = RD2->field_begin(), 16140 Field2End = RD2->field_end(), 16141 Field1 = RD1->field_begin(), 16142 Field1End = RD1->field_end(); 16143 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 16144 if (!isLayoutCompatible(C, *Field1, *Field2)) 16145 return false; 16146 } 16147 if (Field1 != Field1End || Field2 != Field2End) 16148 return false; 16149 16150 return true; 16151 } 16152 16153 /// Check if two standard-layout unions are layout-compatible. 16154 /// (C++11 [class.mem] p18) 16155 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 16156 RecordDecl *RD2) { 16157 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 16158 for (auto *Field2 : RD2->fields()) 16159 UnmatchedFields.insert(Field2); 16160 16161 for (auto *Field1 : RD1->fields()) { 16162 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 16163 I = UnmatchedFields.begin(), 16164 E = UnmatchedFields.end(); 16165 16166 for ( ; I != E; ++I) { 16167 if (isLayoutCompatible(C, Field1, *I)) { 16168 bool Result = UnmatchedFields.erase(*I); 16169 (void) Result; 16170 assert(Result); 16171 break; 16172 } 16173 } 16174 if (I == E) 16175 return false; 16176 } 16177 16178 return UnmatchedFields.empty(); 16179 } 16180 16181 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 16182 RecordDecl *RD2) { 16183 if (RD1->isUnion() != RD2->isUnion()) 16184 return false; 16185 16186 if (RD1->isUnion()) 16187 return isLayoutCompatibleUnion(C, RD1, RD2); 16188 else 16189 return isLayoutCompatibleStruct(C, RD1, RD2); 16190 } 16191 16192 /// Check if two types are layout-compatible in C++11 sense. 16193 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 16194 if (T1.isNull() || T2.isNull()) 16195 return false; 16196 16197 // C++11 [basic.types] p11: 16198 // If two types T1 and T2 are the same type, then T1 and T2 are 16199 // layout-compatible types. 16200 if (C.hasSameType(T1, T2)) 16201 return true; 16202 16203 T1 = T1.getCanonicalType().getUnqualifiedType(); 16204 T2 = T2.getCanonicalType().getUnqualifiedType(); 16205 16206 const Type::TypeClass TC1 = T1->getTypeClass(); 16207 const Type::TypeClass TC2 = T2->getTypeClass(); 16208 16209 if (TC1 != TC2) 16210 return false; 16211 16212 if (TC1 == Type::Enum) { 16213 return isLayoutCompatible(C, 16214 cast<EnumType>(T1)->getDecl(), 16215 cast<EnumType>(T2)->getDecl()); 16216 } else if (TC1 == Type::Record) { 16217 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 16218 return false; 16219 16220 return isLayoutCompatible(C, 16221 cast<RecordType>(T1)->getDecl(), 16222 cast<RecordType>(T2)->getDecl()); 16223 } 16224 16225 return false; 16226 } 16227 16228 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 16229 16230 /// Given a type tag expression find the type tag itself. 16231 /// 16232 /// \param TypeExpr Type tag expression, as it appears in user's code. 16233 /// 16234 /// \param VD Declaration of an identifier that appears in a type tag. 16235 /// 16236 /// \param MagicValue Type tag magic value. 16237 /// 16238 /// \param isConstantEvaluated whether the evalaution should be performed in 16239 16240 /// constant context. 16241 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 16242 const ValueDecl **VD, uint64_t *MagicValue, 16243 bool isConstantEvaluated) { 16244 while(true) { 16245 if (!TypeExpr) 16246 return false; 16247 16248 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 16249 16250 switch (TypeExpr->getStmtClass()) { 16251 case Stmt::UnaryOperatorClass: { 16252 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 16253 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 16254 TypeExpr = UO->getSubExpr(); 16255 continue; 16256 } 16257 return false; 16258 } 16259 16260 case Stmt::DeclRefExprClass: { 16261 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 16262 *VD = DRE->getDecl(); 16263 return true; 16264 } 16265 16266 case Stmt::IntegerLiteralClass: { 16267 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 16268 llvm::APInt MagicValueAPInt = IL->getValue(); 16269 if (MagicValueAPInt.getActiveBits() <= 64) { 16270 *MagicValue = MagicValueAPInt.getZExtValue(); 16271 return true; 16272 } else 16273 return false; 16274 } 16275 16276 case Stmt::BinaryConditionalOperatorClass: 16277 case Stmt::ConditionalOperatorClass: { 16278 const AbstractConditionalOperator *ACO = 16279 cast<AbstractConditionalOperator>(TypeExpr); 16280 bool Result; 16281 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 16282 isConstantEvaluated)) { 16283 if (Result) 16284 TypeExpr = ACO->getTrueExpr(); 16285 else 16286 TypeExpr = ACO->getFalseExpr(); 16287 continue; 16288 } 16289 return false; 16290 } 16291 16292 case Stmt::BinaryOperatorClass: { 16293 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 16294 if (BO->getOpcode() == BO_Comma) { 16295 TypeExpr = BO->getRHS(); 16296 continue; 16297 } 16298 return false; 16299 } 16300 16301 default: 16302 return false; 16303 } 16304 } 16305 } 16306 16307 /// Retrieve the C type corresponding to type tag TypeExpr. 16308 /// 16309 /// \param TypeExpr Expression that specifies a type tag. 16310 /// 16311 /// \param MagicValues Registered magic values. 16312 /// 16313 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 16314 /// kind. 16315 /// 16316 /// \param TypeInfo Information about the corresponding C type. 16317 /// 16318 /// \param isConstantEvaluated whether the evalaution should be performed in 16319 /// constant context. 16320 /// 16321 /// \returns true if the corresponding C type was found. 16322 static bool GetMatchingCType( 16323 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 16324 const ASTContext &Ctx, 16325 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 16326 *MagicValues, 16327 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 16328 bool isConstantEvaluated) { 16329 FoundWrongKind = false; 16330 16331 // Variable declaration that has type_tag_for_datatype attribute. 16332 const ValueDecl *VD = nullptr; 16333 16334 uint64_t MagicValue; 16335 16336 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 16337 return false; 16338 16339 if (VD) { 16340 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 16341 if (I->getArgumentKind() != ArgumentKind) { 16342 FoundWrongKind = true; 16343 return false; 16344 } 16345 TypeInfo.Type = I->getMatchingCType(); 16346 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 16347 TypeInfo.MustBeNull = I->getMustBeNull(); 16348 return true; 16349 } 16350 return false; 16351 } 16352 16353 if (!MagicValues) 16354 return false; 16355 16356 llvm::DenseMap<Sema::TypeTagMagicValue, 16357 Sema::TypeTagData>::const_iterator I = 16358 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 16359 if (I == MagicValues->end()) 16360 return false; 16361 16362 TypeInfo = I->second; 16363 return true; 16364 } 16365 16366 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 16367 uint64_t MagicValue, QualType Type, 16368 bool LayoutCompatible, 16369 bool MustBeNull) { 16370 if (!TypeTagForDatatypeMagicValues) 16371 TypeTagForDatatypeMagicValues.reset( 16372 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 16373 16374 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 16375 (*TypeTagForDatatypeMagicValues)[Magic] = 16376 TypeTagData(Type, LayoutCompatible, MustBeNull); 16377 } 16378 16379 static bool IsSameCharType(QualType T1, QualType T2) { 16380 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 16381 if (!BT1) 16382 return false; 16383 16384 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 16385 if (!BT2) 16386 return false; 16387 16388 BuiltinType::Kind T1Kind = BT1->getKind(); 16389 BuiltinType::Kind T2Kind = BT2->getKind(); 16390 16391 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 16392 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 16393 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 16394 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 16395 } 16396 16397 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 16398 const ArrayRef<const Expr *> ExprArgs, 16399 SourceLocation CallSiteLoc) { 16400 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 16401 bool IsPointerAttr = Attr->getIsPointer(); 16402 16403 // Retrieve the argument representing the 'type_tag'. 16404 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 16405 if (TypeTagIdxAST >= ExprArgs.size()) { 16406 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16407 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 16408 return; 16409 } 16410 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 16411 bool FoundWrongKind; 16412 TypeTagData TypeInfo; 16413 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 16414 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 16415 TypeInfo, isConstantEvaluated())) { 16416 if (FoundWrongKind) 16417 Diag(TypeTagExpr->getExprLoc(), 16418 diag::warn_type_tag_for_datatype_wrong_kind) 16419 << TypeTagExpr->getSourceRange(); 16420 return; 16421 } 16422 16423 // Retrieve the argument representing the 'arg_idx'. 16424 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 16425 if (ArgumentIdxAST >= ExprArgs.size()) { 16426 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 16427 << 1 << Attr->getArgumentIdx().getSourceIndex(); 16428 return; 16429 } 16430 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 16431 if (IsPointerAttr) { 16432 // Skip implicit cast of pointer to `void *' (as a function argument). 16433 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 16434 if (ICE->getType()->isVoidPointerType() && 16435 ICE->getCastKind() == CK_BitCast) 16436 ArgumentExpr = ICE->getSubExpr(); 16437 } 16438 QualType ArgumentType = ArgumentExpr->getType(); 16439 16440 // Passing a `void*' pointer shouldn't trigger a warning. 16441 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 16442 return; 16443 16444 if (TypeInfo.MustBeNull) { 16445 // Type tag with matching void type requires a null pointer. 16446 if (!ArgumentExpr->isNullPointerConstant(Context, 16447 Expr::NPC_ValueDependentIsNotNull)) { 16448 Diag(ArgumentExpr->getExprLoc(), 16449 diag::warn_type_safety_null_pointer_required) 16450 << ArgumentKind->getName() 16451 << ArgumentExpr->getSourceRange() 16452 << TypeTagExpr->getSourceRange(); 16453 } 16454 return; 16455 } 16456 16457 QualType RequiredType = TypeInfo.Type; 16458 if (IsPointerAttr) 16459 RequiredType = Context.getPointerType(RequiredType); 16460 16461 bool mismatch = false; 16462 if (!TypeInfo.LayoutCompatible) { 16463 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 16464 16465 // C++11 [basic.fundamental] p1: 16466 // Plain char, signed char, and unsigned char are three distinct types. 16467 // 16468 // But we treat plain `char' as equivalent to `signed char' or `unsigned 16469 // char' depending on the current char signedness mode. 16470 if (mismatch) 16471 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 16472 RequiredType->getPointeeType())) || 16473 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 16474 mismatch = false; 16475 } else 16476 if (IsPointerAttr) 16477 mismatch = !isLayoutCompatible(Context, 16478 ArgumentType->getPointeeType(), 16479 RequiredType->getPointeeType()); 16480 else 16481 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 16482 16483 if (mismatch) 16484 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 16485 << ArgumentType << ArgumentKind 16486 << TypeInfo.LayoutCompatible << RequiredType 16487 << ArgumentExpr->getSourceRange() 16488 << TypeTagExpr->getSourceRange(); 16489 } 16490 16491 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 16492 CharUnits Alignment) { 16493 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 16494 } 16495 16496 void Sema::DiagnoseMisalignedMembers() { 16497 for (MisalignedMember &m : MisalignedMembers) { 16498 const NamedDecl *ND = m.RD; 16499 if (ND->getName().empty()) { 16500 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 16501 ND = TD; 16502 } 16503 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 16504 << m.MD << ND << m.E->getSourceRange(); 16505 } 16506 MisalignedMembers.clear(); 16507 } 16508 16509 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 16510 E = E->IgnoreParens(); 16511 if (!T->isPointerType() && !T->isIntegerType()) 16512 return; 16513 if (isa<UnaryOperator>(E) && 16514 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 16515 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 16516 if (isa<MemberExpr>(Op)) { 16517 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 16518 if (MA != MisalignedMembers.end() && 16519 (T->isIntegerType() || 16520 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 16521 Context.getTypeAlignInChars( 16522 T->getPointeeType()) <= MA->Alignment)))) 16523 MisalignedMembers.erase(MA); 16524 } 16525 } 16526 } 16527 16528 void Sema::RefersToMemberWithReducedAlignment( 16529 Expr *E, 16530 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 16531 Action) { 16532 const auto *ME = dyn_cast<MemberExpr>(E); 16533 if (!ME) 16534 return; 16535 16536 // No need to check expressions with an __unaligned-qualified type. 16537 if (E->getType().getQualifiers().hasUnaligned()) 16538 return; 16539 16540 // For a chain of MemberExpr like "a.b.c.d" this list 16541 // will keep FieldDecl's like [d, c, b]. 16542 SmallVector<FieldDecl *, 4> ReverseMemberChain; 16543 const MemberExpr *TopME = nullptr; 16544 bool AnyIsPacked = false; 16545 do { 16546 QualType BaseType = ME->getBase()->getType(); 16547 if (BaseType->isDependentType()) 16548 return; 16549 if (ME->isArrow()) 16550 BaseType = BaseType->getPointeeType(); 16551 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 16552 if (RD->isInvalidDecl()) 16553 return; 16554 16555 ValueDecl *MD = ME->getMemberDecl(); 16556 auto *FD = dyn_cast<FieldDecl>(MD); 16557 // We do not care about non-data members. 16558 if (!FD || FD->isInvalidDecl()) 16559 return; 16560 16561 AnyIsPacked = 16562 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 16563 ReverseMemberChain.push_back(FD); 16564 16565 TopME = ME; 16566 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 16567 } while (ME); 16568 assert(TopME && "We did not compute a topmost MemberExpr!"); 16569 16570 // Not the scope of this diagnostic. 16571 if (!AnyIsPacked) 16572 return; 16573 16574 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 16575 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 16576 // TODO: The innermost base of the member expression may be too complicated. 16577 // For now, just disregard these cases. This is left for future 16578 // improvement. 16579 if (!DRE && !isa<CXXThisExpr>(TopBase)) 16580 return; 16581 16582 // Alignment expected by the whole expression. 16583 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 16584 16585 // No need to do anything else with this case. 16586 if (ExpectedAlignment.isOne()) 16587 return; 16588 16589 // Synthesize offset of the whole access. 16590 CharUnits Offset; 16591 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 16592 I++) { 16593 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 16594 } 16595 16596 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 16597 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 16598 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 16599 16600 // The base expression of the innermost MemberExpr may give 16601 // stronger guarantees than the class containing the member. 16602 if (DRE && !TopME->isArrow()) { 16603 const ValueDecl *VD = DRE->getDecl(); 16604 if (!VD->getType()->isReferenceType()) 16605 CompleteObjectAlignment = 16606 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 16607 } 16608 16609 // Check if the synthesized offset fulfills the alignment. 16610 if (Offset % ExpectedAlignment != 0 || 16611 // It may fulfill the offset it but the effective alignment may still be 16612 // lower than the expected expression alignment. 16613 CompleteObjectAlignment < ExpectedAlignment) { 16614 // If this happens, we want to determine a sensible culprit of this. 16615 // Intuitively, watching the chain of member expressions from right to 16616 // left, we start with the required alignment (as required by the field 16617 // type) but some packed attribute in that chain has reduced the alignment. 16618 // It may happen that another packed structure increases it again. But if 16619 // we are here such increase has not been enough. So pointing the first 16620 // FieldDecl that either is packed or else its RecordDecl is, 16621 // seems reasonable. 16622 FieldDecl *FD = nullptr; 16623 CharUnits Alignment; 16624 for (FieldDecl *FDI : ReverseMemberChain) { 16625 if (FDI->hasAttr<PackedAttr>() || 16626 FDI->getParent()->hasAttr<PackedAttr>()) { 16627 FD = FDI; 16628 Alignment = std::min( 16629 Context.getTypeAlignInChars(FD->getType()), 16630 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 16631 break; 16632 } 16633 } 16634 assert(FD && "We did not find a packed FieldDecl!"); 16635 Action(E, FD->getParent(), FD, Alignment); 16636 } 16637 } 16638 16639 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 16640 using namespace std::placeholders; 16641 16642 RefersToMemberWithReducedAlignment( 16643 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 16644 _2, _3, _4)); 16645 } 16646 16647 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 16648 ExprResult CallResult) { 16649 if (checkArgCount(*this, TheCall, 1)) 16650 return ExprError(); 16651 16652 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 16653 if (MatrixArg.isInvalid()) 16654 return MatrixArg; 16655 Expr *Matrix = MatrixArg.get(); 16656 16657 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 16658 if (!MType) { 16659 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 16660 return ExprError(); 16661 } 16662 16663 // Create returned matrix type by swapping rows and columns of the argument 16664 // matrix type. 16665 QualType ResultType = Context.getConstantMatrixType( 16666 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 16667 16668 // Change the return type to the type of the returned matrix. 16669 TheCall->setType(ResultType); 16670 16671 // Update call argument to use the possibly converted matrix argument. 16672 TheCall->setArg(0, Matrix); 16673 return CallResult; 16674 } 16675 16676 // Get and verify the matrix dimensions. 16677 static llvm::Optional<unsigned> 16678 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 16679 SourceLocation ErrorPos; 16680 Optional<llvm::APSInt> Value = 16681 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 16682 if (!Value) { 16683 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 16684 << Name; 16685 return {}; 16686 } 16687 uint64_t Dim = Value->getZExtValue(); 16688 if (!ConstantMatrixType::isDimensionValid(Dim)) { 16689 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 16690 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 16691 return {}; 16692 } 16693 return Dim; 16694 } 16695 16696 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 16697 ExprResult CallResult) { 16698 if (!getLangOpts().MatrixTypes) { 16699 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 16700 return ExprError(); 16701 } 16702 16703 if (checkArgCount(*this, TheCall, 4)) 16704 return ExprError(); 16705 16706 unsigned PtrArgIdx = 0; 16707 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16708 Expr *RowsExpr = TheCall->getArg(1); 16709 Expr *ColumnsExpr = TheCall->getArg(2); 16710 Expr *StrideExpr = TheCall->getArg(3); 16711 16712 bool ArgError = false; 16713 16714 // Check pointer argument. 16715 { 16716 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16717 if (PtrConv.isInvalid()) 16718 return PtrConv; 16719 PtrExpr = PtrConv.get(); 16720 TheCall->setArg(0, PtrExpr); 16721 if (PtrExpr->isTypeDependent()) { 16722 TheCall->setType(Context.DependentTy); 16723 return TheCall; 16724 } 16725 } 16726 16727 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16728 QualType ElementTy; 16729 if (!PtrTy) { 16730 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16731 << PtrArgIdx + 1; 16732 ArgError = true; 16733 } else { 16734 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 16735 16736 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 16737 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16738 << PtrArgIdx + 1; 16739 ArgError = true; 16740 } 16741 } 16742 16743 // Apply default Lvalue conversions and convert the expression to size_t. 16744 auto ApplyArgumentConversions = [this](Expr *E) { 16745 ExprResult Conv = DefaultLvalueConversion(E); 16746 if (Conv.isInvalid()) 16747 return Conv; 16748 16749 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 16750 }; 16751 16752 // Apply conversion to row and column expressions. 16753 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 16754 if (!RowsConv.isInvalid()) { 16755 RowsExpr = RowsConv.get(); 16756 TheCall->setArg(1, RowsExpr); 16757 } else 16758 RowsExpr = nullptr; 16759 16760 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 16761 if (!ColumnsConv.isInvalid()) { 16762 ColumnsExpr = ColumnsConv.get(); 16763 TheCall->setArg(2, ColumnsExpr); 16764 } else 16765 ColumnsExpr = nullptr; 16766 16767 // If any any part of the result matrix type is still pending, just use 16768 // Context.DependentTy, until all parts are resolved. 16769 if ((RowsExpr && RowsExpr->isTypeDependent()) || 16770 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 16771 TheCall->setType(Context.DependentTy); 16772 return CallResult; 16773 } 16774 16775 // Check row and column dimensions. 16776 llvm::Optional<unsigned> MaybeRows; 16777 if (RowsExpr) 16778 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 16779 16780 llvm::Optional<unsigned> MaybeColumns; 16781 if (ColumnsExpr) 16782 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 16783 16784 // Check stride argument. 16785 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 16786 if (StrideConv.isInvalid()) 16787 return ExprError(); 16788 StrideExpr = StrideConv.get(); 16789 TheCall->setArg(3, StrideExpr); 16790 16791 if (MaybeRows) { 16792 if (Optional<llvm::APSInt> Value = 16793 StrideExpr->getIntegerConstantExpr(Context)) { 16794 uint64_t Stride = Value->getZExtValue(); 16795 if (Stride < *MaybeRows) { 16796 Diag(StrideExpr->getBeginLoc(), 16797 diag::err_builtin_matrix_stride_too_small); 16798 ArgError = true; 16799 } 16800 } 16801 } 16802 16803 if (ArgError || !MaybeRows || !MaybeColumns) 16804 return ExprError(); 16805 16806 TheCall->setType( 16807 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 16808 return CallResult; 16809 } 16810 16811 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 16812 ExprResult CallResult) { 16813 if (checkArgCount(*this, TheCall, 3)) 16814 return ExprError(); 16815 16816 unsigned PtrArgIdx = 1; 16817 Expr *MatrixExpr = TheCall->getArg(0); 16818 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 16819 Expr *StrideExpr = TheCall->getArg(2); 16820 16821 bool ArgError = false; 16822 16823 { 16824 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 16825 if (MatrixConv.isInvalid()) 16826 return MatrixConv; 16827 MatrixExpr = MatrixConv.get(); 16828 TheCall->setArg(0, MatrixExpr); 16829 } 16830 if (MatrixExpr->isTypeDependent()) { 16831 TheCall->setType(Context.DependentTy); 16832 return TheCall; 16833 } 16834 16835 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 16836 if (!MatrixTy) { 16837 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 16838 ArgError = true; 16839 } 16840 16841 { 16842 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 16843 if (PtrConv.isInvalid()) 16844 return PtrConv; 16845 PtrExpr = PtrConv.get(); 16846 TheCall->setArg(1, PtrExpr); 16847 if (PtrExpr->isTypeDependent()) { 16848 TheCall->setType(Context.DependentTy); 16849 return TheCall; 16850 } 16851 } 16852 16853 // Check pointer argument. 16854 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 16855 if (!PtrTy) { 16856 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 16857 << PtrArgIdx + 1; 16858 ArgError = true; 16859 } else { 16860 QualType ElementTy = PtrTy->getPointeeType(); 16861 if (ElementTy.isConstQualified()) { 16862 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 16863 ArgError = true; 16864 } 16865 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 16866 if (MatrixTy && 16867 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 16868 Diag(PtrExpr->getBeginLoc(), 16869 diag::err_builtin_matrix_pointer_arg_mismatch) 16870 << ElementTy << MatrixTy->getElementType(); 16871 ArgError = true; 16872 } 16873 } 16874 16875 // Apply default Lvalue conversions and convert the stride expression to 16876 // size_t. 16877 { 16878 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 16879 if (StrideConv.isInvalid()) 16880 return StrideConv; 16881 16882 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 16883 if (StrideConv.isInvalid()) 16884 return StrideConv; 16885 StrideExpr = StrideConv.get(); 16886 TheCall->setArg(2, StrideExpr); 16887 } 16888 16889 // Check stride argument. 16890 if (MatrixTy) { 16891 if (Optional<llvm::APSInt> Value = 16892 StrideExpr->getIntegerConstantExpr(Context)) { 16893 uint64_t Stride = Value->getZExtValue(); 16894 if (Stride < MatrixTy->getNumRows()) { 16895 Diag(StrideExpr->getBeginLoc(), 16896 diag::err_builtin_matrix_stride_too_small); 16897 ArgError = true; 16898 } 16899 } 16900 } 16901 16902 if (ArgError) 16903 return ExprError(); 16904 16905 return CallResult; 16906 } 16907 16908 /// \brief Enforce the bounds of a TCB 16909 /// CheckTCBEnforcement - Enforces that every function in a named TCB only 16910 /// directly calls other functions in the same TCB as marked by the enforce_tcb 16911 /// and enforce_tcb_leaf attributes. 16912 void Sema::CheckTCBEnforcement(const CallExpr *TheCall, 16913 const FunctionDecl *Callee) { 16914 const FunctionDecl *Caller = getCurFunctionDecl(); 16915 16916 // Calls to builtins are not enforced. 16917 if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() || 16918 Callee->getBuiltinID() != 0) 16919 return; 16920 16921 // Search through the enforce_tcb and enforce_tcb_leaf attributes to find 16922 // all TCBs the callee is a part of. 16923 llvm::StringSet<> CalleeTCBs; 16924 for_each(Callee->specific_attrs<EnforceTCBAttr>(), 16925 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16926 for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(), 16927 [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); }); 16928 16929 // Go through the TCBs the caller is a part of and emit warnings if Caller 16930 // is in a TCB that the Callee is not. 16931 for_each( 16932 Caller->specific_attrs<EnforceTCBAttr>(), 16933 [&](const auto *A) { 16934 StringRef CallerTCB = A->getTCBName(); 16935 if (CalleeTCBs.count(CallerTCB) == 0) { 16936 this->Diag(TheCall->getExprLoc(), 16937 diag::warn_tcb_enforcement_violation) << Callee 16938 << CallerTCB; 16939 } 16940 }); 16941 } 16942