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/StringSwitch.h" 79 #include "llvm/ADT/Triple.h" 80 #include "llvm/Support/AtomicOrdering.h" 81 #include "llvm/Support/Casting.h" 82 #include "llvm/Support/Compiler.h" 83 #include "llvm/Support/ConvertUTF.h" 84 #include "llvm/Support/ErrorHandling.h" 85 #include "llvm/Support/Format.h" 86 #include "llvm/Support/Locale.h" 87 #include "llvm/Support/MathExtras.h" 88 #include "llvm/Support/SaveAndRestore.h" 89 #include "llvm/Support/raw_ostream.h" 90 #include <algorithm> 91 #include <bitset> 92 #include <cassert> 93 #include <cstddef> 94 #include <cstdint> 95 #include <functional> 96 #include <limits> 97 #include <string> 98 #include <tuple> 99 #include <utility> 100 101 using namespace clang; 102 using namespace sema; 103 104 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 105 unsigned ByteNo) const { 106 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 107 Context.getTargetInfo()); 108 } 109 110 /// Checks that a call expression's argument count is the desired number. 111 /// This is useful when doing custom type-checking. Returns true on error. 112 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 113 unsigned argCount = call->getNumArgs(); 114 if (argCount == desiredArgCount) return false; 115 116 if (argCount < desiredArgCount) 117 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 118 << 0 /*function call*/ << desiredArgCount << argCount 119 << call->getSourceRange(); 120 121 // Highlight all the excess arguments. 122 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 123 call->getArg(argCount - 1)->getEndLoc()); 124 125 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 126 << 0 /*function call*/ << desiredArgCount << argCount 127 << call->getArg(1)->getSourceRange(); 128 } 129 130 /// Check that the first argument to __builtin_annotation is an integer 131 /// and the second argument is a non-wide string literal. 132 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 133 if (checkArgCount(S, TheCall, 2)) 134 return true; 135 136 // First argument should be an integer. 137 Expr *ValArg = TheCall->getArg(0); 138 QualType Ty = ValArg->getType(); 139 if (!Ty->isIntegerType()) { 140 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 141 << ValArg->getSourceRange(); 142 return true; 143 } 144 145 // Second argument should be a constant string. 146 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 147 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 148 if (!Literal || !Literal->isAscii()) { 149 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 150 << StrArg->getSourceRange(); 151 return true; 152 } 153 154 TheCall->setType(Ty); 155 return false; 156 } 157 158 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 159 // We need at least one argument. 160 if (TheCall->getNumArgs() < 1) { 161 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 162 << 0 << 1 << TheCall->getNumArgs() 163 << TheCall->getCallee()->getSourceRange(); 164 return true; 165 } 166 167 // All arguments should be wide string literals. 168 for (Expr *Arg : TheCall->arguments()) { 169 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 170 if (!Literal || !Literal->isWide()) { 171 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 172 << Arg->getSourceRange(); 173 return true; 174 } 175 } 176 177 return false; 178 } 179 180 /// Check that the argument to __builtin_addressof is a glvalue, and set the 181 /// result type to the corresponding pointer type. 182 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 183 if (checkArgCount(S, TheCall, 1)) 184 return true; 185 186 ExprResult Arg(TheCall->getArg(0)); 187 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 188 if (ResultType.isNull()) 189 return true; 190 191 TheCall->setArg(0, Arg.get()); 192 TheCall->setType(ResultType); 193 return false; 194 } 195 196 /// Check the number of arguments and set the result type to 197 /// the argument type. 198 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 199 if (checkArgCount(S, TheCall, 1)) 200 return true; 201 202 TheCall->setType(TheCall->getArg(0)->getType()); 203 return false; 204 } 205 206 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 207 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 208 /// type (but not a function pointer) and that the alignment is a power-of-two. 209 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 210 if (checkArgCount(S, TheCall, 2)) 211 return true; 212 213 clang::Expr *Source = TheCall->getArg(0); 214 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 215 216 auto IsValidIntegerType = [](QualType Ty) { 217 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 218 }; 219 QualType SrcTy = Source->getType(); 220 // We should also be able to use it with arrays (but not functions!). 221 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 222 SrcTy = S.Context.getDecayedType(SrcTy); 223 } 224 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 225 SrcTy->isFunctionPointerType()) { 226 // FIXME: this is not quite the right error message since we don't allow 227 // floating point types, or member pointers. 228 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 229 << SrcTy; 230 return true; 231 } 232 233 clang::Expr *AlignOp = TheCall->getArg(1); 234 if (!IsValidIntegerType(AlignOp->getType())) { 235 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 236 << AlignOp->getType(); 237 return true; 238 } 239 Expr::EvalResult AlignResult; 240 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 241 // We can't check validity of alignment if it is value dependent. 242 if (!AlignOp->isValueDependent() && 243 AlignOp->EvaluateAsInt(AlignResult, S.Context, 244 Expr::SE_AllowSideEffects)) { 245 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 246 llvm::APSInt MaxValue( 247 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 248 if (AlignValue < 1) { 249 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 250 return true; 251 } 252 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 253 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 254 << MaxValue.toString(10); 255 return true; 256 } 257 if (!AlignValue.isPowerOf2()) { 258 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 259 return true; 260 } 261 if (AlignValue == 1) { 262 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 263 << IsBooleanAlignBuiltin; 264 } 265 } 266 267 ExprResult SrcArg = S.PerformCopyInitialization( 268 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 269 SourceLocation(), Source); 270 if (SrcArg.isInvalid()) 271 return true; 272 TheCall->setArg(0, SrcArg.get()); 273 ExprResult AlignArg = 274 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 275 S.Context, AlignOp->getType(), false), 276 SourceLocation(), AlignOp); 277 if (AlignArg.isInvalid()) 278 return true; 279 TheCall->setArg(1, AlignArg.get()); 280 // For align_up/align_down, the return type is the same as the (potentially 281 // decayed) argument type including qualifiers. For is_aligned(), the result 282 // is always bool. 283 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 284 return false; 285 } 286 287 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 288 unsigned BuiltinID) { 289 if (checkArgCount(S, TheCall, 3)) 290 return true; 291 292 // First two arguments should be integers. 293 for (unsigned I = 0; I < 2; ++I) { 294 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 295 if (Arg.isInvalid()) return true; 296 TheCall->setArg(I, Arg.get()); 297 298 QualType Ty = Arg.get()->getType(); 299 if (!Ty->isIntegerType()) { 300 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 301 << Ty << Arg.get()->getSourceRange(); 302 return true; 303 } 304 } 305 306 // Third argument should be a pointer to a non-const integer. 307 // IRGen correctly handles volatile, restrict, and address spaces, and 308 // the other qualifiers aren't possible. 309 { 310 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 311 if (Arg.isInvalid()) return true; 312 TheCall->setArg(2, Arg.get()); 313 314 QualType Ty = Arg.get()->getType(); 315 const auto *PtrTy = Ty->getAs<PointerType>(); 316 if (!PtrTy || 317 !PtrTy->getPointeeType()->isIntegerType() || 318 PtrTy->getPointeeType().isConstQualified()) { 319 S.Diag(Arg.get()->getBeginLoc(), 320 diag::err_overflow_builtin_must_be_ptr_int) 321 << Ty << Arg.get()->getSourceRange(); 322 return true; 323 } 324 } 325 326 // Disallow signed ExtIntType args larger than 128 bits to mul function until 327 // we improve backend support. 328 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 329 for (unsigned I = 0; I < 3; ++I) { 330 const auto Arg = TheCall->getArg(I); 331 // Third argument will be a pointer. 332 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 333 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 334 S.getASTContext().getIntWidth(Ty) > 128) 335 return S.Diag(Arg->getBeginLoc(), 336 diag::err_overflow_builtin_ext_int_max_size) 337 << 128; 338 } 339 } 340 341 return false; 342 } 343 344 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 345 if (checkArgCount(S, BuiltinCall, 2)) 346 return true; 347 348 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 349 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 350 Expr *Call = BuiltinCall->getArg(0); 351 Expr *Chain = BuiltinCall->getArg(1); 352 353 if (Call->getStmtClass() != Stmt::CallExprClass) { 354 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 355 << Call->getSourceRange(); 356 return true; 357 } 358 359 auto CE = cast<CallExpr>(Call); 360 if (CE->getCallee()->getType()->isBlockPointerType()) { 361 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 362 << Call->getSourceRange(); 363 return true; 364 } 365 366 const Decl *TargetDecl = CE->getCalleeDecl(); 367 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 368 if (FD->getBuiltinID()) { 369 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 370 << Call->getSourceRange(); 371 return true; 372 } 373 374 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 375 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 376 << Call->getSourceRange(); 377 return true; 378 } 379 380 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 381 if (ChainResult.isInvalid()) 382 return true; 383 if (!ChainResult.get()->getType()->isPointerType()) { 384 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 385 << Chain->getSourceRange(); 386 return true; 387 } 388 389 QualType ReturnTy = CE->getCallReturnType(S.Context); 390 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 391 QualType BuiltinTy = S.Context.getFunctionType( 392 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 393 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 394 395 Builtin = 396 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 397 398 BuiltinCall->setType(CE->getType()); 399 BuiltinCall->setValueKind(CE->getValueKind()); 400 BuiltinCall->setObjectKind(CE->getObjectKind()); 401 BuiltinCall->setCallee(Builtin); 402 BuiltinCall->setArg(1, ChainResult.get()); 403 404 return false; 405 } 406 407 namespace { 408 409 class EstimateSizeFormatHandler 410 : public analyze_format_string::FormatStringHandler { 411 size_t Size; 412 413 public: 414 EstimateSizeFormatHandler(StringRef Format) 415 : Size(std::min(Format.find(0), Format.size()) + 416 1 /* null byte always written by sprintf */) {} 417 418 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 419 const char *, unsigned SpecifierLen) override { 420 421 const size_t FieldWidth = computeFieldWidth(FS); 422 const size_t Precision = computePrecision(FS); 423 424 // The actual format. 425 switch (FS.getConversionSpecifier().getKind()) { 426 // Just a char. 427 case analyze_format_string::ConversionSpecifier::cArg: 428 case analyze_format_string::ConversionSpecifier::CArg: 429 Size += std::max(FieldWidth, (size_t)1); 430 break; 431 // Just an integer. 432 case analyze_format_string::ConversionSpecifier::dArg: 433 case analyze_format_string::ConversionSpecifier::DArg: 434 case analyze_format_string::ConversionSpecifier::iArg: 435 case analyze_format_string::ConversionSpecifier::oArg: 436 case analyze_format_string::ConversionSpecifier::OArg: 437 case analyze_format_string::ConversionSpecifier::uArg: 438 case analyze_format_string::ConversionSpecifier::UArg: 439 case analyze_format_string::ConversionSpecifier::xArg: 440 case analyze_format_string::ConversionSpecifier::XArg: 441 Size += std::max(FieldWidth, Precision); 442 break; 443 444 // %g style conversion switches between %f or %e style dynamically. 445 // %f always takes less space, so default to it. 446 case analyze_format_string::ConversionSpecifier::gArg: 447 case analyze_format_string::ConversionSpecifier::GArg: 448 449 // Floating point number in the form '[+]ddd.ddd'. 450 case analyze_format_string::ConversionSpecifier::fArg: 451 case analyze_format_string::ConversionSpecifier::FArg: 452 Size += std::max(FieldWidth, 1 /* integer part */ + 453 (Precision ? 1 + Precision 454 : 0) /* period + decimal */); 455 break; 456 457 // Floating point number in the form '[-]d.ddde[+-]dd'. 458 case analyze_format_string::ConversionSpecifier::eArg: 459 case analyze_format_string::ConversionSpecifier::EArg: 460 Size += 461 std::max(FieldWidth, 462 1 /* integer part */ + 463 (Precision ? 1 + Precision : 0) /* period + decimal */ + 464 1 /* e or E letter */ + 2 /* exponent */); 465 break; 466 467 // Floating point number in the form '[-]0xh.hhhhp±dd'. 468 case analyze_format_string::ConversionSpecifier::aArg: 469 case analyze_format_string::ConversionSpecifier::AArg: 470 Size += 471 std::max(FieldWidth, 472 2 /* 0x */ + 1 /* integer part */ + 473 (Precision ? 1 + Precision : 0) /* period + decimal */ + 474 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 475 break; 476 477 // Just a string. 478 case analyze_format_string::ConversionSpecifier::sArg: 479 case analyze_format_string::ConversionSpecifier::SArg: 480 Size += FieldWidth; 481 break; 482 483 // Just a pointer in the form '0xddd'. 484 case analyze_format_string::ConversionSpecifier::pArg: 485 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 486 break; 487 488 // A plain percent. 489 case analyze_format_string::ConversionSpecifier::PercentArg: 490 Size += 1; 491 break; 492 493 default: 494 break; 495 } 496 497 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 498 499 if (FS.hasAlternativeForm()) { 500 switch (FS.getConversionSpecifier().getKind()) { 501 default: 502 break; 503 // Force a leading '0'. 504 case analyze_format_string::ConversionSpecifier::oArg: 505 Size += 1; 506 break; 507 // Force a leading '0x'. 508 case analyze_format_string::ConversionSpecifier::xArg: 509 case analyze_format_string::ConversionSpecifier::XArg: 510 Size += 2; 511 break; 512 // Force a period '.' before decimal, even if precision is 0. 513 case analyze_format_string::ConversionSpecifier::aArg: 514 case analyze_format_string::ConversionSpecifier::AArg: 515 case analyze_format_string::ConversionSpecifier::eArg: 516 case analyze_format_string::ConversionSpecifier::EArg: 517 case analyze_format_string::ConversionSpecifier::fArg: 518 case analyze_format_string::ConversionSpecifier::FArg: 519 case analyze_format_string::ConversionSpecifier::gArg: 520 case analyze_format_string::ConversionSpecifier::GArg: 521 Size += (Precision ? 0 : 1); 522 break; 523 } 524 } 525 assert(SpecifierLen <= Size && "no underflow"); 526 Size -= SpecifierLen; 527 return true; 528 } 529 530 size_t getSizeLowerBound() const { return Size; } 531 532 private: 533 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 534 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 535 size_t FieldWidth = 0; 536 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 537 FieldWidth = FW.getConstantAmount(); 538 return FieldWidth; 539 } 540 541 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 542 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 543 size_t Precision = 0; 544 545 // See man 3 printf for default precision value based on the specifier. 546 switch (FW.getHowSpecified()) { 547 case analyze_format_string::OptionalAmount::NotSpecified: 548 switch (FS.getConversionSpecifier().getKind()) { 549 default: 550 break; 551 case analyze_format_string::ConversionSpecifier::dArg: // %d 552 case analyze_format_string::ConversionSpecifier::DArg: // %D 553 case analyze_format_string::ConversionSpecifier::iArg: // %i 554 Precision = 1; 555 break; 556 case analyze_format_string::ConversionSpecifier::oArg: // %d 557 case analyze_format_string::ConversionSpecifier::OArg: // %D 558 case analyze_format_string::ConversionSpecifier::uArg: // %d 559 case analyze_format_string::ConversionSpecifier::UArg: // %D 560 case analyze_format_string::ConversionSpecifier::xArg: // %d 561 case analyze_format_string::ConversionSpecifier::XArg: // %D 562 Precision = 1; 563 break; 564 case analyze_format_string::ConversionSpecifier::fArg: // %f 565 case analyze_format_string::ConversionSpecifier::FArg: // %F 566 case analyze_format_string::ConversionSpecifier::eArg: // %e 567 case analyze_format_string::ConversionSpecifier::EArg: // %E 568 case analyze_format_string::ConversionSpecifier::gArg: // %g 569 case analyze_format_string::ConversionSpecifier::GArg: // %G 570 Precision = 6; 571 break; 572 case analyze_format_string::ConversionSpecifier::pArg: // %d 573 Precision = 1; 574 break; 575 } 576 break; 577 case analyze_format_string::OptionalAmount::Constant: 578 Precision = FW.getConstantAmount(); 579 break; 580 default: 581 break; 582 } 583 return Precision; 584 } 585 }; 586 587 } // namespace 588 589 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 590 /// __builtin_*_chk function, then use the object size argument specified in the 591 /// source. Otherwise, infer the object size using __builtin_object_size. 592 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 593 CallExpr *TheCall) { 594 // FIXME: There are some more useful checks we could be doing here: 595 // - Evaluate strlen of strcpy arguments, use as object size. 596 597 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 598 isConstantEvaluated()) 599 return; 600 601 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 602 if (!BuiltinID) 603 return; 604 605 const TargetInfo &TI = getASTContext().getTargetInfo(); 606 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 607 608 unsigned DiagID = 0; 609 bool IsChkVariant = false; 610 Optional<llvm::APSInt> UsedSize; 611 unsigned SizeIndex, ObjectIndex; 612 switch (BuiltinID) { 613 default: 614 return; 615 case Builtin::BIsprintf: 616 case Builtin::BI__builtin___sprintf_chk: { 617 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 618 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 619 620 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 621 622 if (!Format->isAscii() && !Format->isUTF8()) 623 return; 624 625 StringRef FormatStrRef = Format->getString(); 626 EstimateSizeFormatHandler H(FormatStrRef); 627 const char *FormatBytes = FormatStrRef.data(); 628 const ConstantArrayType *T = 629 Context.getAsConstantArrayType(Format->getType()); 630 assert(T && "String literal not of constant array type!"); 631 size_t TypeSize = T->getSize().getZExtValue(); 632 633 // In case there's a null byte somewhere. 634 size_t StrLen = 635 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 636 if (!analyze_format_string::ParsePrintfString( 637 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 638 Context.getTargetInfo(), false)) { 639 DiagID = diag::warn_fortify_source_format_overflow; 640 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 641 .extOrTrunc(SizeTypeWidth); 642 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 643 IsChkVariant = true; 644 ObjectIndex = 2; 645 } else { 646 IsChkVariant = false; 647 ObjectIndex = 0; 648 } 649 break; 650 } 651 } 652 return; 653 } 654 case Builtin::BI__builtin___memcpy_chk: 655 case Builtin::BI__builtin___memmove_chk: 656 case Builtin::BI__builtin___memset_chk: 657 case Builtin::BI__builtin___strlcat_chk: 658 case Builtin::BI__builtin___strlcpy_chk: 659 case Builtin::BI__builtin___strncat_chk: 660 case Builtin::BI__builtin___strncpy_chk: 661 case Builtin::BI__builtin___stpncpy_chk: 662 case Builtin::BI__builtin___memccpy_chk: 663 case Builtin::BI__builtin___mempcpy_chk: { 664 DiagID = diag::warn_builtin_chk_overflow; 665 IsChkVariant = true; 666 SizeIndex = TheCall->getNumArgs() - 2; 667 ObjectIndex = TheCall->getNumArgs() - 1; 668 break; 669 } 670 671 case Builtin::BI__builtin___snprintf_chk: 672 case Builtin::BI__builtin___vsnprintf_chk: { 673 DiagID = diag::warn_builtin_chk_overflow; 674 IsChkVariant = true; 675 SizeIndex = 1; 676 ObjectIndex = 3; 677 break; 678 } 679 680 case Builtin::BIstrncat: 681 case Builtin::BI__builtin_strncat: 682 case Builtin::BIstrncpy: 683 case Builtin::BI__builtin_strncpy: 684 case Builtin::BIstpncpy: 685 case Builtin::BI__builtin_stpncpy: { 686 // Whether these functions overflow depends on the runtime strlen of the 687 // string, not just the buffer size, so emitting the "always overflow" 688 // diagnostic isn't quite right. We should still diagnose passing a buffer 689 // size larger than the destination buffer though; this is a runtime abort 690 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 691 DiagID = diag::warn_fortify_source_size_mismatch; 692 SizeIndex = TheCall->getNumArgs() - 1; 693 ObjectIndex = 0; 694 break; 695 } 696 697 case Builtin::BImemcpy: 698 case Builtin::BI__builtin_memcpy: 699 case Builtin::BImemmove: 700 case Builtin::BI__builtin_memmove: 701 case Builtin::BImemset: 702 case Builtin::BI__builtin_memset: 703 case Builtin::BImempcpy: 704 case Builtin::BI__builtin_mempcpy: { 705 DiagID = diag::warn_fortify_source_overflow; 706 SizeIndex = TheCall->getNumArgs() - 1; 707 ObjectIndex = 0; 708 break; 709 } 710 case Builtin::BIsnprintf: 711 case Builtin::BI__builtin_snprintf: 712 case Builtin::BIvsnprintf: 713 case Builtin::BI__builtin_vsnprintf: { 714 DiagID = diag::warn_fortify_source_size_mismatch; 715 SizeIndex = 1; 716 ObjectIndex = 0; 717 break; 718 } 719 } 720 721 llvm::APSInt ObjectSize; 722 // For __builtin___*_chk, the object size is explicitly provided by the caller 723 // (usually using __builtin_object_size). Use that value to check this call. 724 if (IsChkVariant) { 725 Expr::EvalResult Result; 726 Expr *SizeArg = TheCall->getArg(ObjectIndex); 727 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 728 return; 729 ObjectSize = Result.Val.getInt(); 730 731 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 732 } else { 733 // If the parameter has a pass_object_size attribute, then we should use its 734 // (potentially) more strict checking mode. Otherwise, conservatively assume 735 // type 0. 736 int BOSType = 0; 737 if (const auto *POS = 738 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 739 BOSType = POS->getType(); 740 741 Expr *ObjArg = TheCall->getArg(ObjectIndex); 742 uint64_t Result; 743 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 744 return; 745 // Get the object size in the target's size_t width. 746 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 747 } 748 749 // Evaluate the number of bytes of the object that this call will use. 750 if (!UsedSize) { 751 Expr::EvalResult Result; 752 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 753 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 754 return; 755 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 756 } 757 758 if (UsedSize.getValue().ule(ObjectSize)) 759 return; 760 761 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 762 // Skim off the details of whichever builtin was called to produce a better 763 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 764 if (IsChkVariant) { 765 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 766 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 767 } else if (FunctionName.startswith("__builtin_")) { 768 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 769 } 770 771 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 772 PDiag(DiagID) 773 << FunctionName << ObjectSize.toString(/*Radix=*/10) 774 << UsedSize.getValue().toString(/*Radix=*/10)); 775 } 776 777 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 778 Scope::ScopeFlags NeededScopeFlags, 779 unsigned DiagID) { 780 // Scopes aren't available during instantiation. Fortunately, builtin 781 // functions cannot be template args so they cannot be formed through template 782 // instantiation. Therefore checking once during the parse is sufficient. 783 if (SemaRef.inTemplateInstantiation()) 784 return false; 785 786 Scope *S = SemaRef.getCurScope(); 787 while (S && !S->isSEHExceptScope()) 788 S = S->getParent(); 789 if (!S || !(S->getFlags() & NeededScopeFlags)) { 790 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 791 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 792 << DRE->getDecl()->getIdentifier(); 793 return true; 794 } 795 796 return false; 797 } 798 799 static inline bool isBlockPointer(Expr *Arg) { 800 return Arg->getType()->isBlockPointerType(); 801 } 802 803 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 804 /// void*, which is a requirement of device side enqueue. 805 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 806 const BlockPointerType *BPT = 807 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 808 ArrayRef<QualType> Params = 809 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 810 unsigned ArgCounter = 0; 811 bool IllegalParams = false; 812 // Iterate through the block parameters until either one is found that is not 813 // a local void*, or the block is valid. 814 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 815 I != E; ++I, ++ArgCounter) { 816 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 817 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 818 LangAS::opencl_local) { 819 // Get the location of the error. If a block literal has been passed 820 // (BlockExpr) then we can point straight to the offending argument, 821 // else we just point to the variable reference. 822 SourceLocation ErrorLoc; 823 if (isa<BlockExpr>(BlockArg)) { 824 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 825 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 826 } else if (isa<DeclRefExpr>(BlockArg)) { 827 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 828 } 829 S.Diag(ErrorLoc, 830 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 831 IllegalParams = true; 832 } 833 } 834 835 return IllegalParams; 836 } 837 838 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 839 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 840 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 841 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 842 return true; 843 } 844 return false; 845 } 846 847 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 848 if (checkArgCount(S, TheCall, 2)) 849 return true; 850 851 if (checkOpenCLSubgroupExt(S, TheCall)) 852 return true; 853 854 // First argument is an ndrange_t type. 855 Expr *NDRangeArg = TheCall->getArg(0); 856 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 857 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 858 << TheCall->getDirectCallee() << "'ndrange_t'"; 859 return true; 860 } 861 862 Expr *BlockArg = TheCall->getArg(1); 863 if (!isBlockPointer(BlockArg)) { 864 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 865 << TheCall->getDirectCallee() << "block"; 866 return true; 867 } 868 return checkOpenCLBlockArgs(S, BlockArg); 869 } 870 871 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 872 /// get_kernel_work_group_size 873 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 874 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 875 if (checkArgCount(S, TheCall, 1)) 876 return true; 877 878 Expr *BlockArg = TheCall->getArg(0); 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 /// Diagnose integer type and any valid implicit conversion to it. 888 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 889 const QualType &IntType); 890 891 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 892 unsigned Start, unsigned End) { 893 bool IllegalParams = false; 894 for (unsigned I = Start; I <= End; ++I) 895 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 896 S.Context.getSizeType()); 897 return IllegalParams; 898 } 899 900 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 901 /// 'local void*' parameter of passed block. 902 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 903 Expr *BlockArg, 904 unsigned NumNonVarArgs) { 905 const BlockPointerType *BPT = 906 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 907 unsigned NumBlockParams = 908 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 909 unsigned TotalNumArgs = TheCall->getNumArgs(); 910 911 // For each argument passed to the block, a corresponding uint needs to 912 // be passed to describe the size of the local memory. 913 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 914 S.Diag(TheCall->getBeginLoc(), 915 diag::err_opencl_enqueue_kernel_local_size_args); 916 return true; 917 } 918 919 // Check that the sizes of the local memory are specified by integers. 920 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 921 TotalNumArgs - 1); 922 } 923 924 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 925 /// overload formats specified in Table 6.13.17.1. 926 /// int enqueue_kernel(queue_t queue, 927 /// kernel_enqueue_flags_t flags, 928 /// const ndrange_t ndrange, 929 /// void (^block)(void)) 930 /// int enqueue_kernel(queue_t queue, 931 /// kernel_enqueue_flags_t flags, 932 /// const ndrange_t ndrange, 933 /// uint num_events_in_wait_list, 934 /// clk_event_t *event_wait_list, 935 /// clk_event_t *event_ret, 936 /// void (^block)(void)) 937 /// int enqueue_kernel(queue_t queue, 938 /// kernel_enqueue_flags_t flags, 939 /// const ndrange_t ndrange, 940 /// void (^block)(local void*, ...), 941 /// uint size0, ...) 942 /// int enqueue_kernel(queue_t queue, 943 /// kernel_enqueue_flags_t flags, 944 /// const ndrange_t ndrange, 945 /// uint num_events_in_wait_list, 946 /// clk_event_t *event_wait_list, 947 /// clk_event_t *event_ret, 948 /// void (^block)(local void*, ...), 949 /// uint size0, ...) 950 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 951 unsigned NumArgs = TheCall->getNumArgs(); 952 953 if (NumArgs < 4) { 954 S.Diag(TheCall->getBeginLoc(), 955 diag::err_typecheck_call_too_few_args_at_least) 956 << 0 << 4 << NumArgs; 957 return true; 958 } 959 960 Expr *Arg0 = TheCall->getArg(0); 961 Expr *Arg1 = TheCall->getArg(1); 962 Expr *Arg2 = TheCall->getArg(2); 963 Expr *Arg3 = TheCall->getArg(3); 964 965 // First argument always needs to be a queue_t type. 966 if (!Arg0->getType()->isQueueT()) { 967 S.Diag(TheCall->getArg(0)->getBeginLoc(), 968 diag::err_opencl_builtin_expected_type) 969 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 970 return true; 971 } 972 973 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 974 if (!Arg1->getType()->isIntegerType()) { 975 S.Diag(TheCall->getArg(1)->getBeginLoc(), 976 diag::err_opencl_builtin_expected_type) 977 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 978 return true; 979 } 980 981 // Third argument is always an ndrange_t type. 982 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 983 S.Diag(TheCall->getArg(2)->getBeginLoc(), 984 diag::err_opencl_builtin_expected_type) 985 << TheCall->getDirectCallee() << "'ndrange_t'"; 986 return true; 987 } 988 989 // With four arguments, there is only one form that the function could be 990 // called in: no events and no variable arguments. 991 if (NumArgs == 4) { 992 // check that the last argument is the right block type. 993 if (!isBlockPointer(Arg3)) { 994 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 995 << TheCall->getDirectCallee() << "block"; 996 return true; 997 } 998 // we have a block type, check the prototype 999 const BlockPointerType *BPT = 1000 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1001 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1002 S.Diag(Arg3->getBeginLoc(), 1003 diag::err_opencl_enqueue_kernel_blocks_no_args); 1004 return true; 1005 } 1006 return false; 1007 } 1008 // we can have block + varargs. 1009 if (isBlockPointer(Arg3)) 1010 return (checkOpenCLBlockArgs(S, Arg3) || 1011 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1012 // last two cases with either exactly 7 args or 7 args and varargs. 1013 if (NumArgs >= 7) { 1014 // check common block argument. 1015 Expr *Arg6 = TheCall->getArg(6); 1016 if (!isBlockPointer(Arg6)) { 1017 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1018 << TheCall->getDirectCallee() << "block"; 1019 return true; 1020 } 1021 if (checkOpenCLBlockArgs(S, Arg6)) 1022 return true; 1023 1024 // Forth argument has to be any integer type. 1025 if (!Arg3->getType()->isIntegerType()) { 1026 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1027 diag::err_opencl_builtin_expected_type) 1028 << TheCall->getDirectCallee() << "integer"; 1029 return true; 1030 } 1031 // check remaining common arguments. 1032 Expr *Arg4 = TheCall->getArg(4); 1033 Expr *Arg5 = TheCall->getArg(5); 1034 1035 // Fifth argument is always passed as a pointer to clk_event_t. 1036 if (!Arg4->isNullPointerConstant(S.Context, 1037 Expr::NPC_ValueDependentIsNotNull) && 1038 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1039 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1040 diag::err_opencl_builtin_expected_type) 1041 << TheCall->getDirectCallee() 1042 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1043 return true; 1044 } 1045 1046 // Sixth argument is always passed as a pointer to clk_event_t. 1047 if (!Arg5->isNullPointerConstant(S.Context, 1048 Expr::NPC_ValueDependentIsNotNull) && 1049 !(Arg5->getType()->isPointerType() && 1050 Arg5->getType()->getPointeeType()->isClkEventT())) { 1051 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1052 diag::err_opencl_builtin_expected_type) 1053 << TheCall->getDirectCallee() 1054 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1055 return true; 1056 } 1057 1058 if (NumArgs == 7) 1059 return false; 1060 1061 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1062 } 1063 1064 // None of the specific case has been detected, give generic error 1065 S.Diag(TheCall->getBeginLoc(), 1066 diag::err_opencl_enqueue_kernel_incorrect_args); 1067 return true; 1068 } 1069 1070 /// Returns OpenCL access qual. 1071 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1072 return D->getAttr<OpenCLAccessAttr>(); 1073 } 1074 1075 /// Returns true if pipe element type is different from the pointer. 1076 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1077 const Expr *Arg0 = Call->getArg(0); 1078 // First argument type should always be pipe. 1079 if (!Arg0->getType()->isPipeType()) { 1080 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1081 << Call->getDirectCallee() << Arg0->getSourceRange(); 1082 return true; 1083 } 1084 OpenCLAccessAttr *AccessQual = 1085 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1086 // Validates the access qualifier is compatible with the call. 1087 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1088 // read_only and write_only, and assumed to be read_only if no qualifier is 1089 // specified. 1090 switch (Call->getDirectCallee()->getBuiltinID()) { 1091 case Builtin::BIread_pipe: 1092 case Builtin::BIreserve_read_pipe: 1093 case Builtin::BIcommit_read_pipe: 1094 case Builtin::BIwork_group_reserve_read_pipe: 1095 case Builtin::BIsub_group_reserve_read_pipe: 1096 case Builtin::BIwork_group_commit_read_pipe: 1097 case Builtin::BIsub_group_commit_read_pipe: 1098 if (!(!AccessQual || AccessQual->isReadOnly())) { 1099 S.Diag(Arg0->getBeginLoc(), 1100 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1101 << "read_only" << Arg0->getSourceRange(); 1102 return true; 1103 } 1104 break; 1105 case Builtin::BIwrite_pipe: 1106 case Builtin::BIreserve_write_pipe: 1107 case Builtin::BIcommit_write_pipe: 1108 case Builtin::BIwork_group_reserve_write_pipe: 1109 case Builtin::BIsub_group_reserve_write_pipe: 1110 case Builtin::BIwork_group_commit_write_pipe: 1111 case Builtin::BIsub_group_commit_write_pipe: 1112 if (!(AccessQual && AccessQual->isWriteOnly())) { 1113 S.Diag(Arg0->getBeginLoc(), 1114 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1115 << "write_only" << Arg0->getSourceRange(); 1116 return true; 1117 } 1118 break; 1119 default: 1120 break; 1121 } 1122 return false; 1123 } 1124 1125 /// Returns true if pipe element type is different from the pointer. 1126 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1127 const Expr *Arg0 = Call->getArg(0); 1128 const Expr *ArgIdx = Call->getArg(Idx); 1129 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1130 const QualType EltTy = PipeTy->getElementType(); 1131 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1132 // The Idx argument should be a pointer and the type of the pointer and 1133 // the type of pipe element should also be the same. 1134 if (!ArgTy || 1135 !S.Context.hasSameType( 1136 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1137 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1138 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1139 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1140 return true; 1141 } 1142 return false; 1143 } 1144 1145 // Performs semantic analysis for the read/write_pipe call. 1146 // \param S Reference to the semantic analyzer. 1147 // \param Call A pointer to the builtin call. 1148 // \return True if a semantic error has been found, false otherwise. 1149 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1150 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1151 // functions have two forms. 1152 switch (Call->getNumArgs()) { 1153 case 2: 1154 if (checkOpenCLPipeArg(S, Call)) 1155 return true; 1156 // The call with 2 arguments should be 1157 // read/write_pipe(pipe T, T*). 1158 // Check packet type T. 1159 if (checkOpenCLPipePacketType(S, Call, 1)) 1160 return true; 1161 break; 1162 1163 case 4: { 1164 if (checkOpenCLPipeArg(S, Call)) 1165 return true; 1166 // The call with 4 arguments should be 1167 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1168 // Check reserve_id_t. 1169 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1170 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1171 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1172 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1173 return true; 1174 } 1175 1176 // Check the index. 1177 const Expr *Arg2 = Call->getArg(2); 1178 if (!Arg2->getType()->isIntegerType() && 1179 !Arg2->getType()->isUnsignedIntegerType()) { 1180 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1181 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1182 << Arg2->getType() << Arg2->getSourceRange(); 1183 return true; 1184 } 1185 1186 // Check packet type T. 1187 if (checkOpenCLPipePacketType(S, Call, 3)) 1188 return true; 1189 } break; 1190 default: 1191 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1192 << Call->getDirectCallee() << Call->getSourceRange(); 1193 return true; 1194 } 1195 1196 return false; 1197 } 1198 1199 // Performs a semantic analysis on the {work_group_/sub_group_ 1200 // /_}reserve_{read/write}_pipe 1201 // \param S Reference to the semantic analyzer. 1202 // \param Call The call to the builtin function to be analyzed. 1203 // \return True if a semantic error was found, false otherwise. 1204 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1205 if (checkArgCount(S, Call, 2)) 1206 return true; 1207 1208 if (checkOpenCLPipeArg(S, Call)) 1209 return true; 1210 1211 // Check the reserve size. 1212 if (!Call->getArg(1)->getType()->isIntegerType() && 1213 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1214 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1215 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1216 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1217 return true; 1218 } 1219 1220 // Since return type of reserve_read/write_pipe built-in function is 1221 // reserve_id_t, which is not defined in the builtin def file , we used int 1222 // as return type and need to override the return type of these functions. 1223 Call->setType(S.Context.OCLReserveIDTy); 1224 1225 return false; 1226 } 1227 1228 // Performs a semantic analysis on {work_group_/sub_group_ 1229 // /_}commit_{read/write}_pipe 1230 // \param S Reference to the semantic analyzer. 1231 // \param Call The call to the builtin function to be analyzed. 1232 // \return True if a semantic error was found, false otherwise. 1233 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1234 if (checkArgCount(S, Call, 2)) 1235 return true; 1236 1237 if (checkOpenCLPipeArg(S, Call)) 1238 return true; 1239 1240 // Check reserve_id_t. 1241 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1242 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1243 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1244 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1245 return true; 1246 } 1247 1248 return false; 1249 } 1250 1251 // Performs a semantic analysis on the call to built-in Pipe 1252 // Query Functions. 1253 // \param S Reference to the semantic analyzer. 1254 // \param Call The call to the builtin function to be analyzed. 1255 // \return True if a semantic error was found, false otherwise. 1256 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1257 if (checkArgCount(S, Call, 1)) 1258 return true; 1259 1260 if (!Call->getArg(0)->getType()->isPipeType()) { 1261 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1262 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1263 return true; 1264 } 1265 1266 return false; 1267 } 1268 1269 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1270 // Performs semantic analysis for the to_global/local/private call. 1271 // \param S Reference to the semantic analyzer. 1272 // \param BuiltinID ID of the builtin function. 1273 // \param Call A pointer to the builtin call. 1274 // \return True if a semantic error has been found, false otherwise. 1275 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1276 CallExpr *Call) { 1277 if (Call->getNumArgs() != 1) { 1278 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 1279 << Call->getDirectCallee() << Call->getSourceRange(); 1280 return true; 1281 } 1282 1283 auto RT = Call->getArg(0)->getType(); 1284 if (!RT->isPointerType() || RT->getPointeeType() 1285 .getAddressSpace() == LangAS::opencl_constant) { 1286 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1287 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1288 return true; 1289 } 1290 1291 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1292 S.Diag(Call->getArg(0)->getBeginLoc(), 1293 diag::warn_opencl_generic_address_space_arg) 1294 << Call->getDirectCallee()->getNameInfo().getAsString() 1295 << Call->getArg(0)->getSourceRange(); 1296 } 1297 1298 RT = RT->getPointeeType(); 1299 auto Qual = RT.getQualifiers(); 1300 switch (BuiltinID) { 1301 case Builtin::BIto_global: 1302 Qual.setAddressSpace(LangAS::opencl_global); 1303 break; 1304 case Builtin::BIto_local: 1305 Qual.setAddressSpace(LangAS::opencl_local); 1306 break; 1307 case Builtin::BIto_private: 1308 Qual.setAddressSpace(LangAS::opencl_private); 1309 break; 1310 default: 1311 llvm_unreachable("Invalid builtin function"); 1312 } 1313 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1314 RT.getUnqualifiedType(), Qual))); 1315 1316 return false; 1317 } 1318 1319 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1320 if (checkArgCount(S, TheCall, 1)) 1321 return ExprError(); 1322 1323 // Compute __builtin_launder's parameter type from the argument. 1324 // The parameter type is: 1325 // * The type of the argument if it's not an array or function type, 1326 // Otherwise, 1327 // * The decayed argument type. 1328 QualType ParamTy = [&]() { 1329 QualType ArgTy = TheCall->getArg(0)->getType(); 1330 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1331 return S.Context.getPointerType(Ty->getElementType()); 1332 if (ArgTy->isFunctionType()) { 1333 return S.Context.getPointerType(ArgTy); 1334 } 1335 return ArgTy; 1336 }(); 1337 1338 TheCall->setType(ParamTy); 1339 1340 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1341 if (!ParamTy->isPointerType()) 1342 return 0; 1343 if (ParamTy->isFunctionPointerType()) 1344 return 1; 1345 if (ParamTy->isVoidPointerType()) 1346 return 2; 1347 return llvm::Optional<unsigned>{}; 1348 }(); 1349 if (DiagSelect.hasValue()) { 1350 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1351 << DiagSelect.getValue() << TheCall->getSourceRange(); 1352 return ExprError(); 1353 } 1354 1355 // We either have an incomplete class type, or we have a class template 1356 // whose instantiation has not been forced. Example: 1357 // 1358 // template <class T> struct Foo { T value; }; 1359 // Foo<int> *p = nullptr; 1360 // auto *d = __builtin_launder(p); 1361 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1362 diag::err_incomplete_type)) 1363 return ExprError(); 1364 1365 assert(ParamTy->getPointeeType()->isObjectType() && 1366 "Unhandled non-object pointer case"); 1367 1368 InitializedEntity Entity = 1369 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1370 ExprResult Arg = 1371 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1372 if (Arg.isInvalid()) 1373 return ExprError(); 1374 TheCall->setArg(0, Arg.get()); 1375 1376 return TheCall; 1377 } 1378 1379 // Emit an error and return true if the current architecture is not in the list 1380 // of supported architectures. 1381 static bool 1382 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1383 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1384 llvm::Triple::ArchType CurArch = 1385 S.getASTContext().getTargetInfo().getTriple().getArch(); 1386 if (llvm::is_contained(SupportedArchs, CurArch)) 1387 return false; 1388 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1389 << TheCall->getSourceRange(); 1390 return true; 1391 } 1392 1393 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1394 SourceLocation CallSiteLoc); 1395 1396 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1397 CallExpr *TheCall) { 1398 switch (TI.getTriple().getArch()) { 1399 default: 1400 // Some builtins don't require additional checking, so just consider these 1401 // acceptable. 1402 return false; 1403 case llvm::Triple::arm: 1404 case llvm::Triple::armeb: 1405 case llvm::Triple::thumb: 1406 case llvm::Triple::thumbeb: 1407 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1408 case llvm::Triple::aarch64: 1409 case llvm::Triple::aarch64_32: 1410 case llvm::Triple::aarch64_be: 1411 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1412 case llvm::Triple::bpfeb: 1413 case llvm::Triple::bpfel: 1414 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1415 case llvm::Triple::hexagon: 1416 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1417 case llvm::Triple::mips: 1418 case llvm::Triple::mipsel: 1419 case llvm::Triple::mips64: 1420 case llvm::Triple::mips64el: 1421 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1422 case llvm::Triple::systemz: 1423 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1424 case llvm::Triple::x86: 1425 case llvm::Triple::x86_64: 1426 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1427 case llvm::Triple::ppc: 1428 case llvm::Triple::ppc64: 1429 case llvm::Triple::ppc64le: 1430 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1431 case llvm::Triple::amdgcn: 1432 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1433 } 1434 } 1435 1436 ExprResult 1437 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1438 CallExpr *TheCall) { 1439 ExprResult TheCallResult(TheCall); 1440 1441 // Find out if any arguments are required to be integer constant expressions. 1442 unsigned ICEArguments = 0; 1443 ASTContext::GetBuiltinTypeError Error; 1444 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1445 if (Error != ASTContext::GE_None) 1446 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1447 1448 // If any arguments are required to be ICE's, check and diagnose. 1449 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1450 // Skip arguments not required to be ICE's. 1451 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1452 1453 llvm::APSInt Result; 1454 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1455 return true; 1456 ICEArguments &= ~(1 << ArgNo); 1457 } 1458 1459 switch (BuiltinID) { 1460 case Builtin::BI__builtin___CFStringMakeConstantString: 1461 assert(TheCall->getNumArgs() == 1 && 1462 "Wrong # arguments to builtin CFStringMakeConstantString"); 1463 if (CheckObjCString(TheCall->getArg(0))) 1464 return ExprError(); 1465 break; 1466 case Builtin::BI__builtin_ms_va_start: 1467 case Builtin::BI__builtin_stdarg_start: 1468 case Builtin::BI__builtin_va_start: 1469 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1470 return ExprError(); 1471 break; 1472 case Builtin::BI__va_start: { 1473 switch (Context.getTargetInfo().getTriple().getArch()) { 1474 case llvm::Triple::aarch64: 1475 case llvm::Triple::arm: 1476 case llvm::Triple::thumb: 1477 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1478 return ExprError(); 1479 break; 1480 default: 1481 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1482 return ExprError(); 1483 break; 1484 } 1485 break; 1486 } 1487 1488 // The acquire, release, and no fence variants are ARM and AArch64 only. 1489 case Builtin::BI_interlockedbittestandset_acq: 1490 case Builtin::BI_interlockedbittestandset_rel: 1491 case Builtin::BI_interlockedbittestandset_nf: 1492 case Builtin::BI_interlockedbittestandreset_acq: 1493 case Builtin::BI_interlockedbittestandreset_rel: 1494 case Builtin::BI_interlockedbittestandreset_nf: 1495 if (CheckBuiltinTargetSupport( 1496 *this, BuiltinID, TheCall, 1497 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1498 return ExprError(); 1499 break; 1500 1501 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1502 case Builtin::BI_bittest64: 1503 case Builtin::BI_bittestandcomplement64: 1504 case Builtin::BI_bittestandreset64: 1505 case Builtin::BI_bittestandset64: 1506 case Builtin::BI_interlockedbittestandreset64: 1507 case Builtin::BI_interlockedbittestandset64: 1508 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1509 {llvm::Triple::x86_64, llvm::Triple::arm, 1510 llvm::Triple::thumb, llvm::Triple::aarch64})) 1511 return ExprError(); 1512 break; 1513 1514 case Builtin::BI__builtin_isgreater: 1515 case Builtin::BI__builtin_isgreaterequal: 1516 case Builtin::BI__builtin_isless: 1517 case Builtin::BI__builtin_islessequal: 1518 case Builtin::BI__builtin_islessgreater: 1519 case Builtin::BI__builtin_isunordered: 1520 if (SemaBuiltinUnorderedCompare(TheCall)) 1521 return ExprError(); 1522 break; 1523 case Builtin::BI__builtin_fpclassify: 1524 if (SemaBuiltinFPClassification(TheCall, 6)) 1525 return ExprError(); 1526 break; 1527 case Builtin::BI__builtin_isfinite: 1528 case Builtin::BI__builtin_isinf: 1529 case Builtin::BI__builtin_isinf_sign: 1530 case Builtin::BI__builtin_isnan: 1531 case Builtin::BI__builtin_isnormal: 1532 case Builtin::BI__builtin_signbit: 1533 case Builtin::BI__builtin_signbitf: 1534 case Builtin::BI__builtin_signbitl: 1535 if (SemaBuiltinFPClassification(TheCall, 1)) 1536 return ExprError(); 1537 break; 1538 case Builtin::BI__builtin_shufflevector: 1539 return SemaBuiltinShuffleVector(TheCall); 1540 // TheCall will be freed by the smart pointer here, but that's fine, since 1541 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1542 case Builtin::BI__builtin_prefetch: 1543 if (SemaBuiltinPrefetch(TheCall)) 1544 return ExprError(); 1545 break; 1546 case Builtin::BI__builtin_alloca_with_align: 1547 if (SemaBuiltinAllocaWithAlign(TheCall)) 1548 return ExprError(); 1549 LLVM_FALLTHROUGH; 1550 case Builtin::BI__builtin_alloca: 1551 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1552 << TheCall->getDirectCallee(); 1553 break; 1554 case Builtin::BI__assume: 1555 case Builtin::BI__builtin_assume: 1556 if (SemaBuiltinAssume(TheCall)) 1557 return ExprError(); 1558 break; 1559 case Builtin::BI__builtin_assume_aligned: 1560 if (SemaBuiltinAssumeAligned(TheCall)) 1561 return ExprError(); 1562 break; 1563 case Builtin::BI__builtin_dynamic_object_size: 1564 case Builtin::BI__builtin_object_size: 1565 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1566 return ExprError(); 1567 break; 1568 case Builtin::BI__builtin_longjmp: 1569 if (SemaBuiltinLongjmp(TheCall)) 1570 return ExprError(); 1571 break; 1572 case Builtin::BI__builtin_setjmp: 1573 if (SemaBuiltinSetjmp(TheCall)) 1574 return ExprError(); 1575 break; 1576 case Builtin::BI_setjmp: 1577 case Builtin::BI_setjmpex: 1578 if (checkArgCount(*this, TheCall, 1)) 1579 return true; 1580 break; 1581 case Builtin::BI__builtin_classify_type: 1582 if (checkArgCount(*this, TheCall, 1)) return true; 1583 TheCall->setType(Context.IntTy); 1584 break; 1585 case Builtin::BI__builtin_complex: 1586 if (SemaBuiltinComplex(TheCall)) 1587 return ExprError(); 1588 break; 1589 case Builtin::BI__builtin_constant_p: { 1590 if (checkArgCount(*this, TheCall, 1)) return true; 1591 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1592 if (Arg.isInvalid()) return true; 1593 TheCall->setArg(0, Arg.get()); 1594 TheCall->setType(Context.IntTy); 1595 break; 1596 } 1597 case Builtin::BI__builtin_launder: 1598 return SemaBuiltinLaunder(*this, TheCall); 1599 case Builtin::BI__sync_fetch_and_add: 1600 case Builtin::BI__sync_fetch_and_add_1: 1601 case Builtin::BI__sync_fetch_and_add_2: 1602 case Builtin::BI__sync_fetch_and_add_4: 1603 case Builtin::BI__sync_fetch_and_add_8: 1604 case Builtin::BI__sync_fetch_and_add_16: 1605 case Builtin::BI__sync_fetch_and_sub: 1606 case Builtin::BI__sync_fetch_and_sub_1: 1607 case Builtin::BI__sync_fetch_and_sub_2: 1608 case Builtin::BI__sync_fetch_and_sub_4: 1609 case Builtin::BI__sync_fetch_and_sub_8: 1610 case Builtin::BI__sync_fetch_and_sub_16: 1611 case Builtin::BI__sync_fetch_and_or: 1612 case Builtin::BI__sync_fetch_and_or_1: 1613 case Builtin::BI__sync_fetch_and_or_2: 1614 case Builtin::BI__sync_fetch_and_or_4: 1615 case Builtin::BI__sync_fetch_and_or_8: 1616 case Builtin::BI__sync_fetch_and_or_16: 1617 case Builtin::BI__sync_fetch_and_and: 1618 case Builtin::BI__sync_fetch_and_and_1: 1619 case Builtin::BI__sync_fetch_and_and_2: 1620 case Builtin::BI__sync_fetch_and_and_4: 1621 case Builtin::BI__sync_fetch_and_and_8: 1622 case Builtin::BI__sync_fetch_and_and_16: 1623 case Builtin::BI__sync_fetch_and_xor: 1624 case Builtin::BI__sync_fetch_and_xor_1: 1625 case Builtin::BI__sync_fetch_and_xor_2: 1626 case Builtin::BI__sync_fetch_and_xor_4: 1627 case Builtin::BI__sync_fetch_and_xor_8: 1628 case Builtin::BI__sync_fetch_and_xor_16: 1629 case Builtin::BI__sync_fetch_and_nand: 1630 case Builtin::BI__sync_fetch_and_nand_1: 1631 case Builtin::BI__sync_fetch_and_nand_2: 1632 case Builtin::BI__sync_fetch_and_nand_4: 1633 case Builtin::BI__sync_fetch_and_nand_8: 1634 case Builtin::BI__sync_fetch_and_nand_16: 1635 case Builtin::BI__sync_add_and_fetch: 1636 case Builtin::BI__sync_add_and_fetch_1: 1637 case Builtin::BI__sync_add_and_fetch_2: 1638 case Builtin::BI__sync_add_and_fetch_4: 1639 case Builtin::BI__sync_add_and_fetch_8: 1640 case Builtin::BI__sync_add_and_fetch_16: 1641 case Builtin::BI__sync_sub_and_fetch: 1642 case Builtin::BI__sync_sub_and_fetch_1: 1643 case Builtin::BI__sync_sub_and_fetch_2: 1644 case Builtin::BI__sync_sub_and_fetch_4: 1645 case Builtin::BI__sync_sub_and_fetch_8: 1646 case Builtin::BI__sync_sub_and_fetch_16: 1647 case Builtin::BI__sync_and_and_fetch: 1648 case Builtin::BI__sync_and_and_fetch_1: 1649 case Builtin::BI__sync_and_and_fetch_2: 1650 case Builtin::BI__sync_and_and_fetch_4: 1651 case Builtin::BI__sync_and_and_fetch_8: 1652 case Builtin::BI__sync_and_and_fetch_16: 1653 case Builtin::BI__sync_or_and_fetch: 1654 case Builtin::BI__sync_or_and_fetch_1: 1655 case Builtin::BI__sync_or_and_fetch_2: 1656 case Builtin::BI__sync_or_and_fetch_4: 1657 case Builtin::BI__sync_or_and_fetch_8: 1658 case Builtin::BI__sync_or_and_fetch_16: 1659 case Builtin::BI__sync_xor_and_fetch: 1660 case Builtin::BI__sync_xor_and_fetch_1: 1661 case Builtin::BI__sync_xor_and_fetch_2: 1662 case Builtin::BI__sync_xor_and_fetch_4: 1663 case Builtin::BI__sync_xor_and_fetch_8: 1664 case Builtin::BI__sync_xor_and_fetch_16: 1665 case Builtin::BI__sync_nand_and_fetch: 1666 case Builtin::BI__sync_nand_and_fetch_1: 1667 case Builtin::BI__sync_nand_and_fetch_2: 1668 case Builtin::BI__sync_nand_and_fetch_4: 1669 case Builtin::BI__sync_nand_and_fetch_8: 1670 case Builtin::BI__sync_nand_and_fetch_16: 1671 case Builtin::BI__sync_val_compare_and_swap: 1672 case Builtin::BI__sync_val_compare_and_swap_1: 1673 case Builtin::BI__sync_val_compare_and_swap_2: 1674 case Builtin::BI__sync_val_compare_and_swap_4: 1675 case Builtin::BI__sync_val_compare_and_swap_8: 1676 case Builtin::BI__sync_val_compare_and_swap_16: 1677 case Builtin::BI__sync_bool_compare_and_swap: 1678 case Builtin::BI__sync_bool_compare_and_swap_1: 1679 case Builtin::BI__sync_bool_compare_and_swap_2: 1680 case Builtin::BI__sync_bool_compare_and_swap_4: 1681 case Builtin::BI__sync_bool_compare_and_swap_8: 1682 case Builtin::BI__sync_bool_compare_and_swap_16: 1683 case Builtin::BI__sync_lock_test_and_set: 1684 case Builtin::BI__sync_lock_test_and_set_1: 1685 case Builtin::BI__sync_lock_test_and_set_2: 1686 case Builtin::BI__sync_lock_test_and_set_4: 1687 case Builtin::BI__sync_lock_test_and_set_8: 1688 case Builtin::BI__sync_lock_test_and_set_16: 1689 case Builtin::BI__sync_lock_release: 1690 case Builtin::BI__sync_lock_release_1: 1691 case Builtin::BI__sync_lock_release_2: 1692 case Builtin::BI__sync_lock_release_4: 1693 case Builtin::BI__sync_lock_release_8: 1694 case Builtin::BI__sync_lock_release_16: 1695 case Builtin::BI__sync_swap: 1696 case Builtin::BI__sync_swap_1: 1697 case Builtin::BI__sync_swap_2: 1698 case Builtin::BI__sync_swap_4: 1699 case Builtin::BI__sync_swap_8: 1700 case Builtin::BI__sync_swap_16: 1701 return SemaBuiltinAtomicOverloaded(TheCallResult); 1702 case Builtin::BI__sync_synchronize: 1703 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1704 << TheCall->getCallee()->getSourceRange(); 1705 break; 1706 case Builtin::BI__builtin_nontemporal_load: 1707 case Builtin::BI__builtin_nontemporal_store: 1708 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1709 case Builtin::BI__builtin_memcpy_inline: { 1710 clang::Expr *SizeOp = TheCall->getArg(2); 1711 // We warn about copying to or from `nullptr` pointers when `size` is 1712 // greater than 0. When `size` is value dependent we cannot evaluate its 1713 // value so we bail out. 1714 if (SizeOp->isValueDependent()) 1715 break; 1716 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1717 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1718 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1719 } 1720 break; 1721 } 1722 #define BUILTIN(ID, TYPE, ATTRS) 1723 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1724 case Builtin::BI##ID: \ 1725 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1726 #include "clang/Basic/Builtins.def" 1727 case Builtin::BI__annotation: 1728 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1729 return ExprError(); 1730 break; 1731 case Builtin::BI__builtin_annotation: 1732 if (SemaBuiltinAnnotation(*this, TheCall)) 1733 return ExprError(); 1734 break; 1735 case Builtin::BI__builtin_addressof: 1736 if (SemaBuiltinAddressof(*this, TheCall)) 1737 return ExprError(); 1738 break; 1739 case Builtin::BI__builtin_is_aligned: 1740 case Builtin::BI__builtin_align_up: 1741 case Builtin::BI__builtin_align_down: 1742 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1743 return ExprError(); 1744 break; 1745 case Builtin::BI__builtin_add_overflow: 1746 case Builtin::BI__builtin_sub_overflow: 1747 case Builtin::BI__builtin_mul_overflow: 1748 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1749 return ExprError(); 1750 break; 1751 case Builtin::BI__builtin_operator_new: 1752 case Builtin::BI__builtin_operator_delete: { 1753 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1754 ExprResult Res = 1755 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1756 if (Res.isInvalid()) 1757 CorrectDelayedTyposInExpr(TheCallResult.get()); 1758 return Res; 1759 } 1760 case Builtin::BI__builtin_dump_struct: { 1761 // We first want to ensure we are called with 2 arguments 1762 if (checkArgCount(*this, TheCall, 2)) 1763 return ExprError(); 1764 // Ensure that the first argument is of type 'struct XX *' 1765 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1766 const QualType PtrArgType = PtrArg->getType(); 1767 if (!PtrArgType->isPointerType() || 1768 !PtrArgType->getPointeeType()->isRecordType()) { 1769 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1770 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1771 << "structure pointer"; 1772 return ExprError(); 1773 } 1774 1775 // Ensure that the second argument is of type 'FunctionType' 1776 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1777 const QualType FnPtrArgType = FnPtrArg->getType(); 1778 if (!FnPtrArgType->isPointerType()) { 1779 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1780 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1781 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1782 return ExprError(); 1783 } 1784 1785 const auto *FuncType = 1786 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1787 1788 if (!FuncType) { 1789 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1790 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1791 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1792 return ExprError(); 1793 } 1794 1795 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1796 if (!FT->getNumParams()) { 1797 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1798 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1799 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1800 return ExprError(); 1801 } 1802 QualType PT = FT->getParamType(0); 1803 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1804 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1805 !PT->getPointeeType().isConstQualified()) { 1806 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1807 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1808 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1809 return ExprError(); 1810 } 1811 } 1812 1813 TheCall->setType(Context.IntTy); 1814 break; 1815 } 1816 case Builtin::BI__builtin_expect_with_probability: { 1817 // We first want to ensure we are called with 3 arguments 1818 if (checkArgCount(*this, TheCall, 3)) 1819 return ExprError(); 1820 // then check probability is constant float in range [0.0, 1.0] 1821 const Expr *ProbArg = TheCall->getArg(2); 1822 SmallVector<PartialDiagnosticAt, 8> Notes; 1823 Expr::EvalResult Eval; 1824 Eval.Diag = &Notes; 1825 if ((!ProbArg->EvaluateAsConstantExpr(Eval, Expr::EvaluateForCodeGen, 1826 Context)) || 1827 !Eval.Val.isFloat()) { 1828 Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float) 1829 << ProbArg->getSourceRange(); 1830 for (const PartialDiagnosticAt &PDiag : Notes) 1831 Diag(PDiag.first, PDiag.second); 1832 return ExprError(); 1833 } 1834 llvm::APFloat Probability = Eval.Val.getFloat(); 1835 bool LoseInfo = false; 1836 Probability.convert(llvm::APFloat::IEEEdouble(), 1837 llvm::RoundingMode::Dynamic, &LoseInfo); 1838 if (!(Probability >= llvm::APFloat(0.0) && 1839 Probability <= llvm::APFloat(1.0))) { 1840 Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range) 1841 << ProbArg->getSourceRange(); 1842 return ExprError(); 1843 } 1844 break; 1845 } 1846 case Builtin::BI__builtin_preserve_access_index: 1847 if (SemaBuiltinPreserveAI(*this, TheCall)) 1848 return ExprError(); 1849 break; 1850 case Builtin::BI__builtin_call_with_static_chain: 1851 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1852 return ExprError(); 1853 break; 1854 case Builtin::BI__exception_code: 1855 case Builtin::BI_exception_code: 1856 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1857 diag::err_seh___except_block)) 1858 return ExprError(); 1859 break; 1860 case Builtin::BI__exception_info: 1861 case Builtin::BI_exception_info: 1862 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1863 diag::err_seh___except_filter)) 1864 return ExprError(); 1865 break; 1866 case Builtin::BI__GetExceptionInfo: 1867 if (checkArgCount(*this, TheCall, 1)) 1868 return ExprError(); 1869 1870 if (CheckCXXThrowOperand( 1871 TheCall->getBeginLoc(), 1872 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1873 TheCall)) 1874 return ExprError(); 1875 1876 TheCall->setType(Context.VoidPtrTy); 1877 break; 1878 // OpenCL v2.0, s6.13.16 - Pipe functions 1879 case Builtin::BIread_pipe: 1880 case Builtin::BIwrite_pipe: 1881 // Since those two functions are declared with var args, we need a semantic 1882 // check for the argument. 1883 if (SemaBuiltinRWPipe(*this, TheCall)) 1884 return ExprError(); 1885 break; 1886 case Builtin::BIreserve_read_pipe: 1887 case Builtin::BIreserve_write_pipe: 1888 case Builtin::BIwork_group_reserve_read_pipe: 1889 case Builtin::BIwork_group_reserve_write_pipe: 1890 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1891 return ExprError(); 1892 break; 1893 case Builtin::BIsub_group_reserve_read_pipe: 1894 case Builtin::BIsub_group_reserve_write_pipe: 1895 if (checkOpenCLSubgroupExt(*this, TheCall) || 1896 SemaBuiltinReserveRWPipe(*this, TheCall)) 1897 return ExprError(); 1898 break; 1899 case Builtin::BIcommit_read_pipe: 1900 case Builtin::BIcommit_write_pipe: 1901 case Builtin::BIwork_group_commit_read_pipe: 1902 case Builtin::BIwork_group_commit_write_pipe: 1903 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1904 return ExprError(); 1905 break; 1906 case Builtin::BIsub_group_commit_read_pipe: 1907 case Builtin::BIsub_group_commit_write_pipe: 1908 if (checkOpenCLSubgroupExt(*this, TheCall) || 1909 SemaBuiltinCommitRWPipe(*this, TheCall)) 1910 return ExprError(); 1911 break; 1912 case Builtin::BIget_pipe_num_packets: 1913 case Builtin::BIget_pipe_max_packets: 1914 if (SemaBuiltinPipePackets(*this, TheCall)) 1915 return ExprError(); 1916 break; 1917 case Builtin::BIto_global: 1918 case Builtin::BIto_local: 1919 case Builtin::BIto_private: 1920 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1921 return ExprError(); 1922 break; 1923 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1924 case Builtin::BIenqueue_kernel: 1925 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1926 return ExprError(); 1927 break; 1928 case Builtin::BIget_kernel_work_group_size: 1929 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1930 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1931 return ExprError(); 1932 break; 1933 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1934 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1935 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1936 return ExprError(); 1937 break; 1938 case Builtin::BI__builtin_os_log_format: 1939 Cleanup.setExprNeedsCleanups(true); 1940 LLVM_FALLTHROUGH; 1941 case Builtin::BI__builtin_os_log_format_buffer_size: 1942 if (SemaBuiltinOSLogFormat(TheCall)) 1943 return ExprError(); 1944 break; 1945 case Builtin::BI__builtin_frame_address: 1946 case Builtin::BI__builtin_return_address: { 1947 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1948 return ExprError(); 1949 1950 // -Wframe-address warning if non-zero passed to builtin 1951 // return/frame address. 1952 Expr::EvalResult Result; 1953 if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1954 Result.Val.getInt() != 0) 1955 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1956 << ((BuiltinID == Builtin::BI__builtin_return_address) 1957 ? "__builtin_return_address" 1958 : "__builtin_frame_address") 1959 << TheCall->getSourceRange(); 1960 break; 1961 } 1962 1963 case Builtin::BI__builtin_matrix_transpose: 1964 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1965 1966 case Builtin::BI__builtin_matrix_column_major_load: 1967 return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult); 1968 1969 case Builtin::BI__builtin_matrix_column_major_store: 1970 return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult); 1971 } 1972 1973 // Since the target specific builtins for each arch overlap, only check those 1974 // of the arch we are compiling for. 1975 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1976 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 1977 assert(Context.getAuxTargetInfo() && 1978 "Aux Target Builtin, but not an aux target?"); 1979 1980 if (CheckTSBuiltinFunctionCall( 1981 *Context.getAuxTargetInfo(), 1982 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 1983 return ExprError(); 1984 } else { 1985 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 1986 TheCall)) 1987 return ExprError(); 1988 } 1989 } 1990 1991 return TheCallResult; 1992 } 1993 1994 // Get the valid immediate range for the specified NEON type code. 1995 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1996 NeonTypeFlags Type(t); 1997 int IsQuad = ForceQuad ? true : Type.isQuad(); 1998 switch (Type.getEltType()) { 1999 case NeonTypeFlags::Int8: 2000 case NeonTypeFlags::Poly8: 2001 return shift ? 7 : (8 << IsQuad) - 1; 2002 case NeonTypeFlags::Int16: 2003 case NeonTypeFlags::Poly16: 2004 return shift ? 15 : (4 << IsQuad) - 1; 2005 case NeonTypeFlags::Int32: 2006 return shift ? 31 : (2 << IsQuad) - 1; 2007 case NeonTypeFlags::Int64: 2008 case NeonTypeFlags::Poly64: 2009 return shift ? 63 : (1 << IsQuad) - 1; 2010 case NeonTypeFlags::Poly128: 2011 return shift ? 127 : (1 << IsQuad) - 1; 2012 case NeonTypeFlags::Float16: 2013 assert(!shift && "cannot shift float types!"); 2014 return (4 << IsQuad) - 1; 2015 case NeonTypeFlags::Float32: 2016 assert(!shift && "cannot shift float types!"); 2017 return (2 << IsQuad) - 1; 2018 case NeonTypeFlags::Float64: 2019 assert(!shift && "cannot shift float types!"); 2020 return (1 << IsQuad) - 1; 2021 case NeonTypeFlags::BFloat16: 2022 assert(!shift && "cannot shift float types!"); 2023 return (4 << IsQuad) - 1; 2024 } 2025 llvm_unreachable("Invalid NeonTypeFlag!"); 2026 } 2027 2028 /// getNeonEltType - Return the QualType corresponding to the elements of 2029 /// the vector type specified by the NeonTypeFlags. This is used to check 2030 /// the pointer arguments for Neon load/store intrinsics. 2031 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 2032 bool IsPolyUnsigned, bool IsInt64Long) { 2033 switch (Flags.getEltType()) { 2034 case NeonTypeFlags::Int8: 2035 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 2036 case NeonTypeFlags::Int16: 2037 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 2038 case NeonTypeFlags::Int32: 2039 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 2040 case NeonTypeFlags::Int64: 2041 if (IsInt64Long) 2042 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2043 else 2044 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2045 : Context.LongLongTy; 2046 case NeonTypeFlags::Poly8: 2047 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2048 case NeonTypeFlags::Poly16: 2049 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2050 case NeonTypeFlags::Poly64: 2051 if (IsInt64Long) 2052 return Context.UnsignedLongTy; 2053 else 2054 return Context.UnsignedLongLongTy; 2055 case NeonTypeFlags::Poly128: 2056 break; 2057 case NeonTypeFlags::Float16: 2058 return Context.HalfTy; 2059 case NeonTypeFlags::Float32: 2060 return Context.FloatTy; 2061 case NeonTypeFlags::Float64: 2062 return Context.DoubleTy; 2063 case NeonTypeFlags::BFloat16: 2064 return Context.BFloat16Ty; 2065 } 2066 llvm_unreachable("Invalid NeonTypeFlag!"); 2067 } 2068 2069 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2070 // Range check SVE intrinsics that take immediate values. 2071 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2072 2073 switch (BuiltinID) { 2074 default: 2075 return false; 2076 #define GET_SVE_IMMEDIATE_CHECK 2077 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2078 #undef GET_SVE_IMMEDIATE_CHECK 2079 } 2080 2081 // Perform all the immediate checks for this builtin call. 2082 bool HasError = false; 2083 for (auto &I : ImmChecks) { 2084 int ArgNum, CheckTy, ElementSizeInBits; 2085 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2086 2087 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2088 2089 // Function that checks whether the operand (ArgNum) is an immediate 2090 // that is one of the predefined values. 2091 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2092 int ErrDiag) -> bool { 2093 // We can't check the value of a dependent argument. 2094 Expr *Arg = TheCall->getArg(ArgNum); 2095 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2096 return false; 2097 2098 // Check constant-ness first. 2099 llvm::APSInt Imm; 2100 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2101 return true; 2102 2103 if (!CheckImm(Imm.getSExtValue())) 2104 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2105 return false; 2106 }; 2107 2108 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2109 case SVETypeFlags::ImmCheck0_31: 2110 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2111 HasError = true; 2112 break; 2113 case SVETypeFlags::ImmCheck0_13: 2114 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2115 HasError = true; 2116 break; 2117 case SVETypeFlags::ImmCheck1_16: 2118 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2119 HasError = true; 2120 break; 2121 case SVETypeFlags::ImmCheck0_7: 2122 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2123 HasError = true; 2124 break; 2125 case SVETypeFlags::ImmCheckExtract: 2126 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2127 (2048 / ElementSizeInBits) - 1)) 2128 HasError = true; 2129 break; 2130 case SVETypeFlags::ImmCheckShiftRight: 2131 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2132 HasError = true; 2133 break; 2134 case SVETypeFlags::ImmCheckShiftRightNarrow: 2135 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2136 ElementSizeInBits / 2)) 2137 HasError = true; 2138 break; 2139 case SVETypeFlags::ImmCheckShiftLeft: 2140 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2141 ElementSizeInBits - 1)) 2142 HasError = true; 2143 break; 2144 case SVETypeFlags::ImmCheckLaneIndex: 2145 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2146 (128 / (1 * ElementSizeInBits)) - 1)) 2147 HasError = true; 2148 break; 2149 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2150 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2151 (128 / (2 * ElementSizeInBits)) - 1)) 2152 HasError = true; 2153 break; 2154 case SVETypeFlags::ImmCheckLaneIndexDot: 2155 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2156 (128 / (4 * ElementSizeInBits)) - 1)) 2157 HasError = true; 2158 break; 2159 case SVETypeFlags::ImmCheckComplexRot90_270: 2160 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2161 diag::err_rotation_argument_to_cadd)) 2162 HasError = true; 2163 break; 2164 case SVETypeFlags::ImmCheckComplexRotAll90: 2165 if (CheckImmediateInSet( 2166 [](int64_t V) { 2167 return V == 0 || V == 90 || V == 180 || V == 270; 2168 }, 2169 diag::err_rotation_argument_to_cmla)) 2170 HasError = true; 2171 break; 2172 case SVETypeFlags::ImmCheck0_1: 2173 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1)) 2174 HasError = true; 2175 break; 2176 case SVETypeFlags::ImmCheck0_2: 2177 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2)) 2178 HasError = true; 2179 break; 2180 case SVETypeFlags::ImmCheck0_3: 2181 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3)) 2182 HasError = true; 2183 break; 2184 } 2185 } 2186 2187 return HasError; 2188 } 2189 2190 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2191 unsigned BuiltinID, CallExpr *TheCall) { 2192 llvm::APSInt Result; 2193 uint64_t mask = 0; 2194 unsigned TV = 0; 2195 int PtrArgNum = -1; 2196 bool HasConstPtr = false; 2197 switch (BuiltinID) { 2198 #define GET_NEON_OVERLOAD_CHECK 2199 #include "clang/Basic/arm_neon.inc" 2200 #include "clang/Basic/arm_fp16.inc" 2201 #undef GET_NEON_OVERLOAD_CHECK 2202 } 2203 2204 // For NEON intrinsics which are overloaded on vector element type, validate 2205 // the immediate which specifies which variant to emit. 2206 unsigned ImmArg = TheCall->getNumArgs()-1; 2207 if (mask) { 2208 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2209 return true; 2210 2211 TV = Result.getLimitedValue(64); 2212 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2213 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2214 << TheCall->getArg(ImmArg)->getSourceRange(); 2215 } 2216 2217 if (PtrArgNum >= 0) { 2218 // Check that pointer arguments have the specified type. 2219 Expr *Arg = TheCall->getArg(PtrArgNum); 2220 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2221 Arg = ICE->getSubExpr(); 2222 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2223 QualType RHSTy = RHS.get()->getType(); 2224 2225 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2226 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2227 Arch == llvm::Triple::aarch64_32 || 2228 Arch == llvm::Triple::aarch64_be; 2229 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2230 QualType EltTy = 2231 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2232 if (HasConstPtr) 2233 EltTy = EltTy.withConst(); 2234 QualType LHSTy = Context.getPointerType(EltTy); 2235 AssignConvertType ConvTy; 2236 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2237 if (RHS.isInvalid()) 2238 return true; 2239 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2240 RHS.get(), AA_Assigning)) 2241 return true; 2242 } 2243 2244 // For NEON intrinsics which take an immediate value as part of the 2245 // instruction, range check them here. 2246 unsigned i = 0, l = 0, u = 0; 2247 switch (BuiltinID) { 2248 default: 2249 return false; 2250 #define GET_NEON_IMMEDIATE_CHECK 2251 #include "clang/Basic/arm_neon.inc" 2252 #include "clang/Basic/arm_fp16.inc" 2253 #undef GET_NEON_IMMEDIATE_CHECK 2254 } 2255 2256 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2257 } 2258 2259 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2260 switch (BuiltinID) { 2261 default: 2262 return false; 2263 #include "clang/Basic/arm_mve_builtin_sema.inc" 2264 } 2265 } 2266 2267 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2268 CallExpr *TheCall) { 2269 bool Err = false; 2270 switch (BuiltinID) { 2271 default: 2272 return false; 2273 #include "clang/Basic/arm_cde_builtin_sema.inc" 2274 } 2275 2276 if (Err) 2277 return true; 2278 2279 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2280 } 2281 2282 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2283 const Expr *CoprocArg, bool WantCDE) { 2284 if (isConstantEvaluated()) 2285 return false; 2286 2287 // We can't check the value of a dependent argument. 2288 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2289 return false; 2290 2291 llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context); 2292 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2293 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2294 2295 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2296 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2297 2298 if (IsCDECoproc != WantCDE) 2299 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2300 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2301 2302 return false; 2303 } 2304 2305 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2306 unsigned MaxWidth) { 2307 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2308 BuiltinID == ARM::BI__builtin_arm_ldaex || 2309 BuiltinID == ARM::BI__builtin_arm_strex || 2310 BuiltinID == ARM::BI__builtin_arm_stlex || 2311 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2312 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2313 BuiltinID == AArch64::BI__builtin_arm_strex || 2314 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2315 "unexpected ARM builtin"); 2316 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2317 BuiltinID == ARM::BI__builtin_arm_ldaex || 2318 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2319 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2320 2321 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2322 2323 // Ensure that we have the proper number of arguments. 2324 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2325 return true; 2326 2327 // Inspect the pointer argument of the atomic builtin. This should always be 2328 // a pointer type, whose element is an integral scalar or pointer type. 2329 // Because it is a pointer type, we don't have to worry about any implicit 2330 // casts here. 2331 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2332 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2333 if (PointerArgRes.isInvalid()) 2334 return true; 2335 PointerArg = PointerArgRes.get(); 2336 2337 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2338 if (!pointerType) { 2339 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2340 << PointerArg->getType() << PointerArg->getSourceRange(); 2341 return true; 2342 } 2343 2344 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2345 // task is to insert the appropriate casts into the AST. First work out just 2346 // what the appropriate type is. 2347 QualType ValType = pointerType->getPointeeType(); 2348 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2349 if (IsLdrex) 2350 AddrType.addConst(); 2351 2352 // Issue a warning if the cast is dodgy. 2353 CastKind CastNeeded = CK_NoOp; 2354 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2355 CastNeeded = CK_BitCast; 2356 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2357 << PointerArg->getType() << Context.getPointerType(AddrType) 2358 << AA_Passing << PointerArg->getSourceRange(); 2359 } 2360 2361 // Finally, do the cast and replace the argument with the corrected version. 2362 AddrType = Context.getPointerType(AddrType); 2363 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2364 if (PointerArgRes.isInvalid()) 2365 return true; 2366 PointerArg = PointerArgRes.get(); 2367 2368 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2369 2370 // In general, we allow ints, floats and pointers to be loaded and stored. 2371 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2372 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2373 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2374 << PointerArg->getType() << PointerArg->getSourceRange(); 2375 return true; 2376 } 2377 2378 // But ARM doesn't have instructions to deal with 128-bit versions. 2379 if (Context.getTypeSize(ValType) > MaxWidth) { 2380 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2381 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2382 << PointerArg->getType() << PointerArg->getSourceRange(); 2383 return true; 2384 } 2385 2386 switch (ValType.getObjCLifetime()) { 2387 case Qualifiers::OCL_None: 2388 case Qualifiers::OCL_ExplicitNone: 2389 // okay 2390 break; 2391 2392 case Qualifiers::OCL_Weak: 2393 case Qualifiers::OCL_Strong: 2394 case Qualifiers::OCL_Autoreleasing: 2395 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2396 << ValType << PointerArg->getSourceRange(); 2397 return true; 2398 } 2399 2400 if (IsLdrex) { 2401 TheCall->setType(ValType); 2402 return false; 2403 } 2404 2405 // Initialize the argument to be stored. 2406 ExprResult ValArg = TheCall->getArg(0); 2407 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2408 Context, ValType, /*consume*/ false); 2409 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2410 if (ValArg.isInvalid()) 2411 return true; 2412 TheCall->setArg(0, ValArg.get()); 2413 2414 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2415 // but the custom checker bypasses all default analysis. 2416 TheCall->setType(Context.IntTy); 2417 return false; 2418 } 2419 2420 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2421 CallExpr *TheCall) { 2422 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2423 BuiltinID == ARM::BI__builtin_arm_ldaex || 2424 BuiltinID == ARM::BI__builtin_arm_strex || 2425 BuiltinID == ARM::BI__builtin_arm_stlex) { 2426 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2427 } 2428 2429 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2430 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2431 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2432 } 2433 2434 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2435 BuiltinID == ARM::BI__builtin_arm_wsr64) 2436 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2437 2438 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2439 BuiltinID == ARM::BI__builtin_arm_rsrp || 2440 BuiltinID == ARM::BI__builtin_arm_wsr || 2441 BuiltinID == ARM::BI__builtin_arm_wsrp) 2442 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2443 2444 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2445 return true; 2446 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2447 return true; 2448 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2449 return true; 2450 2451 // For intrinsics which take an immediate value as part of the instruction, 2452 // range check them here. 2453 // FIXME: VFP Intrinsics should error if VFP not present. 2454 switch (BuiltinID) { 2455 default: return false; 2456 case ARM::BI__builtin_arm_ssat: 2457 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2458 case ARM::BI__builtin_arm_usat: 2459 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2460 case ARM::BI__builtin_arm_ssat16: 2461 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2462 case ARM::BI__builtin_arm_usat16: 2463 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2464 case ARM::BI__builtin_arm_vcvtr_f: 2465 case ARM::BI__builtin_arm_vcvtr_d: 2466 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2467 case ARM::BI__builtin_arm_dmb: 2468 case ARM::BI__builtin_arm_dsb: 2469 case ARM::BI__builtin_arm_isb: 2470 case ARM::BI__builtin_arm_dbg: 2471 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2472 case ARM::BI__builtin_arm_cdp: 2473 case ARM::BI__builtin_arm_cdp2: 2474 case ARM::BI__builtin_arm_mcr: 2475 case ARM::BI__builtin_arm_mcr2: 2476 case ARM::BI__builtin_arm_mrc: 2477 case ARM::BI__builtin_arm_mrc2: 2478 case ARM::BI__builtin_arm_mcrr: 2479 case ARM::BI__builtin_arm_mcrr2: 2480 case ARM::BI__builtin_arm_mrrc: 2481 case ARM::BI__builtin_arm_mrrc2: 2482 case ARM::BI__builtin_arm_ldc: 2483 case ARM::BI__builtin_arm_ldcl: 2484 case ARM::BI__builtin_arm_ldc2: 2485 case ARM::BI__builtin_arm_ldc2l: 2486 case ARM::BI__builtin_arm_stc: 2487 case ARM::BI__builtin_arm_stcl: 2488 case ARM::BI__builtin_arm_stc2: 2489 case ARM::BI__builtin_arm_stc2l: 2490 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2491 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2492 /*WantCDE*/ false); 2493 } 2494 } 2495 2496 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2497 unsigned BuiltinID, 2498 CallExpr *TheCall) { 2499 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2500 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2501 BuiltinID == AArch64::BI__builtin_arm_strex || 2502 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2503 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2504 } 2505 2506 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2507 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2508 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2509 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2510 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2511 } 2512 2513 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2514 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2515 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2516 2517 // Memory Tagging Extensions (MTE) Intrinsics 2518 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2519 BuiltinID == AArch64::BI__builtin_arm_addg || 2520 BuiltinID == AArch64::BI__builtin_arm_gmi || 2521 BuiltinID == AArch64::BI__builtin_arm_ldg || 2522 BuiltinID == AArch64::BI__builtin_arm_stg || 2523 BuiltinID == AArch64::BI__builtin_arm_subp) { 2524 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2525 } 2526 2527 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2528 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2529 BuiltinID == AArch64::BI__builtin_arm_wsr || 2530 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2531 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2532 2533 // Only check the valid encoding range. Any constant in this range would be 2534 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2535 // an exception for incorrect registers. This matches MSVC behavior. 2536 if (BuiltinID == AArch64::BI_ReadStatusReg || 2537 BuiltinID == AArch64::BI_WriteStatusReg) 2538 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2539 2540 if (BuiltinID == AArch64::BI__getReg) 2541 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2542 2543 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2544 return true; 2545 2546 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2547 return true; 2548 2549 // For intrinsics which take an immediate value as part of the instruction, 2550 // range check them here. 2551 unsigned i = 0, l = 0, u = 0; 2552 switch (BuiltinID) { 2553 default: return false; 2554 case AArch64::BI__builtin_arm_dmb: 2555 case AArch64::BI__builtin_arm_dsb: 2556 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2557 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2558 } 2559 2560 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2561 } 2562 2563 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2564 CallExpr *TheCall) { 2565 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2566 BuiltinID == BPF::BI__builtin_btf_type_id) && 2567 "unexpected ARM builtin"); 2568 2569 if (checkArgCount(*this, TheCall, 2)) 2570 return true; 2571 2572 Expr *Arg; 2573 if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2574 // The second argument needs to be a constant int 2575 Arg = TheCall->getArg(1); 2576 if (!Arg->isIntegerConstantExpr(Context)) { 2577 Diag(Arg->getBeginLoc(), diag::err_btf_type_id_not_const) 2578 << 2 << Arg->getSourceRange(); 2579 return true; 2580 } 2581 2582 TheCall->setType(Context.UnsignedIntTy); 2583 return false; 2584 } 2585 2586 // The first argument needs to be a record field access. 2587 // If it is an array element access, we delay decision 2588 // to BPF backend to check whether the access is a 2589 // field access or not. 2590 Arg = TheCall->getArg(0); 2591 if (Arg->getType()->getAsPlaceholderType() || 2592 (Arg->IgnoreParens()->getObjectKind() != OK_BitField && 2593 !dyn_cast<MemberExpr>(Arg->IgnoreParens()) && 2594 !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) { 2595 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field) 2596 << 1 << Arg->getSourceRange(); 2597 return true; 2598 } 2599 2600 // The second argument needs to be a constant int 2601 Arg = TheCall->getArg(1); 2602 if (!Arg->isIntegerConstantExpr(Context)) { 2603 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const) 2604 << 2 << Arg->getSourceRange(); 2605 return true; 2606 } 2607 2608 TheCall->setType(Context.UnsignedIntTy); 2609 return false; 2610 } 2611 2612 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2613 struct ArgInfo { 2614 uint8_t OpNum; 2615 bool IsSigned; 2616 uint8_t BitWidth; 2617 uint8_t Align; 2618 }; 2619 struct BuiltinInfo { 2620 unsigned BuiltinID; 2621 ArgInfo Infos[2]; 2622 }; 2623 2624 static BuiltinInfo Infos[] = { 2625 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2626 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2627 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2628 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2629 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2630 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2631 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2632 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2633 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2634 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2635 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2636 2637 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2638 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2639 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2640 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2641 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2642 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2643 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2644 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2645 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2646 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2647 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2648 2649 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2650 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2651 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2652 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2653 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2654 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2655 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2656 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2657 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2658 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2659 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2660 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2661 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2662 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2663 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2664 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2665 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2666 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2667 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2668 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2669 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2670 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2671 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2672 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2673 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2674 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2675 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2676 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2677 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2678 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2679 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2680 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2681 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2682 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2683 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2684 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2685 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2686 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2687 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2688 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2689 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2690 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2691 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2692 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2693 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2694 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2695 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2696 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2697 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2698 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2699 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2700 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2701 {{ 1, false, 6, 0 }} }, 2702 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2703 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2704 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2705 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2706 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2707 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2708 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2709 {{ 1, false, 5, 0 }} }, 2710 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2711 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2712 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2713 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2714 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2715 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2716 { 2, false, 5, 0 }} }, 2717 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2718 { 2, false, 6, 0 }} }, 2719 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2720 { 3, false, 5, 0 }} }, 2721 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2722 { 3, false, 6, 0 }} }, 2723 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2724 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2725 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2726 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2727 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2728 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2729 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2730 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2731 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2732 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2733 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2734 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2735 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2736 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2737 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2738 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2739 {{ 2, false, 4, 0 }, 2740 { 3, false, 5, 0 }} }, 2741 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2742 {{ 2, false, 4, 0 }, 2743 { 3, false, 5, 0 }} }, 2744 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2745 {{ 2, false, 4, 0 }, 2746 { 3, false, 5, 0 }} }, 2747 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2748 {{ 2, false, 4, 0 }, 2749 { 3, false, 5, 0 }} }, 2750 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2751 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2752 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2753 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2754 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2755 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2756 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2757 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2758 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2759 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2760 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2761 { 2, false, 5, 0 }} }, 2762 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2763 { 2, false, 6, 0 }} }, 2764 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2765 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2766 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2767 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2768 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2769 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2770 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2771 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2772 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2773 {{ 1, false, 4, 0 }} }, 2774 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2775 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2776 {{ 1, false, 4, 0 }} }, 2777 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2778 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2779 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2780 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2781 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2782 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2783 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2784 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2785 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2786 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2787 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2788 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2789 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2790 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2791 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2792 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2793 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2794 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2795 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2796 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2797 {{ 3, false, 1, 0 }} }, 2798 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2799 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2800 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2801 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2802 {{ 3, false, 1, 0 }} }, 2803 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2804 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2805 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2806 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2807 {{ 3, false, 1, 0 }} }, 2808 }; 2809 2810 // Use a dynamically initialized static to sort the table exactly once on 2811 // first run. 2812 static const bool SortOnce = 2813 (llvm::sort(Infos, 2814 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2815 return LHS.BuiltinID < RHS.BuiltinID; 2816 }), 2817 true); 2818 (void)SortOnce; 2819 2820 const BuiltinInfo *F = llvm::partition_point( 2821 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2822 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2823 return false; 2824 2825 bool Error = false; 2826 2827 for (const ArgInfo &A : F->Infos) { 2828 // Ignore empty ArgInfo elements. 2829 if (A.BitWidth == 0) 2830 continue; 2831 2832 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2833 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2834 if (!A.Align) { 2835 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2836 } else { 2837 unsigned M = 1 << A.Align; 2838 Min *= M; 2839 Max *= M; 2840 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2841 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2842 } 2843 } 2844 return Error; 2845 } 2846 2847 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2848 CallExpr *TheCall) { 2849 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2850 } 2851 2852 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2853 unsigned BuiltinID, CallExpr *TheCall) { 2854 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2855 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2856 } 2857 2858 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2859 CallExpr *TheCall) { 2860 2861 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2862 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2863 if (!TI.hasFeature("dsp")) 2864 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2865 } 2866 2867 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2868 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2869 if (!TI.hasFeature("dspr2")) 2870 return Diag(TheCall->getBeginLoc(), 2871 diag::err_mips_builtin_requires_dspr2); 2872 } 2873 2874 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2875 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2876 if (!TI.hasFeature("msa")) 2877 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2878 } 2879 2880 return false; 2881 } 2882 2883 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2884 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2885 // ordering for DSP is unspecified. MSA is ordered by the data format used 2886 // by the underlying instruction i.e., df/m, df/n and then by size. 2887 // 2888 // FIXME: The size tests here should instead be tablegen'd along with the 2889 // definitions from include/clang/Basic/BuiltinsMips.def. 2890 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2891 // be too. 2892 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2893 unsigned i = 0, l = 0, u = 0, m = 0; 2894 switch (BuiltinID) { 2895 default: return false; 2896 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2897 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2898 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2899 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2900 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2901 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2902 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2903 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 2904 // df/m field. 2905 // These intrinsics take an unsigned 3 bit immediate. 2906 case Mips::BI__builtin_msa_bclri_b: 2907 case Mips::BI__builtin_msa_bnegi_b: 2908 case Mips::BI__builtin_msa_bseti_b: 2909 case Mips::BI__builtin_msa_sat_s_b: 2910 case Mips::BI__builtin_msa_sat_u_b: 2911 case Mips::BI__builtin_msa_slli_b: 2912 case Mips::BI__builtin_msa_srai_b: 2913 case Mips::BI__builtin_msa_srari_b: 2914 case Mips::BI__builtin_msa_srli_b: 2915 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2916 case Mips::BI__builtin_msa_binsli_b: 2917 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2918 // These intrinsics take an unsigned 4 bit immediate. 2919 case Mips::BI__builtin_msa_bclri_h: 2920 case Mips::BI__builtin_msa_bnegi_h: 2921 case Mips::BI__builtin_msa_bseti_h: 2922 case Mips::BI__builtin_msa_sat_s_h: 2923 case Mips::BI__builtin_msa_sat_u_h: 2924 case Mips::BI__builtin_msa_slli_h: 2925 case Mips::BI__builtin_msa_srai_h: 2926 case Mips::BI__builtin_msa_srari_h: 2927 case Mips::BI__builtin_msa_srli_h: 2928 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2929 case Mips::BI__builtin_msa_binsli_h: 2930 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2931 // These intrinsics take an unsigned 5 bit immediate. 2932 // The first block of intrinsics actually have an unsigned 5 bit field, 2933 // not a df/n field. 2934 case Mips::BI__builtin_msa_cfcmsa: 2935 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 2936 case Mips::BI__builtin_msa_clei_u_b: 2937 case Mips::BI__builtin_msa_clei_u_h: 2938 case Mips::BI__builtin_msa_clei_u_w: 2939 case Mips::BI__builtin_msa_clei_u_d: 2940 case Mips::BI__builtin_msa_clti_u_b: 2941 case Mips::BI__builtin_msa_clti_u_h: 2942 case Mips::BI__builtin_msa_clti_u_w: 2943 case Mips::BI__builtin_msa_clti_u_d: 2944 case Mips::BI__builtin_msa_maxi_u_b: 2945 case Mips::BI__builtin_msa_maxi_u_h: 2946 case Mips::BI__builtin_msa_maxi_u_w: 2947 case Mips::BI__builtin_msa_maxi_u_d: 2948 case Mips::BI__builtin_msa_mini_u_b: 2949 case Mips::BI__builtin_msa_mini_u_h: 2950 case Mips::BI__builtin_msa_mini_u_w: 2951 case Mips::BI__builtin_msa_mini_u_d: 2952 case Mips::BI__builtin_msa_addvi_b: 2953 case Mips::BI__builtin_msa_addvi_h: 2954 case Mips::BI__builtin_msa_addvi_w: 2955 case Mips::BI__builtin_msa_addvi_d: 2956 case Mips::BI__builtin_msa_bclri_w: 2957 case Mips::BI__builtin_msa_bnegi_w: 2958 case Mips::BI__builtin_msa_bseti_w: 2959 case Mips::BI__builtin_msa_sat_s_w: 2960 case Mips::BI__builtin_msa_sat_u_w: 2961 case Mips::BI__builtin_msa_slli_w: 2962 case Mips::BI__builtin_msa_srai_w: 2963 case Mips::BI__builtin_msa_srari_w: 2964 case Mips::BI__builtin_msa_srli_w: 2965 case Mips::BI__builtin_msa_srlri_w: 2966 case Mips::BI__builtin_msa_subvi_b: 2967 case Mips::BI__builtin_msa_subvi_h: 2968 case Mips::BI__builtin_msa_subvi_w: 2969 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2970 case Mips::BI__builtin_msa_binsli_w: 2971 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2972 // These intrinsics take an unsigned 6 bit immediate. 2973 case Mips::BI__builtin_msa_bclri_d: 2974 case Mips::BI__builtin_msa_bnegi_d: 2975 case Mips::BI__builtin_msa_bseti_d: 2976 case Mips::BI__builtin_msa_sat_s_d: 2977 case Mips::BI__builtin_msa_sat_u_d: 2978 case Mips::BI__builtin_msa_slli_d: 2979 case Mips::BI__builtin_msa_srai_d: 2980 case Mips::BI__builtin_msa_srari_d: 2981 case Mips::BI__builtin_msa_srli_d: 2982 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2983 case Mips::BI__builtin_msa_binsli_d: 2984 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2985 // These intrinsics take a signed 5 bit immediate. 2986 case Mips::BI__builtin_msa_ceqi_b: 2987 case Mips::BI__builtin_msa_ceqi_h: 2988 case Mips::BI__builtin_msa_ceqi_w: 2989 case Mips::BI__builtin_msa_ceqi_d: 2990 case Mips::BI__builtin_msa_clti_s_b: 2991 case Mips::BI__builtin_msa_clti_s_h: 2992 case Mips::BI__builtin_msa_clti_s_w: 2993 case Mips::BI__builtin_msa_clti_s_d: 2994 case Mips::BI__builtin_msa_clei_s_b: 2995 case Mips::BI__builtin_msa_clei_s_h: 2996 case Mips::BI__builtin_msa_clei_s_w: 2997 case Mips::BI__builtin_msa_clei_s_d: 2998 case Mips::BI__builtin_msa_maxi_s_b: 2999 case Mips::BI__builtin_msa_maxi_s_h: 3000 case Mips::BI__builtin_msa_maxi_s_w: 3001 case Mips::BI__builtin_msa_maxi_s_d: 3002 case Mips::BI__builtin_msa_mini_s_b: 3003 case Mips::BI__builtin_msa_mini_s_h: 3004 case Mips::BI__builtin_msa_mini_s_w: 3005 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 3006 // These intrinsics take an unsigned 8 bit immediate. 3007 case Mips::BI__builtin_msa_andi_b: 3008 case Mips::BI__builtin_msa_nori_b: 3009 case Mips::BI__builtin_msa_ori_b: 3010 case Mips::BI__builtin_msa_shf_b: 3011 case Mips::BI__builtin_msa_shf_h: 3012 case Mips::BI__builtin_msa_shf_w: 3013 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 3014 case Mips::BI__builtin_msa_bseli_b: 3015 case Mips::BI__builtin_msa_bmnzi_b: 3016 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 3017 // df/n format 3018 // These intrinsics take an unsigned 4 bit immediate. 3019 case Mips::BI__builtin_msa_copy_s_b: 3020 case Mips::BI__builtin_msa_copy_u_b: 3021 case Mips::BI__builtin_msa_insve_b: 3022 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 3023 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 3024 // These intrinsics take an unsigned 3 bit immediate. 3025 case Mips::BI__builtin_msa_copy_s_h: 3026 case Mips::BI__builtin_msa_copy_u_h: 3027 case Mips::BI__builtin_msa_insve_h: 3028 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 3029 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 3030 // These intrinsics take an unsigned 2 bit immediate. 3031 case Mips::BI__builtin_msa_copy_s_w: 3032 case Mips::BI__builtin_msa_copy_u_w: 3033 case Mips::BI__builtin_msa_insve_w: 3034 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 3035 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 3036 // These intrinsics take an unsigned 1 bit immediate. 3037 case Mips::BI__builtin_msa_copy_s_d: 3038 case Mips::BI__builtin_msa_copy_u_d: 3039 case Mips::BI__builtin_msa_insve_d: 3040 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 3041 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 3042 // Memory offsets and immediate loads. 3043 // These intrinsics take a signed 10 bit immediate. 3044 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 3045 case Mips::BI__builtin_msa_ldi_h: 3046 case Mips::BI__builtin_msa_ldi_w: 3047 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3048 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3049 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3050 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3051 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3052 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3053 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3054 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3055 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3056 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3057 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3058 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3059 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3060 } 3061 3062 if (!m) 3063 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3064 3065 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3066 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3067 } 3068 3069 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3070 CallExpr *TheCall) { 3071 unsigned i = 0, l = 0, u = 0; 3072 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3073 BuiltinID == PPC::BI__builtin_divdeu || 3074 BuiltinID == PPC::BI__builtin_bpermd; 3075 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3076 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3077 BuiltinID == PPC::BI__builtin_divweu || 3078 BuiltinID == PPC::BI__builtin_divde || 3079 BuiltinID == PPC::BI__builtin_divdeu; 3080 3081 if (Is64BitBltin && !IsTarget64Bit) 3082 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3083 << TheCall->getSourceRange(); 3084 3085 if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) || 3086 (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd"))) 3087 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3088 << TheCall->getSourceRange(); 3089 3090 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3091 if (!TI.hasFeature("vsx")) 3092 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3093 << TheCall->getSourceRange(); 3094 return false; 3095 }; 3096 3097 switch (BuiltinID) { 3098 default: return false; 3099 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3100 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3101 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3102 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3103 case PPC::BI__builtin_altivec_dss: 3104 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3105 case PPC::BI__builtin_tbegin: 3106 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3107 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3108 case PPC::BI__builtin_tabortwc: 3109 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3110 case PPC::BI__builtin_tabortwci: 3111 case PPC::BI__builtin_tabortdci: 3112 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3113 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3114 case PPC::BI__builtin_altivec_dst: 3115 case PPC::BI__builtin_altivec_dstt: 3116 case PPC::BI__builtin_altivec_dstst: 3117 case PPC::BI__builtin_altivec_dststt: 3118 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3119 case PPC::BI__builtin_vsx_xxpermdi: 3120 case PPC::BI__builtin_vsx_xxsldwi: 3121 return SemaBuiltinVSX(TheCall); 3122 case PPC::BI__builtin_unpack_vector_int128: 3123 return SemaVSXCheck(TheCall) || 3124 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3125 case PPC::BI__builtin_pack_vector_int128: 3126 return SemaVSXCheck(TheCall); 3127 case PPC::BI__builtin_altivec_vgnb: 3128 return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7); 3129 case PPC::BI__builtin_vsx_xxeval: 3130 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255); 3131 case PPC::BI__builtin_altivec_vsldbi: 3132 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3133 case PPC::BI__builtin_altivec_vsrdbi: 3134 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7); 3135 case PPC::BI__builtin_vsx_xxpermx: 3136 return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7); 3137 } 3138 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3139 } 3140 3141 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3142 CallExpr *TheCall) { 3143 // position of memory order and scope arguments in the builtin 3144 unsigned OrderIndex, ScopeIndex; 3145 switch (BuiltinID) { 3146 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3147 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3148 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3149 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3150 OrderIndex = 2; 3151 ScopeIndex = 3; 3152 break; 3153 case AMDGPU::BI__builtin_amdgcn_fence: 3154 OrderIndex = 0; 3155 ScopeIndex = 1; 3156 break; 3157 default: 3158 return false; 3159 } 3160 3161 ExprResult Arg = TheCall->getArg(OrderIndex); 3162 auto ArgExpr = Arg.get(); 3163 Expr::EvalResult ArgResult; 3164 3165 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3166 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3167 << ArgExpr->getType(); 3168 int ord = ArgResult.Val.getInt().getZExtValue(); 3169 3170 // Check valididty of memory ordering as per C11 / C++11's memody model. 3171 switch (static_cast<llvm::AtomicOrderingCABI>(ord)) { 3172 case llvm::AtomicOrderingCABI::acquire: 3173 case llvm::AtomicOrderingCABI::release: 3174 case llvm::AtomicOrderingCABI::acq_rel: 3175 case llvm::AtomicOrderingCABI::seq_cst: 3176 break; 3177 default: { 3178 return Diag(ArgExpr->getBeginLoc(), 3179 diag::warn_atomic_op_has_invalid_memory_order) 3180 << ArgExpr->getSourceRange(); 3181 } 3182 } 3183 3184 Arg = TheCall->getArg(ScopeIndex); 3185 ArgExpr = Arg.get(); 3186 Expr::EvalResult ArgResult1; 3187 // Check that sync scope is a constant literal 3188 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen, 3189 Context)) 3190 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3191 << ArgExpr->getType(); 3192 3193 return false; 3194 } 3195 3196 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3197 CallExpr *TheCall) { 3198 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3199 Expr *Arg = TheCall->getArg(0); 3200 if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context)) 3201 if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256) 3202 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3203 << Arg->getSourceRange(); 3204 } 3205 3206 // For intrinsics which take an immediate value as part of the instruction, 3207 // range check them here. 3208 unsigned i = 0, l = 0, u = 0; 3209 switch (BuiltinID) { 3210 default: return false; 3211 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3212 case SystemZ::BI__builtin_s390_verimb: 3213 case SystemZ::BI__builtin_s390_verimh: 3214 case SystemZ::BI__builtin_s390_verimf: 3215 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3216 case SystemZ::BI__builtin_s390_vfaeb: 3217 case SystemZ::BI__builtin_s390_vfaeh: 3218 case SystemZ::BI__builtin_s390_vfaef: 3219 case SystemZ::BI__builtin_s390_vfaebs: 3220 case SystemZ::BI__builtin_s390_vfaehs: 3221 case SystemZ::BI__builtin_s390_vfaefs: 3222 case SystemZ::BI__builtin_s390_vfaezb: 3223 case SystemZ::BI__builtin_s390_vfaezh: 3224 case SystemZ::BI__builtin_s390_vfaezf: 3225 case SystemZ::BI__builtin_s390_vfaezbs: 3226 case SystemZ::BI__builtin_s390_vfaezhs: 3227 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3228 case SystemZ::BI__builtin_s390_vfisb: 3229 case SystemZ::BI__builtin_s390_vfidb: 3230 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3231 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3232 case SystemZ::BI__builtin_s390_vftcisb: 3233 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3234 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3235 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3236 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3237 case SystemZ::BI__builtin_s390_vstrcb: 3238 case SystemZ::BI__builtin_s390_vstrch: 3239 case SystemZ::BI__builtin_s390_vstrcf: 3240 case SystemZ::BI__builtin_s390_vstrczb: 3241 case SystemZ::BI__builtin_s390_vstrczh: 3242 case SystemZ::BI__builtin_s390_vstrczf: 3243 case SystemZ::BI__builtin_s390_vstrcbs: 3244 case SystemZ::BI__builtin_s390_vstrchs: 3245 case SystemZ::BI__builtin_s390_vstrcfs: 3246 case SystemZ::BI__builtin_s390_vstrczbs: 3247 case SystemZ::BI__builtin_s390_vstrczhs: 3248 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3249 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3250 case SystemZ::BI__builtin_s390_vfminsb: 3251 case SystemZ::BI__builtin_s390_vfmaxsb: 3252 case SystemZ::BI__builtin_s390_vfmindb: 3253 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3254 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3255 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3256 } 3257 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3258 } 3259 3260 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3261 /// This checks that the target supports __builtin_cpu_supports and 3262 /// that the string argument is constant and valid. 3263 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3264 CallExpr *TheCall) { 3265 Expr *Arg = TheCall->getArg(0); 3266 3267 // Check if the argument is a string literal. 3268 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3269 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3270 << Arg->getSourceRange(); 3271 3272 // Check the contents of the string. 3273 StringRef Feature = 3274 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3275 if (!TI.validateCpuSupports(Feature)) 3276 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3277 << Arg->getSourceRange(); 3278 return false; 3279 } 3280 3281 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3282 /// This checks that the target supports __builtin_cpu_is and 3283 /// that the string argument is constant and valid. 3284 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3285 Expr *Arg = TheCall->getArg(0); 3286 3287 // Check if the argument is a string literal. 3288 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3289 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3290 << Arg->getSourceRange(); 3291 3292 // Check the contents of the string. 3293 StringRef Feature = 3294 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3295 if (!TI.validateCpuIs(Feature)) 3296 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3297 << Arg->getSourceRange(); 3298 return false; 3299 } 3300 3301 // Check if the rounding mode is legal. 3302 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3303 // Indicates if this instruction has rounding control or just SAE. 3304 bool HasRC = false; 3305 3306 unsigned ArgNum = 0; 3307 switch (BuiltinID) { 3308 default: 3309 return false; 3310 case X86::BI__builtin_ia32_vcvttsd2si32: 3311 case X86::BI__builtin_ia32_vcvttsd2si64: 3312 case X86::BI__builtin_ia32_vcvttsd2usi32: 3313 case X86::BI__builtin_ia32_vcvttsd2usi64: 3314 case X86::BI__builtin_ia32_vcvttss2si32: 3315 case X86::BI__builtin_ia32_vcvttss2si64: 3316 case X86::BI__builtin_ia32_vcvttss2usi32: 3317 case X86::BI__builtin_ia32_vcvttss2usi64: 3318 ArgNum = 1; 3319 break; 3320 case X86::BI__builtin_ia32_maxpd512: 3321 case X86::BI__builtin_ia32_maxps512: 3322 case X86::BI__builtin_ia32_minpd512: 3323 case X86::BI__builtin_ia32_minps512: 3324 ArgNum = 2; 3325 break; 3326 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3327 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3328 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3329 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3330 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3331 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3332 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3333 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3334 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3335 case X86::BI__builtin_ia32_exp2pd_mask: 3336 case X86::BI__builtin_ia32_exp2ps_mask: 3337 case X86::BI__builtin_ia32_getexppd512_mask: 3338 case X86::BI__builtin_ia32_getexpps512_mask: 3339 case X86::BI__builtin_ia32_rcp28pd_mask: 3340 case X86::BI__builtin_ia32_rcp28ps_mask: 3341 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3342 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3343 case X86::BI__builtin_ia32_vcomisd: 3344 case X86::BI__builtin_ia32_vcomiss: 3345 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3346 ArgNum = 3; 3347 break; 3348 case X86::BI__builtin_ia32_cmppd512_mask: 3349 case X86::BI__builtin_ia32_cmpps512_mask: 3350 case X86::BI__builtin_ia32_cmpsd_mask: 3351 case X86::BI__builtin_ia32_cmpss_mask: 3352 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3353 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3354 case X86::BI__builtin_ia32_getexpss128_round_mask: 3355 case X86::BI__builtin_ia32_getmantpd512_mask: 3356 case X86::BI__builtin_ia32_getmantps512_mask: 3357 case X86::BI__builtin_ia32_maxsd_round_mask: 3358 case X86::BI__builtin_ia32_maxss_round_mask: 3359 case X86::BI__builtin_ia32_minsd_round_mask: 3360 case X86::BI__builtin_ia32_minss_round_mask: 3361 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3362 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3363 case X86::BI__builtin_ia32_reducepd512_mask: 3364 case X86::BI__builtin_ia32_reduceps512_mask: 3365 case X86::BI__builtin_ia32_rndscalepd_mask: 3366 case X86::BI__builtin_ia32_rndscaleps_mask: 3367 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3368 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3369 ArgNum = 4; 3370 break; 3371 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3372 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3373 case X86::BI__builtin_ia32_fixupimmps512_mask: 3374 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3375 case X86::BI__builtin_ia32_fixupimmsd_mask: 3376 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3377 case X86::BI__builtin_ia32_fixupimmss_mask: 3378 case X86::BI__builtin_ia32_fixupimmss_maskz: 3379 case X86::BI__builtin_ia32_getmantsd_round_mask: 3380 case X86::BI__builtin_ia32_getmantss_round_mask: 3381 case X86::BI__builtin_ia32_rangepd512_mask: 3382 case X86::BI__builtin_ia32_rangeps512_mask: 3383 case X86::BI__builtin_ia32_rangesd128_round_mask: 3384 case X86::BI__builtin_ia32_rangess128_round_mask: 3385 case X86::BI__builtin_ia32_reducesd_mask: 3386 case X86::BI__builtin_ia32_reducess_mask: 3387 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3388 case X86::BI__builtin_ia32_rndscaless_round_mask: 3389 ArgNum = 5; 3390 break; 3391 case X86::BI__builtin_ia32_vcvtsd2si64: 3392 case X86::BI__builtin_ia32_vcvtsd2si32: 3393 case X86::BI__builtin_ia32_vcvtsd2usi32: 3394 case X86::BI__builtin_ia32_vcvtsd2usi64: 3395 case X86::BI__builtin_ia32_vcvtss2si32: 3396 case X86::BI__builtin_ia32_vcvtss2si64: 3397 case X86::BI__builtin_ia32_vcvtss2usi32: 3398 case X86::BI__builtin_ia32_vcvtss2usi64: 3399 case X86::BI__builtin_ia32_sqrtpd512: 3400 case X86::BI__builtin_ia32_sqrtps512: 3401 ArgNum = 1; 3402 HasRC = true; 3403 break; 3404 case X86::BI__builtin_ia32_addpd512: 3405 case X86::BI__builtin_ia32_addps512: 3406 case X86::BI__builtin_ia32_divpd512: 3407 case X86::BI__builtin_ia32_divps512: 3408 case X86::BI__builtin_ia32_mulpd512: 3409 case X86::BI__builtin_ia32_mulps512: 3410 case X86::BI__builtin_ia32_subpd512: 3411 case X86::BI__builtin_ia32_subps512: 3412 case X86::BI__builtin_ia32_cvtsi2sd64: 3413 case X86::BI__builtin_ia32_cvtsi2ss32: 3414 case X86::BI__builtin_ia32_cvtsi2ss64: 3415 case X86::BI__builtin_ia32_cvtusi2sd64: 3416 case X86::BI__builtin_ia32_cvtusi2ss32: 3417 case X86::BI__builtin_ia32_cvtusi2ss64: 3418 ArgNum = 2; 3419 HasRC = true; 3420 break; 3421 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3422 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3423 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3424 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3425 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3426 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3427 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3428 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3429 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3430 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3431 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3432 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3433 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3434 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3435 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3436 ArgNum = 3; 3437 HasRC = true; 3438 break; 3439 case X86::BI__builtin_ia32_addss_round_mask: 3440 case X86::BI__builtin_ia32_addsd_round_mask: 3441 case X86::BI__builtin_ia32_divss_round_mask: 3442 case X86::BI__builtin_ia32_divsd_round_mask: 3443 case X86::BI__builtin_ia32_mulss_round_mask: 3444 case X86::BI__builtin_ia32_mulsd_round_mask: 3445 case X86::BI__builtin_ia32_subss_round_mask: 3446 case X86::BI__builtin_ia32_subsd_round_mask: 3447 case X86::BI__builtin_ia32_scalefpd512_mask: 3448 case X86::BI__builtin_ia32_scalefps512_mask: 3449 case X86::BI__builtin_ia32_scalefsd_round_mask: 3450 case X86::BI__builtin_ia32_scalefss_round_mask: 3451 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3452 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3453 case X86::BI__builtin_ia32_sqrtss_round_mask: 3454 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3455 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3456 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3457 case X86::BI__builtin_ia32_vfmaddss3_mask: 3458 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3459 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3460 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3461 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3462 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3463 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3464 case X86::BI__builtin_ia32_vfmaddps512_mask: 3465 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3466 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3467 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3468 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3469 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3470 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3471 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3472 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3473 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3474 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3475 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3476 ArgNum = 4; 3477 HasRC = true; 3478 break; 3479 } 3480 3481 llvm::APSInt Result; 3482 3483 // We can't check the value of a dependent argument. 3484 Expr *Arg = TheCall->getArg(ArgNum); 3485 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3486 return false; 3487 3488 // Check constant-ness first. 3489 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3490 return true; 3491 3492 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3493 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3494 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3495 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3496 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3497 Result == 8/*ROUND_NO_EXC*/ || 3498 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3499 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3500 return false; 3501 3502 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3503 << Arg->getSourceRange(); 3504 } 3505 3506 // Check if the gather/scatter scale is legal. 3507 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3508 CallExpr *TheCall) { 3509 unsigned ArgNum = 0; 3510 switch (BuiltinID) { 3511 default: 3512 return false; 3513 case X86::BI__builtin_ia32_gatherpfdpd: 3514 case X86::BI__builtin_ia32_gatherpfdps: 3515 case X86::BI__builtin_ia32_gatherpfqpd: 3516 case X86::BI__builtin_ia32_gatherpfqps: 3517 case X86::BI__builtin_ia32_scatterpfdpd: 3518 case X86::BI__builtin_ia32_scatterpfdps: 3519 case X86::BI__builtin_ia32_scatterpfqpd: 3520 case X86::BI__builtin_ia32_scatterpfqps: 3521 ArgNum = 3; 3522 break; 3523 case X86::BI__builtin_ia32_gatherd_pd: 3524 case X86::BI__builtin_ia32_gatherd_pd256: 3525 case X86::BI__builtin_ia32_gatherq_pd: 3526 case X86::BI__builtin_ia32_gatherq_pd256: 3527 case X86::BI__builtin_ia32_gatherd_ps: 3528 case X86::BI__builtin_ia32_gatherd_ps256: 3529 case X86::BI__builtin_ia32_gatherq_ps: 3530 case X86::BI__builtin_ia32_gatherq_ps256: 3531 case X86::BI__builtin_ia32_gatherd_q: 3532 case X86::BI__builtin_ia32_gatherd_q256: 3533 case X86::BI__builtin_ia32_gatherq_q: 3534 case X86::BI__builtin_ia32_gatherq_q256: 3535 case X86::BI__builtin_ia32_gatherd_d: 3536 case X86::BI__builtin_ia32_gatherd_d256: 3537 case X86::BI__builtin_ia32_gatherq_d: 3538 case X86::BI__builtin_ia32_gatherq_d256: 3539 case X86::BI__builtin_ia32_gather3div2df: 3540 case X86::BI__builtin_ia32_gather3div2di: 3541 case X86::BI__builtin_ia32_gather3div4df: 3542 case X86::BI__builtin_ia32_gather3div4di: 3543 case X86::BI__builtin_ia32_gather3div4sf: 3544 case X86::BI__builtin_ia32_gather3div4si: 3545 case X86::BI__builtin_ia32_gather3div8sf: 3546 case X86::BI__builtin_ia32_gather3div8si: 3547 case X86::BI__builtin_ia32_gather3siv2df: 3548 case X86::BI__builtin_ia32_gather3siv2di: 3549 case X86::BI__builtin_ia32_gather3siv4df: 3550 case X86::BI__builtin_ia32_gather3siv4di: 3551 case X86::BI__builtin_ia32_gather3siv4sf: 3552 case X86::BI__builtin_ia32_gather3siv4si: 3553 case X86::BI__builtin_ia32_gather3siv8sf: 3554 case X86::BI__builtin_ia32_gather3siv8si: 3555 case X86::BI__builtin_ia32_gathersiv8df: 3556 case X86::BI__builtin_ia32_gathersiv16sf: 3557 case X86::BI__builtin_ia32_gatherdiv8df: 3558 case X86::BI__builtin_ia32_gatherdiv16sf: 3559 case X86::BI__builtin_ia32_gathersiv8di: 3560 case X86::BI__builtin_ia32_gathersiv16si: 3561 case X86::BI__builtin_ia32_gatherdiv8di: 3562 case X86::BI__builtin_ia32_gatherdiv16si: 3563 case X86::BI__builtin_ia32_scatterdiv2df: 3564 case X86::BI__builtin_ia32_scatterdiv2di: 3565 case X86::BI__builtin_ia32_scatterdiv4df: 3566 case X86::BI__builtin_ia32_scatterdiv4di: 3567 case X86::BI__builtin_ia32_scatterdiv4sf: 3568 case X86::BI__builtin_ia32_scatterdiv4si: 3569 case X86::BI__builtin_ia32_scatterdiv8sf: 3570 case X86::BI__builtin_ia32_scatterdiv8si: 3571 case X86::BI__builtin_ia32_scattersiv2df: 3572 case X86::BI__builtin_ia32_scattersiv2di: 3573 case X86::BI__builtin_ia32_scattersiv4df: 3574 case X86::BI__builtin_ia32_scattersiv4di: 3575 case X86::BI__builtin_ia32_scattersiv4sf: 3576 case X86::BI__builtin_ia32_scattersiv4si: 3577 case X86::BI__builtin_ia32_scattersiv8sf: 3578 case X86::BI__builtin_ia32_scattersiv8si: 3579 case X86::BI__builtin_ia32_scattersiv8df: 3580 case X86::BI__builtin_ia32_scattersiv16sf: 3581 case X86::BI__builtin_ia32_scatterdiv8df: 3582 case X86::BI__builtin_ia32_scatterdiv16sf: 3583 case X86::BI__builtin_ia32_scattersiv8di: 3584 case X86::BI__builtin_ia32_scattersiv16si: 3585 case X86::BI__builtin_ia32_scatterdiv8di: 3586 case X86::BI__builtin_ia32_scatterdiv16si: 3587 ArgNum = 4; 3588 break; 3589 } 3590 3591 llvm::APSInt Result; 3592 3593 // We can't check the value of a dependent argument. 3594 Expr *Arg = TheCall->getArg(ArgNum); 3595 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3596 return false; 3597 3598 // Check constant-ness first. 3599 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3600 return true; 3601 3602 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3603 return false; 3604 3605 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3606 << Arg->getSourceRange(); 3607 } 3608 3609 enum { TileRegLow = 0, TileRegHigh = 7 }; 3610 3611 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, 3612 ArrayRef<int> ArgNums) { 3613 for (int ArgNum : ArgNums) { 3614 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh)) 3615 return true; 3616 } 3617 return false; 3618 } 3619 3620 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, int ArgNum) { 3621 return SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh); 3622 } 3623 3624 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall, 3625 ArrayRef<int> ArgNums) { 3626 // Because the max number of tile register is TileRegHigh + 1, so here we use 3627 // each bit to represent the usage of them in bitset. 3628 std::bitset<TileRegHigh + 1> ArgValues; 3629 for (int ArgNum : ArgNums) { 3630 llvm::APSInt Arg; 3631 SemaBuiltinConstantArg(TheCall, ArgNum, Arg); 3632 int ArgExtValue = Arg.getExtValue(); 3633 assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) && 3634 "Incorrect tile register num."); 3635 if (ArgValues.test(ArgExtValue)) 3636 return Diag(TheCall->getBeginLoc(), 3637 diag::err_x86_builtin_tile_arg_duplicate) 3638 << TheCall->getArg(ArgNum)->getSourceRange(); 3639 ArgValues.set(ArgExtValue); 3640 } 3641 return false; 3642 } 3643 3644 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, 3645 ArrayRef<int> ArgNums) { 3646 return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) || 3647 CheckX86BuiltinTileDuplicate(TheCall, ArgNums); 3648 } 3649 3650 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) { 3651 switch (BuiltinID) { 3652 default: 3653 return false; 3654 case X86::BI__builtin_ia32_tileloadd64: 3655 case X86::BI__builtin_ia32_tileloaddt164: 3656 case X86::BI__builtin_ia32_tilestored64: 3657 case X86::BI__builtin_ia32_tilezero: 3658 return CheckX86BuiltinTileArgumentsRange(TheCall, 0); 3659 case X86::BI__builtin_ia32_tdpbssd: 3660 case X86::BI__builtin_ia32_tdpbsud: 3661 case X86::BI__builtin_ia32_tdpbusd: 3662 case X86::BI__builtin_ia32_tdpbuud: 3663 case X86::BI__builtin_ia32_tdpbf16ps: 3664 return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2}); 3665 } 3666 } 3667 static bool isX86_32Builtin(unsigned BuiltinID) { 3668 // These builtins only work on x86-32 targets. 3669 switch (BuiltinID) { 3670 case X86::BI__builtin_ia32_readeflags_u32: 3671 case X86::BI__builtin_ia32_writeeflags_u32: 3672 return true; 3673 } 3674 3675 return false; 3676 } 3677 3678 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3679 CallExpr *TheCall) { 3680 if (BuiltinID == X86::BI__builtin_cpu_supports) 3681 return SemaBuiltinCpuSupports(*this, TI, TheCall); 3682 3683 if (BuiltinID == X86::BI__builtin_cpu_is) 3684 return SemaBuiltinCpuIs(*this, TI, TheCall); 3685 3686 // Check for 32-bit only builtins on a 64-bit target. 3687 const llvm::Triple &TT = TI.getTriple(); 3688 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3689 return Diag(TheCall->getCallee()->getBeginLoc(), 3690 diag::err_32_bit_builtin_64_bit_tgt); 3691 3692 // If the intrinsic has rounding or SAE make sure its valid. 3693 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3694 return true; 3695 3696 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3697 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3698 return true; 3699 3700 // If the intrinsic has a tile arguments, make sure they are valid. 3701 if (CheckX86BuiltinTileArguments(BuiltinID, TheCall)) 3702 return true; 3703 3704 // For intrinsics which take an immediate value as part of the instruction, 3705 // range check them here. 3706 int i = 0, l = 0, u = 0; 3707 switch (BuiltinID) { 3708 default: 3709 return false; 3710 case X86::BI__builtin_ia32_vec_ext_v2si: 3711 case X86::BI__builtin_ia32_vec_ext_v2di: 3712 case X86::BI__builtin_ia32_vextractf128_pd256: 3713 case X86::BI__builtin_ia32_vextractf128_ps256: 3714 case X86::BI__builtin_ia32_vextractf128_si256: 3715 case X86::BI__builtin_ia32_extract128i256: 3716 case X86::BI__builtin_ia32_extractf64x4_mask: 3717 case X86::BI__builtin_ia32_extracti64x4_mask: 3718 case X86::BI__builtin_ia32_extractf32x8_mask: 3719 case X86::BI__builtin_ia32_extracti32x8_mask: 3720 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3721 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3722 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3723 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3724 i = 1; l = 0; u = 1; 3725 break; 3726 case X86::BI__builtin_ia32_vec_set_v2di: 3727 case X86::BI__builtin_ia32_vinsertf128_pd256: 3728 case X86::BI__builtin_ia32_vinsertf128_ps256: 3729 case X86::BI__builtin_ia32_vinsertf128_si256: 3730 case X86::BI__builtin_ia32_insert128i256: 3731 case X86::BI__builtin_ia32_insertf32x8: 3732 case X86::BI__builtin_ia32_inserti32x8: 3733 case X86::BI__builtin_ia32_insertf64x4: 3734 case X86::BI__builtin_ia32_inserti64x4: 3735 case X86::BI__builtin_ia32_insertf64x2_256: 3736 case X86::BI__builtin_ia32_inserti64x2_256: 3737 case X86::BI__builtin_ia32_insertf32x4_256: 3738 case X86::BI__builtin_ia32_inserti32x4_256: 3739 i = 2; l = 0; u = 1; 3740 break; 3741 case X86::BI__builtin_ia32_vpermilpd: 3742 case X86::BI__builtin_ia32_vec_ext_v4hi: 3743 case X86::BI__builtin_ia32_vec_ext_v4si: 3744 case X86::BI__builtin_ia32_vec_ext_v4sf: 3745 case X86::BI__builtin_ia32_vec_ext_v4di: 3746 case X86::BI__builtin_ia32_extractf32x4_mask: 3747 case X86::BI__builtin_ia32_extracti32x4_mask: 3748 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3749 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3750 i = 1; l = 0; u = 3; 3751 break; 3752 case X86::BI_mm_prefetch: 3753 case X86::BI__builtin_ia32_vec_ext_v8hi: 3754 case X86::BI__builtin_ia32_vec_ext_v8si: 3755 i = 1; l = 0; u = 7; 3756 break; 3757 case X86::BI__builtin_ia32_sha1rnds4: 3758 case X86::BI__builtin_ia32_blendpd: 3759 case X86::BI__builtin_ia32_shufpd: 3760 case X86::BI__builtin_ia32_vec_set_v4hi: 3761 case X86::BI__builtin_ia32_vec_set_v4si: 3762 case X86::BI__builtin_ia32_vec_set_v4di: 3763 case X86::BI__builtin_ia32_shuf_f32x4_256: 3764 case X86::BI__builtin_ia32_shuf_f64x2_256: 3765 case X86::BI__builtin_ia32_shuf_i32x4_256: 3766 case X86::BI__builtin_ia32_shuf_i64x2_256: 3767 case X86::BI__builtin_ia32_insertf64x2_512: 3768 case X86::BI__builtin_ia32_inserti64x2_512: 3769 case X86::BI__builtin_ia32_insertf32x4: 3770 case X86::BI__builtin_ia32_inserti32x4: 3771 i = 2; l = 0; u = 3; 3772 break; 3773 case X86::BI__builtin_ia32_vpermil2pd: 3774 case X86::BI__builtin_ia32_vpermil2pd256: 3775 case X86::BI__builtin_ia32_vpermil2ps: 3776 case X86::BI__builtin_ia32_vpermil2ps256: 3777 i = 3; l = 0; u = 3; 3778 break; 3779 case X86::BI__builtin_ia32_cmpb128_mask: 3780 case X86::BI__builtin_ia32_cmpw128_mask: 3781 case X86::BI__builtin_ia32_cmpd128_mask: 3782 case X86::BI__builtin_ia32_cmpq128_mask: 3783 case X86::BI__builtin_ia32_cmpb256_mask: 3784 case X86::BI__builtin_ia32_cmpw256_mask: 3785 case X86::BI__builtin_ia32_cmpd256_mask: 3786 case X86::BI__builtin_ia32_cmpq256_mask: 3787 case X86::BI__builtin_ia32_cmpb512_mask: 3788 case X86::BI__builtin_ia32_cmpw512_mask: 3789 case X86::BI__builtin_ia32_cmpd512_mask: 3790 case X86::BI__builtin_ia32_cmpq512_mask: 3791 case X86::BI__builtin_ia32_ucmpb128_mask: 3792 case X86::BI__builtin_ia32_ucmpw128_mask: 3793 case X86::BI__builtin_ia32_ucmpd128_mask: 3794 case X86::BI__builtin_ia32_ucmpq128_mask: 3795 case X86::BI__builtin_ia32_ucmpb256_mask: 3796 case X86::BI__builtin_ia32_ucmpw256_mask: 3797 case X86::BI__builtin_ia32_ucmpd256_mask: 3798 case X86::BI__builtin_ia32_ucmpq256_mask: 3799 case X86::BI__builtin_ia32_ucmpb512_mask: 3800 case X86::BI__builtin_ia32_ucmpw512_mask: 3801 case X86::BI__builtin_ia32_ucmpd512_mask: 3802 case X86::BI__builtin_ia32_ucmpq512_mask: 3803 case X86::BI__builtin_ia32_vpcomub: 3804 case X86::BI__builtin_ia32_vpcomuw: 3805 case X86::BI__builtin_ia32_vpcomud: 3806 case X86::BI__builtin_ia32_vpcomuq: 3807 case X86::BI__builtin_ia32_vpcomb: 3808 case X86::BI__builtin_ia32_vpcomw: 3809 case X86::BI__builtin_ia32_vpcomd: 3810 case X86::BI__builtin_ia32_vpcomq: 3811 case X86::BI__builtin_ia32_vec_set_v8hi: 3812 case X86::BI__builtin_ia32_vec_set_v8si: 3813 i = 2; l = 0; u = 7; 3814 break; 3815 case X86::BI__builtin_ia32_vpermilpd256: 3816 case X86::BI__builtin_ia32_roundps: 3817 case X86::BI__builtin_ia32_roundpd: 3818 case X86::BI__builtin_ia32_roundps256: 3819 case X86::BI__builtin_ia32_roundpd256: 3820 case X86::BI__builtin_ia32_getmantpd128_mask: 3821 case X86::BI__builtin_ia32_getmantpd256_mask: 3822 case X86::BI__builtin_ia32_getmantps128_mask: 3823 case X86::BI__builtin_ia32_getmantps256_mask: 3824 case X86::BI__builtin_ia32_getmantpd512_mask: 3825 case X86::BI__builtin_ia32_getmantps512_mask: 3826 case X86::BI__builtin_ia32_vec_ext_v16qi: 3827 case X86::BI__builtin_ia32_vec_ext_v16hi: 3828 i = 1; l = 0; u = 15; 3829 break; 3830 case X86::BI__builtin_ia32_pblendd128: 3831 case X86::BI__builtin_ia32_blendps: 3832 case X86::BI__builtin_ia32_blendpd256: 3833 case X86::BI__builtin_ia32_shufpd256: 3834 case X86::BI__builtin_ia32_roundss: 3835 case X86::BI__builtin_ia32_roundsd: 3836 case X86::BI__builtin_ia32_rangepd128_mask: 3837 case X86::BI__builtin_ia32_rangepd256_mask: 3838 case X86::BI__builtin_ia32_rangepd512_mask: 3839 case X86::BI__builtin_ia32_rangeps128_mask: 3840 case X86::BI__builtin_ia32_rangeps256_mask: 3841 case X86::BI__builtin_ia32_rangeps512_mask: 3842 case X86::BI__builtin_ia32_getmantsd_round_mask: 3843 case X86::BI__builtin_ia32_getmantss_round_mask: 3844 case X86::BI__builtin_ia32_vec_set_v16qi: 3845 case X86::BI__builtin_ia32_vec_set_v16hi: 3846 i = 2; l = 0; u = 15; 3847 break; 3848 case X86::BI__builtin_ia32_vec_ext_v32qi: 3849 i = 1; l = 0; u = 31; 3850 break; 3851 case X86::BI__builtin_ia32_cmpps: 3852 case X86::BI__builtin_ia32_cmpss: 3853 case X86::BI__builtin_ia32_cmppd: 3854 case X86::BI__builtin_ia32_cmpsd: 3855 case X86::BI__builtin_ia32_cmpps256: 3856 case X86::BI__builtin_ia32_cmppd256: 3857 case X86::BI__builtin_ia32_cmpps128_mask: 3858 case X86::BI__builtin_ia32_cmppd128_mask: 3859 case X86::BI__builtin_ia32_cmpps256_mask: 3860 case X86::BI__builtin_ia32_cmppd256_mask: 3861 case X86::BI__builtin_ia32_cmpps512_mask: 3862 case X86::BI__builtin_ia32_cmppd512_mask: 3863 case X86::BI__builtin_ia32_cmpsd_mask: 3864 case X86::BI__builtin_ia32_cmpss_mask: 3865 case X86::BI__builtin_ia32_vec_set_v32qi: 3866 i = 2; l = 0; u = 31; 3867 break; 3868 case X86::BI__builtin_ia32_permdf256: 3869 case X86::BI__builtin_ia32_permdi256: 3870 case X86::BI__builtin_ia32_permdf512: 3871 case X86::BI__builtin_ia32_permdi512: 3872 case X86::BI__builtin_ia32_vpermilps: 3873 case X86::BI__builtin_ia32_vpermilps256: 3874 case X86::BI__builtin_ia32_vpermilpd512: 3875 case X86::BI__builtin_ia32_vpermilps512: 3876 case X86::BI__builtin_ia32_pshufd: 3877 case X86::BI__builtin_ia32_pshufd256: 3878 case X86::BI__builtin_ia32_pshufd512: 3879 case X86::BI__builtin_ia32_pshufhw: 3880 case X86::BI__builtin_ia32_pshufhw256: 3881 case X86::BI__builtin_ia32_pshufhw512: 3882 case X86::BI__builtin_ia32_pshuflw: 3883 case X86::BI__builtin_ia32_pshuflw256: 3884 case X86::BI__builtin_ia32_pshuflw512: 3885 case X86::BI__builtin_ia32_vcvtps2ph: 3886 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3887 case X86::BI__builtin_ia32_vcvtps2ph256: 3888 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3889 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3890 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3891 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3892 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3893 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3894 case X86::BI__builtin_ia32_rndscaleps_mask: 3895 case X86::BI__builtin_ia32_rndscalepd_mask: 3896 case X86::BI__builtin_ia32_reducepd128_mask: 3897 case X86::BI__builtin_ia32_reducepd256_mask: 3898 case X86::BI__builtin_ia32_reducepd512_mask: 3899 case X86::BI__builtin_ia32_reduceps128_mask: 3900 case X86::BI__builtin_ia32_reduceps256_mask: 3901 case X86::BI__builtin_ia32_reduceps512_mask: 3902 case X86::BI__builtin_ia32_prold512: 3903 case X86::BI__builtin_ia32_prolq512: 3904 case X86::BI__builtin_ia32_prold128: 3905 case X86::BI__builtin_ia32_prold256: 3906 case X86::BI__builtin_ia32_prolq128: 3907 case X86::BI__builtin_ia32_prolq256: 3908 case X86::BI__builtin_ia32_prord512: 3909 case X86::BI__builtin_ia32_prorq512: 3910 case X86::BI__builtin_ia32_prord128: 3911 case X86::BI__builtin_ia32_prord256: 3912 case X86::BI__builtin_ia32_prorq128: 3913 case X86::BI__builtin_ia32_prorq256: 3914 case X86::BI__builtin_ia32_fpclasspd128_mask: 3915 case X86::BI__builtin_ia32_fpclasspd256_mask: 3916 case X86::BI__builtin_ia32_fpclassps128_mask: 3917 case X86::BI__builtin_ia32_fpclassps256_mask: 3918 case X86::BI__builtin_ia32_fpclassps512_mask: 3919 case X86::BI__builtin_ia32_fpclasspd512_mask: 3920 case X86::BI__builtin_ia32_fpclasssd_mask: 3921 case X86::BI__builtin_ia32_fpclassss_mask: 3922 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3923 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3924 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3925 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3926 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3927 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3928 case X86::BI__builtin_ia32_kshiftliqi: 3929 case X86::BI__builtin_ia32_kshiftlihi: 3930 case X86::BI__builtin_ia32_kshiftlisi: 3931 case X86::BI__builtin_ia32_kshiftlidi: 3932 case X86::BI__builtin_ia32_kshiftriqi: 3933 case X86::BI__builtin_ia32_kshiftrihi: 3934 case X86::BI__builtin_ia32_kshiftrisi: 3935 case X86::BI__builtin_ia32_kshiftridi: 3936 i = 1; l = 0; u = 255; 3937 break; 3938 case X86::BI__builtin_ia32_vperm2f128_pd256: 3939 case X86::BI__builtin_ia32_vperm2f128_ps256: 3940 case X86::BI__builtin_ia32_vperm2f128_si256: 3941 case X86::BI__builtin_ia32_permti256: 3942 case X86::BI__builtin_ia32_pblendw128: 3943 case X86::BI__builtin_ia32_pblendw256: 3944 case X86::BI__builtin_ia32_blendps256: 3945 case X86::BI__builtin_ia32_pblendd256: 3946 case X86::BI__builtin_ia32_palignr128: 3947 case X86::BI__builtin_ia32_palignr256: 3948 case X86::BI__builtin_ia32_palignr512: 3949 case X86::BI__builtin_ia32_alignq512: 3950 case X86::BI__builtin_ia32_alignd512: 3951 case X86::BI__builtin_ia32_alignd128: 3952 case X86::BI__builtin_ia32_alignd256: 3953 case X86::BI__builtin_ia32_alignq128: 3954 case X86::BI__builtin_ia32_alignq256: 3955 case X86::BI__builtin_ia32_vcomisd: 3956 case X86::BI__builtin_ia32_vcomiss: 3957 case X86::BI__builtin_ia32_shuf_f32x4: 3958 case X86::BI__builtin_ia32_shuf_f64x2: 3959 case X86::BI__builtin_ia32_shuf_i32x4: 3960 case X86::BI__builtin_ia32_shuf_i64x2: 3961 case X86::BI__builtin_ia32_shufpd512: 3962 case X86::BI__builtin_ia32_shufps: 3963 case X86::BI__builtin_ia32_shufps256: 3964 case X86::BI__builtin_ia32_shufps512: 3965 case X86::BI__builtin_ia32_dbpsadbw128: 3966 case X86::BI__builtin_ia32_dbpsadbw256: 3967 case X86::BI__builtin_ia32_dbpsadbw512: 3968 case X86::BI__builtin_ia32_vpshldd128: 3969 case X86::BI__builtin_ia32_vpshldd256: 3970 case X86::BI__builtin_ia32_vpshldd512: 3971 case X86::BI__builtin_ia32_vpshldq128: 3972 case X86::BI__builtin_ia32_vpshldq256: 3973 case X86::BI__builtin_ia32_vpshldq512: 3974 case X86::BI__builtin_ia32_vpshldw128: 3975 case X86::BI__builtin_ia32_vpshldw256: 3976 case X86::BI__builtin_ia32_vpshldw512: 3977 case X86::BI__builtin_ia32_vpshrdd128: 3978 case X86::BI__builtin_ia32_vpshrdd256: 3979 case X86::BI__builtin_ia32_vpshrdd512: 3980 case X86::BI__builtin_ia32_vpshrdq128: 3981 case X86::BI__builtin_ia32_vpshrdq256: 3982 case X86::BI__builtin_ia32_vpshrdq512: 3983 case X86::BI__builtin_ia32_vpshrdw128: 3984 case X86::BI__builtin_ia32_vpshrdw256: 3985 case X86::BI__builtin_ia32_vpshrdw512: 3986 i = 2; l = 0; u = 255; 3987 break; 3988 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3989 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3990 case X86::BI__builtin_ia32_fixupimmps512_mask: 3991 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3992 case X86::BI__builtin_ia32_fixupimmsd_mask: 3993 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3994 case X86::BI__builtin_ia32_fixupimmss_mask: 3995 case X86::BI__builtin_ia32_fixupimmss_maskz: 3996 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3997 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3998 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3999 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 4000 case X86::BI__builtin_ia32_fixupimmps128_mask: 4001 case X86::BI__builtin_ia32_fixupimmps128_maskz: 4002 case X86::BI__builtin_ia32_fixupimmps256_mask: 4003 case X86::BI__builtin_ia32_fixupimmps256_maskz: 4004 case X86::BI__builtin_ia32_pternlogd512_mask: 4005 case X86::BI__builtin_ia32_pternlogd512_maskz: 4006 case X86::BI__builtin_ia32_pternlogq512_mask: 4007 case X86::BI__builtin_ia32_pternlogq512_maskz: 4008 case X86::BI__builtin_ia32_pternlogd128_mask: 4009 case X86::BI__builtin_ia32_pternlogd128_maskz: 4010 case X86::BI__builtin_ia32_pternlogd256_mask: 4011 case X86::BI__builtin_ia32_pternlogd256_maskz: 4012 case X86::BI__builtin_ia32_pternlogq128_mask: 4013 case X86::BI__builtin_ia32_pternlogq128_maskz: 4014 case X86::BI__builtin_ia32_pternlogq256_mask: 4015 case X86::BI__builtin_ia32_pternlogq256_maskz: 4016 i = 3; l = 0; u = 255; 4017 break; 4018 case X86::BI__builtin_ia32_gatherpfdpd: 4019 case X86::BI__builtin_ia32_gatherpfdps: 4020 case X86::BI__builtin_ia32_gatherpfqpd: 4021 case X86::BI__builtin_ia32_gatherpfqps: 4022 case X86::BI__builtin_ia32_scatterpfdpd: 4023 case X86::BI__builtin_ia32_scatterpfdps: 4024 case X86::BI__builtin_ia32_scatterpfqpd: 4025 case X86::BI__builtin_ia32_scatterpfqps: 4026 i = 4; l = 2; u = 3; 4027 break; 4028 case X86::BI__builtin_ia32_reducesd_mask: 4029 case X86::BI__builtin_ia32_reducess_mask: 4030 case X86::BI__builtin_ia32_rndscalesd_round_mask: 4031 case X86::BI__builtin_ia32_rndscaless_round_mask: 4032 i = 4; l = 0; u = 255; 4033 break; 4034 } 4035 4036 // Note that we don't force a hard error on the range check here, allowing 4037 // template-generated or macro-generated dead code to potentially have out-of- 4038 // range values. These need to code generate, but don't need to necessarily 4039 // make any sense. We use a warning that defaults to an error. 4040 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 4041 } 4042 4043 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 4044 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 4045 /// Returns true when the format fits the function and the FormatStringInfo has 4046 /// been populated. 4047 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 4048 FormatStringInfo *FSI) { 4049 FSI->HasVAListArg = Format->getFirstArg() == 0; 4050 FSI->FormatIdx = Format->getFormatIdx() - 1; 4051 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 4052 4053 // The way the format attribute works in GCC, the implicit this argument 4054 // of member functions is counted. However, it doesn't appear in our own 4055 // lists, so decrement format_idx in that case. 4056 if (IsCXXMember) { 4057 if(FSI->FormatIdx == 0) 4058 return false; 4059 --FSI->FormatIdx; 4060 if (FSI->FirstDataArg != 0) 4061 --FSI->FirstDataArg; 4062 } 4063 return true; 4064 } 4065 4066 /// Checks if a the given expression evaluates to null. 4067 /// 4068 /// Returns true if the value evaluates to null. 4069 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 4070 // If the expression has non-null type, it doesn't evaluate to null. 4071 if (auto nullability 4072 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 4073 if (*nullability == NullabilityKind::NonNull) 4074 return false; 4075 } 4076 4077 // As a special case, transparent unions initialized with zero are 4078 // considered null for the purposes of the nonnull attribute. 4079 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 4080 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 4081 if (const CompoundLiteralExpr *CLE = 4082 dyn_cast<CompoundLiteralExpr>(Expr)) 4083 if (const InitListExpr *ILE = 4084 dyn_cast<InitListExpr>(CLE->getInitializer())) 4085 Expr = ILE->getInit(0); 4086 } 4087 4088 bool Result; 4089 return (!Expr->isValueDependent() && 4090 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 4091 !Result); 4092 } 4093 4094 static void CheckNonNullArgument(Sema &S, 4095 const Expr *ArgExpr, 4096 SourceLocation CallSiteLoc) { 4097 if (CheckNonNullExpr(S, ArgExpr)) 4098 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 4099 S.PDiag(diag::warn_null_arg) 4100 << ArgExpr->getSourceRange()); 4101 } 4102 4103 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 4104 FormatStringInfo FSI; 4105 if ((GetFormatStringType(Format) == FST_NSString) && 4106 getFormatStringInfo(Format, false, &FSI)) { 4107 Idx = FSI.FormatIdx; 4108 return true; 4109 } 4110 return false; 4111 } 4112 4113 /// Diagnose use of %s directive in an NSString which is being passed 4114 /// as formatting string to formatting method. 4115 static void 4116 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 4117 const NamedDecl *FDecl, 4118 Expr **Args, 4119 unsigned NumArgs) { 4120 unsigned Idx = 0; 4121 bool Format = false; 4122 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4123 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4124 Idx = 2; 4125 Format = true; 4126 } 4127 else 4128 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4129 if (S.GetFormatNSStringIdx(I, Idx)) { 4130 Format = true; 4131 break; 4132 } 4133 } 4134 if (!Format || NumArgs <= Idx) 4135 return; 4136 const Expr *FormatExpr = Args[Idx]; 4137 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4138 FormatExpr = CSCE->getSubExpr(); 4139 const StringLiteral *FormatString; 4140 if (const ObjCStringLiteral *OSL = 4141 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4142 FormatString = OSL->getString(); 4143 else 4144 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4145 if (!FormatString) 4146 return; 4147 if (S.FormatStringHasSArg(FormatString)) { 4148 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4149 << "%s" << 1 << 1; 4150 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4151 << FDecl->getDeclName(); 4152 } 4153 } 4154 4155 /// Determine whether the given type has a non-null nullability annotation. 4156 static bool isNonNullType(ASTContext &ctx, QualType type) { 4157 if (auto nullability = type->getNullability(ctx)) 4158 return *nullability == NullabilityKind::NonNull; 4159 4160 return false; 4161 } 4162 4163 static void CheckNonNullArguments(Sema &S, 4164 const NamedDecl *FDecl, 4165 const FunctionProtoType *Proto, 4166 ArrayRef<const Expr *> Args, 4167 SourceLocation CallSiteLoc) { 4168 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4169 4170 // Already checked by by constant evaluator. 4171 if (S.isConstantEvaluated()) 4172 return; 4173 // Check the attributes attached to the method/function itself. 4174 llvm::SmallBitVector NonNullArgs; 4175 if (FDecl) { 4176 // Handle the nonnull attribute on the function/method declaration itself. 4177 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4178 if (!NonNull->args_size()) { 4179 // Easy case: all pointer arguments are nonnull. 4180 for (const auto *Arg : Args) 4181 if (S.isValidPointerAttrType(Arg->getType())) 4182 CheckNonNullArgument(S, Arg, CallSiteLoc); 4183 return; 4184 } 4185 4186 for (const ParamIdx &Idx : NonNull->args()) { 4187 unsigned IdxAST = Idx.getASTIndex(); 4188 if (IdxAST >= Args.size()) 4189 continue; 4190 if (NonNullArgs.empty()) 4191 NonNullArgs.resize(Args.size()); 4192 NonNullArgs.set(IdxAST); 4193 } 4194 } 4195 } 4196 4197 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4198 // Handle the nonnull attribute on the parameters of the 4199 // function/method. 4200 ArrayRef<ParmVarDecl*> parms; 4201 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4202 parms = FD->parameters(); 4203 else 4204 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4205 4206 unsigned ParamIndex = 0; 4207 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4208 I != E; ++I, ++ParamIndex) { 4209 const ParmVarDecl *PVD = *I; 4210 if (PVD->hasAttr<NonNullAttr>() || 4211 isNonNullType(S.Context, PVD->getType())) { 4212 if (NonNullArgs.empty()) 4213 NonNullArgs.resize(Args.size()); 4214 4215 NonNullArgs.set(ParamIndex); 4216 } 4217 } 4218 } else { 4219 // If we have a non-function, non-method declaration but no 4220 // function prototype, try to dig out the function prototype. 4221 if (!Proto) { 4222 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4223 QualType type = VD->getType().getNonReferenceType(); 4224 if (auto pointerType = type->getAs<PointerType>()) 4225 type = pointerType->getPointeeType(); 4226 else if (auto blockType = type->getAs<BlockPointerType>()) 4227 type = blockType->getPointeeType(); 4228 // FIXME: data member pointers? 4229 4230 // Dig out the function prototype, if there is one. 4231 Proto = type->getAs<FunctionProtoType>(); 4232 } 4233 } 4234 4235 // Fill in non-null argument information from the nullability 4236 // information on the parameter types (if we have them). 4237 if (Proto) { 4238 unsigned Index = 0; 4239 for (auto paramType : Proto->getParamTypes()) { 4240 if (isNonNullType(S.Context, paramType)) { 4241 if (NonNullArgs.empty()) 4242 NonNullArgs.resize(Args.size()); 4243 4244 NonNullArgs.set(Index); 4245 } 4246 4247 ++Index; 4248 } 4249 } 4250 } 4251 4252 // Check for non-null arguments. 4253 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4254 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4255 if (NonNullArgs[ArgIndex]) 4256 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4257 } 4258 } 4259 4260 /// Handles the checks for format strings, non-POD arguments to vararg 4261 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4262 /// attributes. 4263 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4264 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4265 bool IsMemberFunction, SourceLocation Loc, 4266 SourceRange Range, VariadicCallType CallType) { 4267 // FIXME: We should check as much as we can in the template definition. 4268 if (CurContext->isDependentContext()) 4269 return; 4270 4271 // Printf and scanf checking. 4272 llvm::SmallBitVector CheckedVarArgs; 4273 if (FDecl) { 4274 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4275 // Only create vector if there are format attributes. 4276 CheckedVarArgs.resize(Args.size()); 4277 4278 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4279 CheckedVarArgs); 4280 } 4281 } 4282 4283 // Refuse POD arguments that weren't caught by the format string 4284 // checks above. 4285 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4286 if (CallType != VariadicDoesNotApply && 4287 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4288 unsigned NumParams = Proto ? Proto->getNumParams() 4289 : FDecl && isa<FunctionDecl>(FDecl) 4290 ? cast<FunctionDecl>(FDecl)->getNumParams() 4291 : FDecl && isa<ObjCMethodDecl>(FDecl) 4292 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4293 : 0; 4294 4295 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4296 // Args[ArgIdx] can be null in malformed code. 4297 if (const Expr *Arg = Args[ArgIdx]) { 4298 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4299 checkVariadicArgument(Arg, CallType); 4300 } 4301 } 4302 } 4303 4304 if (FDecl || Proto) { 4305 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4306 4307 // Type safety checking. 4308 if (FDecl) { 4309 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4310 CheckArgumentWithTypeTag(I, Args, Loc); 4311 } 4312 } 4313 4314 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4315 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4316 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4317 if (!Arg->isValueDependent()) { 4318 Expr::EvalResult Align; 4319 if (Arg->EvaluateAsInt(Align, Context)) { 4320 const llvm::APSInt &I = Align.Val.getInt(); 4321 if (!I.isPowerOf2()) 4322 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4323 << Arg->getSourceRange(); 4324 4325 if (I > Sema::MaximumAlignment) 4326 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4327 << Arg->getSourceRange() << Sema::MaximumAlignment; 4328 } 4329 } 4330 } 4331 4332 if (FD) 4333 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4334 } 4335 4336 /// CheckConstructorCall - Check a constructor call for correctness and safety 4337 /// properties not enforced by the C type system. 4338 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4339 ArrayRef<const Expr *> Args, 4340 const FunctionProtoType *Proto, 4341 SourceLocation Loc) { 4342 VariadicCallType CallType = 4343 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4344 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4345 Loc, SourceRange(), CallType); 4346 } 4347 4348 /// CheckFunctionCall - Check a direct function call for various correctness 4349 /// and safety properties not strictly enforced by the C type system. 4350 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4351 const FunctionProtoType *Proto) { 4352 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4353 isa<CXXMethodDecl>(FDecl); 4354 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4355 IsMemberOperatorCall; 4356 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4357 TheCall->getCallee()); 4358 Expr** Args = TheCall->getArgs(); 4359 unsigned NumArgs = TheCall->getNumArgs(); 4360 4361 Expr *ImplicitThis = nullptr; 4362 if (IsMemberOperatorCall) { 4363 // If this is a call to a member operator, hide the first argument 4364 // from checkCall. 4365 // FIXME: Our choice of AST representation here is less than ideal. 4366 ImplicitThis = Args[0]; 4367 ++Args; 4368 --NumArgs; 4369 } else if (IsMemberFunction) 4370 ImplicitThis = 4371 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4372 4373 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4374 IsMemberFunction, TheCall->getRParenLoc(), 4375 TheCall->getCallee()->getSourceRange(), CallType); 4376 4377 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4378 // None of the checks below are needed for functions that don't have 4379 // simple names (e.g., C++ conversion functions). 4380 if (!FnInfo) 4381 return false; 4382 4383 CheckAbsoluteValueFunction(TheCall, FDecl); 4384 CheckMaxUnsignedZero(TheCall, FDecl); 4385 4386 if (getLangOpts().ObjC) 4387 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4388 4389 unsigned CMId = FDecl->getMemoryFunctionKind(); 4390 if (CMId == 0) 4391 return false; 4392 4393 // Handle memory setting and copying functions. 4394 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4395 CheckStrlcpycatArguments(TheCall, FnInfo); 4396 else if (CMId == Builtin::BIstrncat) 4397 CheckStrncatArguments(TheCall, FnInfo); 4398 else 4399 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4400 4401 return false; 4402 } 4403 4404 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4405 ArrayRef<const Expr *> Args) { 4406 VariadicCallType CallType = 4407 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4408 4409 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4410 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4411 CallType); 4412 4413 return false; 4414 } 4415 4416 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4417 const FunctionProtoType *Proto) { 4418 QualType Ty; 4419 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4420 Ty = V->getType().getNonReferenceType(); 4421 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4422 Ty = F->getType().getNonReferenceType(); 4423 else 4424 return false; 4425 4426 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4427 !Ty->isFunctionProtoType()) 4428 return false; 4429 4430 VariadicCallType CallType; 4431 if (!Proto || !Proto->isVariadic()) { 4432 CallType = VariadicDoesNotApply; 4433 } else if (Ty->isBlockPointerType()) { 4434 CallType = VariadicBlock; 4435 } else { // Ty->isFunctionPointerType() 4436 CallType = VariadicFunction; 4437 } 4438 4439 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4440 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4441 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4442 TheCall->getCallee()->getSourceRange(), CallType); 4443 4444 return false; 4445 } 4446 4447 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4448 /// such as function pointers returned from functions. 4449 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4450 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4451 TheCall->getCallee()); 4452 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4453 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4454 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4455 TheCall->getCallee()->getSourceRange(), CallType); 4456 4457 return false; 4458 } 4459 4460 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4461 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4462 return false; 4463 4464 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4465 switch (Op) { 4466 case AtomicExpr::AO__c11_atomic_init: 4467 case AtomicExpr::AO__opencl_atomic_init: 4468 llvm_unreachable("There is no ordering argument for an init"); 4469 4470 case AtomicExpr::AO__c11_atomic_load: 4471 case AtomicExpr::AO__opencl_atomic_load: 4472 case AtomicExpr::AO__atomic_load_n: 4473 case AtomicExpr::AO__atomic_load: 4474 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4475 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4476 4477 case AtomicExpr::AO__c11_atomic_store: 4478 case AtomicExpr::AO__opencl_atomic_store: 4479 case AtomicExpr::AO__atomic_store: 4480 case AtomicExpr::AO__atomic_store_n: 4481 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4482 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4483 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4484 4485 default: 4486 return true; 4487 } 4488 } 4489 4490 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4491 AtomicExpr::AtomicOp Op) { 4492 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4493 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4494 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4495 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4496 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4497 Op); 4498 } 4499 4500 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4501 SourceLocation RParenLoc, MultiExprArg Args, 4502 AtomicExpr::AtomicOp Op, 4503 AtomicArgumentOrder ArgOrder) { 4504 // All the non-OpenCL operations take one of the following forms. 4505 // The OpenCL operations take the __c11 forms with one extra argument for 4506 // synchronization scope. 4507 enum { 4508 // C __c11_atomic_init(A *, C) 4509 Init, 4510 4511 // C __c11_atomic_load(A *, int) 4512 Load, 4513 4514 // void __atomic_load(A *, CP, int) 4515 LoadCopy, 4516 4517 // void __atomic_store(A *, CP, int) 4518 Copy, 4519 4520 // C __c11_atomic_add(A *, M, int) 4521 Arithmetic, 4522 4523 // C __atomic_exchange_n(A *, CP, int) 4524 Xchg, 4525 4526 // void __atomic_exchange(A *, C *, CP, int) 4527 GNUXchg, 4528 4529 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4530 C11CmpXchg, 4531 4532 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4533 GNUCmpXchg 4534 } Form = Init; 4535 4536 const unsigned NumForm = GNUCmpXchg + 1; 4537 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4538 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4539 // where: 4540 // C is an appropriate type, 4541 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4542 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4543 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4544 // the int parameters are for orderings. 4545 4546 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4547 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4548 "need to update code for modified forms"); 4549 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4550 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4551 AtomicExpr::AO__atomic_load, 4552 "need to update code for modified C11 atomics"); 4553 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4554 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4555 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4556 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4557 IsOpenCL; 4558 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4559 Op == AtomicExpr::AO__atomic_store_n || 4560 Op == AtomicExpr::AO__atomic_exchange_n || 4561 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4562 bool IsAddSub = false; 4563 4564 switch (Op) { 4565 case AtomicExpr::AO__c11_atomic_init: 4566 case AtomicExpr::AO__opencl_atomic_init: 4567 Form = Init; 4568 break; 4569 4570 case AtomicExpr::AO__c11_atomic_load: 4571 case AtomicExpr::AO__opencl_atomic_load: 4572 case AtomicExpr::AO__atomic_load_n: 4573 Form = Load; 4574 break; 4575 4576 case AtomicExpr::AO__atomic_load: 4577 Form = LoadCopy; 4578 break; 4579 4580 case AtomicExpr::AO__c11_atomic_store: 4581 case AtomicExpr::AO__opencl_atomic_store: 4582 case AtomicExpr::AO__atomic_store: 4583 case AtomicExpr::AO__atomic_store_n: 4584 Form = Copy; 4585 break; 4586 4587 case AtomicExpr::AO__c11_atomic_fetch_add: 4588 case AtomicExpr::AO__c11_atomic_fetch_sub: 4589 case AtomicExpr::AO__opencl_atomic_fetch_add: 4590 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4591 case AtomicExpr::AO__atomic_fetch_add: 4592 case AtomicExpr::AO__atomic_fetch_sub: 4593 case AtomicExpr::AO__atomic_add_fetch: 4594 case AtomicExpr::AO__atomic_sub_fetch: 4595 IsAddSub = true; 4596 LLVM_FALLTHROUGH; 4597 case AtomicExpr::AO__c11_atomic_fetch_and: 4598 case AtomicExpr::AO__c11_atomic_fetch_or: 4599 case AtomicExpr::AO__c11_atomic_fetch_xor: 4600 case AtomicExpr::AO__opencl_atomic_fetch_and: 4601 case AtomicExpr::AO__opencl_atomic_fetch_or: 4602 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4603 case AtomicExpr::AO__atomic_fetch_and: 4604 case AtomicExpr::AO__atomic_fetch_or: 4605 case AtomicExpr::AO__atomic_fetch_xor: 4606 case AtomicExpr::AO__atomic_fetch_nand: 4607 case AtomicExpr::AO__atomic_and_fetch: 4608 case AtomicExpr::AO__atomic_or_fetch: 4609 case AtomicExpr::AO__atomic_xor_fetch: 4610 case AtomicExpr::AO__atomic_nand_fetch: 4611 case AtomicExpr::AO__c11_atomic_fetch_min: 4612 case AtomicExpr::AO__c11_atomic_fetch_max: 4613 case AtomicExpr::AO__opencl_atomic_fetch_min: 4614 case AtomicExpr::AO__opencl_atomic_fetch_max: 4615 case AtomicExpr::AO__atomic_min_fetch: 4616 case AtomicExpr::AO__atomic_max_fetch: 4617 case AtomicExpr::AO__atomic_fetch_min: 4618 case AtomicExpr::AO__atomic_fetch_max: 4619 Form = Arithmetic; 4620 break; 4621 4622 case AtomicExpr::AO__c11_atomic_exchange: 4623 case AtomicExpr::AO__opencl_atomic_exchange: 4624 case AtomicExpr::AO__atomic_exchange_n: 4625 Form = Xchg; 4626 break; 4627 4628 case AtomicExpr::AO__atomic_exchange: 4629 Form = GNUXchg; 4630 break; 4631 4632 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4633 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4634 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4635 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4636 Form = C11CmpXchg; 4637 break; 4638 4639 case AtomicExpr::AO__atomic_compare_exchange: 4640 case AtomicExpr::AO__atomic_compare_exchange_n: 4641 Form = GNUCmpXchg; 4642 break; 4643 } 4644 4645 unsigned AdjustedNumArgs = NumArgs[Form]; 4646 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4647 ++AdjustedNumArgs; 4648 // Check we have the right number of arguments. 4649 if (Args.size() < AdjustedNumArgs) { 4650 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4651 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4652 << ExprRange; 4653 return ExprError(); 4654 } else if (Args.size() > AdjustedNumArgs) { 4655 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4656 diag::err_typecheck_call_too_many_args) 4657 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4658 << ExprRange; 4659 return ExprError(); 4660 } 4661 4662 // Inspect the first argument of the atomic operation. 4663 Expr *Ptr = Args[0]; 4664 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4665 if (ConvertedPtr.isInvalid()) 4666 return ExprError(); 4667 4668 Ptr = ConvertedPtr.get(); 4669 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4670 if (!pointerType) { 4671 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4672 << Ptr->getType() << Ptr->getSourceRange(); 4673 return ExprError(); 4674 } 4675 4676 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4677 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4678 QualType ValType = AtomTy; // 'C' 4679 if (IsC11) { 4680 if (!AtomTy->isAtomicType()) { 4681 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4682 << Ptr->getType() << Ptr->getSourceRange(); 4683 return ExprError(); 4684 } 4685 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4686 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4687 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4688 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4689 << Ptr->getSourceRange(); 4690 return ExprError(); 4691 } 4692 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4693 } else if (Form != Load && Form != LoadCopy) { 4694 if (ValType.isConstQualified()) { 4695 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4696 << Ptr->getType() << Ptr->getSourceRange(); 4697 return ExprError(); 4698 } 4699 } 4700 4701 // For an arithmetic operation, the implied arithmetic must be well-formed. 4702 if (Form == Arithmetic) { 4703 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4704 if (IsAddSub && !ValType->isIntegerType() 4705 && !ValType->isPointerType()) { 4706 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4707 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4708 return ExprError(); 4709 } 4710 if (!IsAddSub && !ValType->isIntegerType()) { 4711 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4712 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4713 return ExprError(); 4714 } 4715 if (IsC11 && ValType->isPointerType() && 4716 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4717 diag::err_incomplete_type)) { 4718 return ExprError(); 4719 } 4720 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4721 // For __atomic_*_n operations, the value type must be a scalar integral or 4722 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4723 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4724 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4725 return ExprError(); 4726 } 4727 4728 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4729 !AtomTy->isScalarType()) { 4730 // For GNU atomics, require a trivially-copyable type. This is not part of 4731 // the GNU atomics specification, but we enforce it for sanity. 4732 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4733 << Ptr->getType() << Ptr->getSourceRange(); 4734 return ExprError(); 4735 } 4736 4737 switch (ValType.getObjCLifetime()) { 4738 case Qualifiers::OCL_None: 4739 case Qualifiers::OCL_ExplicitNone: 4740 // okay 4741 break; 4742 4743 case Qualifiers::OCL_Weak: 4744 case Qualifiers::OCL_Strong: 4745 case Qualifiers::OCL_Autoreleasing: 4746 // FIXME: Can this happen? By this point, ValType should be known 4747 // to be trivially copyable. 4748 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4749 << ValType << Ptr->getSourceRange(); 4750 return ExprError(); 4751 } 4752 4753 // All atomic operations have an overload which takes a pointer to a volatile 4754 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4755 // into the result or the other operands. Similarly atomic_load takes a 4756 // pointer to a const 'A'. 4757 ValType.removeLocalVolatile(); 4758 ValType.removeLocalConst(); 4759 QualType ResultType = ValType; 4760 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4761 Form == Init) 4762 ResultType = Context.VoidTy; 4763 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4764 ResultType = Context.BoolTy; 4765 4766 // The type of a parameter passed 'by value'. In the GNU atomics, such 4767 // arguments are actually passed as pointers. 4768 QualType ByValType = ValType; // 'CP' 4769 bool IsPassedByAddress = false; 4770 if (!IsC11 && !IsN) { 4771 ByValType = Ptr->getType(); 4772 IsPassedByAddress = true; 4773 } 4774 4775 SmallVector<Expr *, 5> APIOrderedArgs; 4776 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4777 APIOrderedArgs.push_back(Args[0]); 4778 switch (Form) { 4779 case Init: 4780 case Load: 4781 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4782 break; 4783 case LoadCopy: 4784 case Copy: 4785 case Arithmetic: 4786 case Xchg: 4787 APIOrderedArgs.push_back(Args[2]); // Val1 4788 APIOrderedArgs.push_back(Args[1]); // Order 4789 break; 4790 case GNUXchg: 4791 APIOrderedArgs.push_back(Args[2]); // Val1 4792 APIOrderedArgs.push_back(Args[3]); // Val2 4793 APIOrderedArgs.push_back(Args[1]); // Order 4794 break; 4795 case C11CmpXchg: 4796 APIOrderedArgs.push_back(Args[2]); // Val1 4797 APIOrderedArgs.push_back(Args[4]); // Val2 4798 APIOrderedArgs.push_back(Args[1]); // Order 4799 APIOrderedArgs.push_back(Args[3]); // OrderFail 4800 break; 4801 case GNUCmpXchg: 4802 APIOrderedArgs.push_back(Args[2]); // Val1 4803 APIOrderedArgs.push_back(Args[4]); // Val2 4804 APIOrderedArgs.push_back(Args[5]); // Weak 4805 APIOrderedArgs.push_back(Args[1]); // Order 4806 APIOrderedArgs.push_back(Args[3]); // OrderFail 4807 break; 4808 } 4809 } else 4810 APIOrderedArgs.append(Args.begin(), Args.end()); 4811 4812 // The first argument's non-CV pointer type is used to deduce the type of 4813 // subsequent arguments, except for: 4814 // - weak flag (always converted to bool) 4815 // - memory order (always converted to int) 4816 // - scope (always converted to int) 4817 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4818 QualType Ty; 4819 if (i < NumVals[Form] + 1) { 4820 switch (i) { 4821 case 0: 4822 // The first argument is always a pointer. It has a fixed type. 4823 // It is always dereferenced, a nullptr is undefined. 4824 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4825 // Nothing else to do: we already know all we want about this pointer. 4826 continue; 4827 case 1: 4828 // The second argument is the non-atomic operand. For arithmetic, this 4829 // is always passed by value, and for a compare_exchange it is always 4830 // passed by address. For the rest, GNU uses by-address and C11 uses 4831 // by-value. 4832 assert(Form != Load); 4833 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4834 Ty = ValType; 4835 else if (Form == Copy || Form == Xchg) { 4836 if (IsPassedByAddress) { 4837 // The value pointer is always dereferenced, a nullptr is undefined. 4838 CheckNonNullArgument(*this, APIOrderedArgs[i], 4839 ExprRange.getBegin()); 4840 } 4841 Ty = ByValType; 4842 } else if (Form == Arithmetic) 4843 Ty = Context.getPointerDiffType(); 4844 else { 4845 Expr *ValArg = APIOrderedArgs[i]; 4846 // The value pointer is always dereferenced, a nullptr is undefined. 4847 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4848 LangAS AS = LangAS::Default; 4849 // Keep address space of non-atomic pointer type. 4850 if (const PointerType *PtrTy = 4851 ValArg->getType()->getAs<PointerType>()) { 4852 AS = PtrTy->getPointeeType().getAddressSpace(); 4853 } 4854 Ty = Context.getPointerType( 4855 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4856 } 4857 break; 4858 case 2: 4859 // The third argument to compare_exchange / GNU exchange is the desired 4860 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4861 if (IsPassedByAddress) 4862 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4863 Ty = ByValType; 4864 break; 4865 case 3: 4866 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4867 Ty = Context.BoolTy; 4868 break; 4869 } 4870 } else { 4871 // The order(s) and scope are always converted to int. 4872 Ty = Context.IntTy; 4873 } 4874 4875 InitializedEntity Entity = 4876 InitializedEntity::InitializeParameter(Context, Ty, false); 4877 ExprResult Arg = APIOrderedArgs[i]; 4878 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4879 if (Arg.isInvalid()) 4880 return true; 4881 APIOrderedArgs[i] = Arg.get(); 4882 } 4883 4884 // Permute the arguments into a 'consistent' order. 4885 SmallVector<Expr*, 5> SubExprs; 4886 SubExprs.push_back(Ptr); 4887 switch (Form) { 4888 case Init: 4889 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4890 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4891 break; 4892 case Load: 4893 SubExprs.push_back(APIOrderedArgs[1]); // Order 4894 break; 4895 case LoadCopy: 4896 case Copy: 4897 case Arithmetic: 4898 case Xchg: 4899 SubExprs.push_back(APIOrderedArgs[2]); // Order 4900 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4901 break; 4902 case GNUXchg: 4903 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4904 SubExprs.push_back(APIOrderedArgs[3]); // Order 4905 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4906 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4907 break; 4908 case C11CmpXchg: 4909 SubExprs.push_back(APIOrderedArgs[3]); // Order 4910 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4911 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 4912 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4913 break; 4914 case GNUCmpXchg: 4915 SubExprs.push_back(APIOrderedArgs[4]); // Order 4916 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4917 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 4918 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4919 SubExprs.push_back(APIOrderedArgs[3]); // Weak 4920 break; 4921 } 4922 4923 if (SubExprs.size() >= 2 && Form != Init) { 4924 if (Optional<llvm::APSInt> Result = 4925 SubExprs[1]->getIntegerConstantExpr(Context)) 4926 if (!isValidOrderingForOp(Result->getSExtValue(), Op)) 4927 Diag(SubExprs[1]->getBeginLoc(), 4928 diag::warn_atomic_op_has_invalid_memory_order) 4929 << SubExprs[1]->getSourceRange(); 4930 } 4931 4932 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4933 auto *Scope = Args[Args.size() - 1]; 4934 if (Optional<llvm::APSInt> Result = 4935 Scope->getIntegerConstantExpr(Context)) { 4936 if (!ScopeModel->isValid(Result->getZExtValue())) 4937 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4938 << Scope->getSourceRange(); 4939 } 4940 SubExprs.push_back(Scope); 4941 } 4942 4943 AtomicExpr *AE = new (Context) 4944 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 4945 4946 if ((Op == AtomicExpr::AO__c11_atomic_load || 4947 Op == AtomicExpr::AO__c11_atomic_store || 4948 Op == AtomicExpr::AO__opencl_atomic_load || 4949 Op == AtomicExpr::AO__opencl_atomic_store ) && 4950 Context.AtomicUsesUnsupportedLibcall(AE)) 4951 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4952 << ((Op == AtomicExpr::AO__c11_atomic_load || 4953 Op == AtomicExpr::AO__opencl_atomic_load) 4954 ? 0 4955 : 1); 4956 4957 return AE; 4958 } 4959 4960 /// checkBuiltinArgument - Given a call to a builtin function, perform 4961 /// normal type-checking on the given argument, updating the call in 4962 /// place. This is useful when a builtin function requires custom 4963 /// type-checking for some of its arguments but not necessarily all of 4964 /// them. 4965 /// 4966 /// Returns true on error. 4967 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4968 FunctionDecl *Fn = E->getDirectCallee(); 4969 assert(Fn && "builtin call without direct callee!"); 4970 4971 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4972 InitializedEntity Entity = 4973 InitializedEntity::InitializeParameter(S.Context, Param); 4974 4975 ExprResult Arg = E->getArg(0); 4976 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4977 if (Arg.isInvalid()) 4978 return true; 4979 4980 E->setArg(ArgIndex, Arg.get()); 4981 return false; 4982 } 4983 4984 /// We have a call to a function like __sync_fetch_and_add, which is an 4985 /// overloaded function based on the pointer type of its first argument. 4986 /// The main BuildCallExpr routines have already promoted the types of 4987 /// arguments because all of these calls are prototyped as void(...). 4988 /// 4989 /// This function goes through and does final semantic checking for these 4990 /// builtins, as well as generating any warnings. 4991 ExprResult 4992 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4993 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4994 Expr *Callee = TheCall->getCallee(); 4995 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4996 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4997 4998 // Ensure that we have at least one argument to do type inference from. 4999 if (TheCall->getNumArgs() < 1) { 5000 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5001 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 5002 return ExprError(); 5003 } 5004 5005 // Inspect the first argument of the atomic builtin. This should always be 5006 // a pointer type, whose element is an integral scalar or pointer type. 5007 // Because it is a pointer type, we don't have to worry about any implicit 5008 // casts here. 5009 // FIXME: We don't allow floating point scalars as input. 5010 Expr *FirstArg = TheCall->getArg(0); 5011 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 5012 if (FirstArgResult.isInvalid()) 5013 return ExprError(); 5014 FirstArg = FirstArgResult.get(); 5015 TheCall->setArg(0, FirstArg); 5016 5017 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 5018 if (!pointerType) { 5019 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 5020 << FirstArg->getType() << FirstArg->getSourceRange(); 5021 return ExprError(); 5022 } 5023 5024 QualType ValType = pointerType->getPointeeType(); 5025 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5026 !ValType->isBlockPointerType()) { 5027 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 5028 << FirstArg->getType() << FirstArg->getSourceRange(); 5029 return ExprError(); 5030 } 5031 5032 if (ValType.isConstQualified()) { 5033 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 5034 << FirstArg->getType() << FirstArg->getSourceRange(); 5035 return ExprError(); 5036 } 5037 5038 switch (ValType.getObjCLifetime()) { 5039 case Qualifiers::OCL_None: 5040 case Qualifiers::OCL_ExplicitNone: 5041 // okay 5042 break; 5043 5044 case Qualifiers::OCL_Weak: 5045 case Qualifiers::OCL_Strong: 5046 case Qualifiers::OCL_Autoreleasing: 5047 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 5048 << ValType << FirstArg->getSourceRange(); 5049 return ExprError(); 5050 } 5051 5052 // Strip any qualifiers off ValType. 5053 ValType = ValType.getUnqualifiedType(); 5054 5055 // The majority of builtins return a value, but a few have special return 5056 // types, so allow them to override appropriately below. 5057 QualType ResultType = ValType; 5058 5059 // We need to figure out which concrete builtin this maps onto. For example, 5060 // __sync_fetch_and_add with a 2 byte object turns into 5061 // __sync_fetch_and_add_2. 5062 #define BUILTIN_ROW(x) \ 5063 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 5064 Builtin::BI##x##_8, Builtin::BI##x##_16 } 5065 5066 static const unsigned BuiltinIndices[][5] = { 5067 BUILTIN_ROW(__sync_fetch_and_add), 5068 BUILTIN_ROW(__sync_fetch_and_sub), 5069 BUILTIN_ROW(__sync_fetch_and_or), 5070 BUILTIN_ROW(__sync_fetch_and_and), 5071 BUILTIN_ROW(__sync_fetch_and_xor), 5072 BUILTIN_ROW(__sync_fetch_and_nand), 5073 5074 BUILTIN_ROW(__sync_add_and_fetch), 5075 BUILTIN_ROW(__sync_sub_and_fetch), 5076 BUILTIN_ROW(__sync_and_and_fetch), 5077 BUILTIN_ROW(__sync_or_and_fetch), 5078 BUILTIN_ROW(__sync_xor_and_fetch), 5079 BUILTIN_ROW(__sync_nand_and_fetch), 5080 5081 BUILTIN_ROW(__sync_val_compare_and_swap), 5082 BUILTIN_ROW(__sync_bool_compare_and_swap), 5083 BUILTIN_ROW(__sync_lock_test_and_set), 5084 BUILTIN_ROW(__sync_lock_release), 5085 BUILTIN_ROW(__sync_swap) 5086 }; 5087 #undef BUILTIN_ROW 5088 5089 // Determine the index of the size. 5090 unsigned SizeIndex; 5091 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 5092 case 1: SizeIndex = 0; break; 5093 case 2: SizeIndex = 1; break; 5094 case 4: SizeIndex = 2; break; 5095 case 8: SizeIndex = 3; break; 5096 case 16: SizeIndex = 4; break; 5097 default: 5098 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 5099 << FirstArg->getType() << FirstArg->getSourceRange(); 5100 return ExprError(); 5101 } 5102 5103 // Each of these builtins has one pointer argument, followed by some number of 5104 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 5105 // that we ignore. Find out which row of BuiltinIndices to read from as well 5106 // as the number of fixed args. 5107 unsigned BuiltinID = FDecl->getBuiltinID(); 5108 unsigned BuiltinIndex, NumFixed = 1; 5109 bool WarnAboutSemanticsChange = false; 5110 switch (BuiltinID) { 5111 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 5112 case Builtin::BI__sync_fetch_and_add: 5113 case Builtin::BI__sync_fetch_and_add_1: 5114 case Builtin::BI__sync_fetch_and_add_2: 5115 case Builtin::BI__sync_fetch_and_add_4: 5116 case Builtin::BI__sync_fetch_and_add_8: 5117 case Builtin::BI__sync_fetch_and_add_16: 5118 BuiltinIndex = 0; 5119 break; 5120 5121 case Builtin::BI__sync_fetch_and_sub: 5122 case Builtin::BI__sync_fetch_and_sub_1: 5123 case Builtin::BI__sync_fetch_and_sub_2: 5124 case Builtin::BI__sync_fetch_and_sub_4: 5125 case Builtin::BI__sync_fetch_and_sub_8: 5126 case Builtin::BI__sync_fetch_and_sub_16: 5127 BuiltinIndex = 1; 5128 break; 5129 5130 case Builtin::BI__sync_fetch_and_or: 5131 case Builtin::BI__sync_fetch_and_or_1: 5132 case Builtin::BI__sync_fetch_and_or_2: 5133 case Builtin::BI__sync_fetch_and_or_4: 5134 case Builtin::BI__sync_fetch_and_or_8: 5135 case Builtin::BI__sync_fetch_and_or_16: 5136 BuiltinIndex = 2; 5137 break; 5138 5139 case Builtin::BI__sync_fetch_and_and: 5140 case Builtin::BI__sync_fetch_and_and_1: 5141 case Builtin::BI__sync_fetch_and_and_2: 5142 case Builtin::BI__sync_fetch_and_and_4: 5143 case Builtin::BI__sync_fetch_and_and_8: 5144 case Builtin::BI__sync_fetch_and_and_16: 5145 BuiltinIndex = 3; 5146 break; 5147 5148 case Builtin::BI__sync_fetch_and_xor: 5149 case Builtin::BI__sync_fetch_and_xor_1: 5150 case Builtin::BI__sync_fetch_and_xor_2: 5151 case Builtin::BI__sync_fetch_and_xor_4: 5152 case Builtin::BI__sync_fetch_and_xor_8: 5153 case Builtin::BI__sync_fetch_and_xor_16: 5154 BuiltinIndex = 4; 5155 break; 5156 5157 case Builtin::BI__sync_fetch_and_nand: 5158 case Builtin::BI__sync_fetch_and_nand_1: 5159 case Builtin::BI__sync_fetch_and_nand_2: 5160 case Builtin::BI__sync_fetch_and_nand_4: 5161 case Builtin::BI__sync_fetch_and_nand_8: 5162 case Builtin::BI__sync_fetch_and_nand_16: 5163 BuiltinIndex = 5; 5164 WarnAboutSemanticsChange = true; 5165 break; 5166 5167 case Builtin::BI__sync_add_and_fetch: 5168 case Builtin::BI__sync_add_and_fetch_1: 5169 case Builtin::BI__sync_add_and_fetch_2: 5170 case Builtin::BI__sync_add_and_fetch_4: 5171 case Builtin::BI__sync_add_and_fetch_8: 5172 case Builtin::BI__sync_add_and_fetch_16: 5173 BuiltinIndex = 6; 5174 break; 5175 5176 case Builtin::BI__sync_sub_and_fetch: 5177 case Builtin::BI__sync_sub_and_fetch_1: 5178 case Builtin::BI__sync_sub_and_fetch_2: 5179 case Builtin::BI__sync_sub_and_fetch_4: 5180 case Builtin::BI__sync_sub_and_fetch_8: 5181 case Builtin::BI__sync_sub_and_fetch_16: 5182 BuiltinIndex = 7; 5183 break; 5184 5185 case Builtin::BI__sync_and_and_fetch: 5186 case Builtin::BI__sync_and_and_fetch_1: 5187 case Builtin::BI__sync_and_and_fetch_2: 5188 case Builtin::BI__sync_and_and_fetch_4: 5189 case Builtin::BI__sync_and_and_fetch_8: 5190 case Builtin::BI__sync_and_and_fetch_16: 5191 BuiltinIndex = 8; 5192 break; 5193 5194 case Builtin::BI__sync_or_and_fetch: 5195 case Builtin::BI__sync_or_and_fetch_1: 5196 case Builtin::BI__sync_or_and_fetch_2: 5197 case Builtin::BI__sync_or_and_fetch_4: 5198 case Builtin::BI__sync_or_and_fetch_8: 5199 case Builtin::BI__sync_or_and_fetch_16: 5200 BuiltinIndex = 9; 5201 break; 5202 5203 case Builtin::BI__sync_xor_and_fetch: 5204 case Builtin::BI__sync_xor_and_fetch_1: 5205 case Builtin::BI__sync_xor_and_fetch_2: 5206 case Builtin::BI__sync_xor_and_fetch_4: 5207 case Builtin::BI__sync_xor_and_fetch_8: 5208 case Builtin::BI__sync_xor_and_fetch_16: 5209 BuiltinIndex = 10; 5210 break; 5211 5212 case Builtin::BI__sync_nand_and_fetch: 5213 case Builtin::BI__sync_nand_and_fetch_1: 5214 case Builtin::BI__sync_nand_and_fetch_2: 5215 case Builtin::BI__sync_nand_and_fetch_4: 5216 case Builtin::BI__sync_nand_and_fetch_8: 5217 case Builtin::BI__sync_nand_and_fetch_16: 5218 BuiltinIndex = 11; 5219 WarnAboutSemanticsChange = true; 5220 break; 5221 5222 case Builtin::BI__sync_val_compare_and_swap: 5223 case Builtin::BI__sync_val_compare_and_swap_1: 5224 case Builtin::BI__sync_val_compare_and_swap_2: 5225 case Builtin::BI__sync_val_compare_and_swap_4: 5226 case Builtin::BI__sync_val_compare_and_swap_8: 5227 case Builtin::BI__sync_val_compare_and_swap_16: 5228 BuiltinIndex = 12; 5229 NumFixed = 2; 5230 break; 5231 5232 case Builtin::BI__sync_bool_compare_and_swap: 5233 case Builtin::BI__sync_bool_compare_and_swap_1: 5234 case Builtin::BI__sync_bool_compare_and_swap_2: 5235 case Builtin::BI__sync_bool_compare_and_swap_4: 5236 case Builtin::BI__sync_bool_compare_and_swap_8: 5237 case Builtin::BI__sync_bool_compare_and_swap_16: 5238 BuiltinIndex = 13; 5239 NumFixed = 2; 5240 ResultType = Context.BoolTy; 5241 break; 5242 5243 case Builtin::BI__sync_lock_test_and_set: 5244 case Builtin::BI__sync_lock_test_and_set_1: 5245 case Builtin::BI__sync_lock_test_and_set_2: 5246 case Builtin::BI__sync_lock_test_and_set_4: 5247 case Builtin::BI__sync_lock_test_and_set_8: 5248 case Builtin::BI__sync_lock_test_and_set_16: 5249 BuiltinIndex = 14; 5250 break; 5251 5252 case Builtin::BI__sync_lock_release: 5253 case Builtin::BI__sync_lock_release_1: 5254 case Builtin::BI__sync_lock_release_2: 5255 case Builtin::BI__sync_lock_release_4: 5256 case Builtin::BI__sync_lock_release_8: 5257 case Builtin::BI__sync_lock_release_16: 5258 BuiltinIndex = 15; 5259 NumFixed = 0; 5260 ResultType = Context.VoidTy; 5261 break; 5262 5263 case Builtin::BI__sync_swap: 5264 case Builtin::BI__sync_swap_1: 5265 case Builtin::BI__sync_swap_2: 5266 case Builtin::BI__sync_swap_4: 5267 case Builtin::BI__sync_swap_8: 5268 case Builtin::BI__sync_swap_16: 5269 BuiltinIndex = 16; 5270 break; 5271 } 5272 5273 // Now that we know how many fixed arguments we expect, first check that we 5274 // have at least that many. 5275 if (TheCall->getNumArgs() < 1+NumFixed) { 5276 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5277 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5278 << Callee->getSourceRange(); 5279 return ExprError(); 5280 } 5281 5282 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5283 << Callee->getSourceRange(); 5284 5285 if (WarnAboutSemanticsChange) { 5286 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5287 << Callee->getSourceRange(); 5288 } 5289 5290 // Get the decl for the concrete builtin from this, we can tell what the 5291 // concrete integer type we should convert to is. 5292 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5293 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5294 FunctionDecl *NewBuiltinDecl; 5295 if (NewBuiltinID == BuiltinID) 5296 NewBuiltinDecl = FDecl; 5297 else { 5298 // Perform builtin lookup to avoid redeclaring it. 5299 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5300 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5301 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5302 assert(Res.getFoundDecl()); 5303 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5304 if (!NewBuiltinDecl) 5305 return ExprError(); 5306 } 5307 5308 // The first argument --- the pointer --- has a fixed type; we 5309 // deduce the types of the rest of the arguments accordingly. Walk 5310 // the remaining arguments, converting them to the deduced value type. 5311 for (unsigned i = 0; i != NumFixed; ++i) { 5312 ExprResult Arg = TheCall->getArg(i+1); 5313 5314 // GCC does an implicit conversion to the pointer or integer ValType. This 5315 // can fail in some cases (1i -> int**), check for this error case now. 5316 // Initialize the argument. 5317 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5318 ValType, /*consume*/ false); 5319 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5320 if (Arg.isInvalid()) 5321 return ExprError(); 5322 5323 // Okay, we have something that *can* be converted to the right type. Check 5324 // to see if there is a potentially weird extension going on here. This can 5325 // happen when you do an atomic operation on something like an char* and 5326 // pass in 42. The 42 gets converted to char. This is even more strange 5327 // for things like 45.123 -> char, etc. 5328 // FIXME: Do this check. 5329 TheCall->setArg(i+1, Arg.get()); 5330 } 5331 5332 // Create a new DeclRefExpr to refer to the new decl. 5333 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5334 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5335 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5336 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5337 5338 // Set the callee in the CallExpr. 5339 // FIXME: This loses syntactic information. 5340 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5341 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5342 CK_BuiltinFnToFnPtr); 5343 TheCall->setCallee(PromotedCall.get()); 5344 5345 // Change the result type of the call to match the original value type. This 5346 // is arbitrary, but the codegen for these builtins ins design to handle it 5347 // gracefully. 5348 TheCall->setType(ResultType); 5349 5350 // Prohibit use of _ExtInt with atomic builtins. 5351 // The arguments would have already been converted to the first argument's 5352 // type, so only need to check the first argument. 5353 const auto *ExtIntValType = ValType->getAs<ExtIntType>(); 5354 if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) { 5355 Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size); 5356 return ExprError(); 5357 } 5358 5359 return TheCallResult; 5360 } 5361 5362 /// SemaBuiltinNontemporalOverloaded - We have a call to 5363 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5364 /// overloaded function based on the pointer type of its last argument. 5365 /// 5366 /// This function goes through and does final semantic checking for these 5367 /// builtins. 5368 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5369 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5370 DeclRefExpr *DRE = 5371 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5372 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5373 unsigned BuiltinID = FDecl->getBuiltinID(); 5374 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5375 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5376 "Unexpected nontemporal load/store builtin!"); 5377 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5378 unsigned numArgs = isStore ? 2 : 1; 5379 5380 // Ensure that we have the proper number of arguments. 5381 if (checkArgCount(*this, TheCall, numArgs)) 5382 return ExprError(); 5383 5384 // Inspect the last argument of the nontemporal builtin. This should always 5385 // be a pointer type, from which we imply the type of the memory access. 5386 // Because it is a pointer type, we don't have to worry about any implicit 5387 // casts here. 5388 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5389 ExprResult PointerArgResult = 5390 DefaultFunctionArrayLvalueConversion(PointerArg); 5391 5392 if (PointerArgResult.isInvalid()) 5393 return ExprError(); 5394 PointerArg = PointerArgResult.get(); 5395 TheCall->setArg(numArgs - 1, PointerArg); 5396 5397 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5398 if (!pointerType) { 5399 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5400 << PointerArg->getType() << PointerArg->getSourceRange(); 5401 return ExprError(); 5402 } 5403 5404 QualType ValType = pointerType->getPointeeType(); 5405 5406 // Strip any qualifiers off ValType. 5407 ValType = ValType.getUnqualifiedType(); 5408 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5409 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5410 !ValType->isVectorType()) { 5411 Diag(DRE->getBeginLoc(), 5412 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5413 << PointerArg->getType() << PointerArg->getSourceRange(); 5414 return ExprError(); 5415 } 5416 5417 if (!isStore) { 5418 TheCall->setType(ValType); 5419 return TheCallResult; 5420 } 5421 5422 ExprResult ValArg = TheCall->getArg(0); 5423 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5424 Context, ValType, /*consume*/ false); 5425 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5426 if (ValArg.isInvalid()) 5427 return ExprError(); 5428 5429 TheCall->setArg(0, ValArg.get()); 5430 TheCall->setType(Context.VoidTy); 5431 return TheCallResult; 5432 } 5433 5434 /// CheckObjCString - Checks that the argument to the builtin 5435 /// CFString constructor is correct 5436 /// Note: It might also make sense to do the UTF-16 conversion here (would 5437 /// simplify the backend). 5438 bool Sema::CheckObjCString(Expr *Arg) { 5439 Arg = Arg->IgnoreParenCasts(); 5440 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5441 5442 if (!Literal || !Literal->isAscii()) { 5443 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5444 << Arg->getSourceRange(); 5445 return true; 5446 } 5447 5448 if (Literal->containsNonAsciiOrNull()) { 5449 StringRef String = Literal->getString(); 5450 unsigned NumBytes = String.size(); 5451 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5452 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5453 llvm::UTF16 *ToPtr = &ToBuf[0]; 5454 5455 llvm::ConversionResult Result = 5456 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5457 ToPtr + NumBytes, llvm::strictConversion); 5458 // Check for conversion failure. 5459 if (Result != llvm::conversionOK) 5460 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5461 << Arg->getSourceRange(); 5462 } 5463 return false; 5464 } 5465 5466 /// CheckObjCString - Checks that the format string argument to the os_log() 5467 /// and os_trace() functions is correct, and converts it to const char *. 5468 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5469 Arg = Arg->IgnoreParenCasts(); 5470 auto *Literal = dyn_cast<StringLiteral>(Arg); 5471 if (!Literal) { 5472 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5473 Literal = ObjcLiteral->getString(); 5474 } 5475 } 5476 5477 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5478 return ExprError( 5479 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5480 << Arg->getSourceRange()); 5481 } 5482 5483 ExprResult Result(Literal); 5484 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5485 InitializedEntity Entity = 5486 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5487 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5488 return Result; 5489 } 5490 5491 /// Check that the user is calling the appropriate va_start builtin for the 5492 /// target and calling convention. 5493 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5494 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5495 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5496 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5497 TT.getArch() == llvm::Triple::aarch64_32); 5498 bool IsWindows = TT.isOSWindows(); 5499 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5500 if (IsX64 || IsAArch64) { 5501 CallingConv CC = CC_C; 5502 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5503 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5504 if (IsMSVAStart) { 5505 // Don't allow this in System V ABI functions. 5506 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5507 return S.Diag(Fn->getBeginLoc(), 5508 diag::err_ms_va_start_used_in_sysv_function); 5509 } else { 5510 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5511 // On x64 Windows, don't allow this in System V ABI functions. 5512 // (Yes, that means there's no corresponding way to support variadic 5513 // System V ABI functions on Windows.) 5514 if ((IsWindows && CC == CC_X86_64SysV) || 5515 (!IsWindows && CC == CC_Win64)) 5516 return S.Diag(Fn->getBeginLoc(), 5517 diag::err_va_start_used_in_wrong_abi_function) 5518 << !IsWindows; 5519 } 5520 return false; 5521 } 5522 5523 if (IsMSVAStart) 5524 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5525 return false; 5526 } 5527 5528 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5529 ParmVarDecl **LastParam = nullptr) { 5530 // Determine whether the current function, block, or obj-c method is variadic 5531 // and get its parameter list. 5532 bool IsVariadic = false; 5533 ArrayRef<ParmVarDecl *> Params; 5534 DeclContext *Caller = S.CurContext; 5535 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5536 IsVariadic = Block->isVariadic(); 5537 Params = Block->parameters(); 5538 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5539 IsVariadic = FD->isVariadic(); 5540 Params = FD->parameters(); 5541 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5542 IsVariadic = MD->isVariadic(); 5543 // FIXME: This isn't correct for methods (results in bogus warning). 5544 Params = MD->parameters(); 5545 } else if (isa<CapturedDecl>(Caller)) { 5546 // We don't support va_start in a CapturedDecl. 5547 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5548 return true; 5549 } else { 5550 // This must be some other declcontext that parses exprs. 5551 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5552 return true; 5553 } 5554 5555 if (!IsVariadic) { 5556 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5557 return true; 5558 } 5559 5560 if (LastParam) 5561 *LastParam = Params.empty() ? nullptr : Params.back(); 5562 5563 return false; 5564 } 5565 5566 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5567 /// for validity. Emit an error and return true on failure; return false 5568 /// on success. 5569 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5570 Expr *Fn = TheCall->getCallee(); 5571 5572 if (checkVAStartABI(*this, BuiltinID, Fn)) 5573 return true; 5574 5575 if (TheCall->getNumArgs() > 2) { 5576 Diag(TheCall->getArg(2)->getBeginLoc(), 5577 diag::err_typecheck_call_too_many_args) 5578 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5579 << Fn->getSourceRange() 5580 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5581 (*(TheCall->arg_end() - 1))->getEndLoc()); 5582 return true; 5583 } 5584 5585 if (TheCall->getNumArgs() < 2) { 5586 return Diag(TheCall->getEndLoc(), 5587 diag::err_typecheck_call_too_few_args_at_least) 5588 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5589 } 5590 5591 // Type-check the first argument normally. 5592 if (checkBuiltinArgument(*this, TheCall, 0)) 5593 return true; 5594 5595 // Check that the current function is variadic, and get its last parameter. 5596 ParmVarDecl *LastParam; 5597 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5598 return true; 5599 5600 // Verify that the second argument to the builtin is the last argument of the 5601 // current function or method. 5602 bool SecondArgIsLastNamedArgument = false; 5603 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5604 5605 // These are valid if SecondArgIsLastNamedArgument is false after the next 5606 // block. 5607 QualType Type; 5608 SourceLocation ParamLoc; 5609 bool IsCRegister = false; 5610 5611 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5612 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5613 SecondArgIsLastNamedArgument = PV == LastParam; 5614 5615 Type = PV->getType(); 5616 ParamLoc = PV->getLocation(); 5617 IsCRegister = 5618 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5619 } 5620 } 5621 5622 if (!SecondArgIsLastNamedArgument) 5623 Diag(TheCall->getArg(1)->getBeginLoc(), 5624 diag::warn_second_arg_of_va_start_not_last_named_param); 5625 else if (IsCRegister || Type->isReferenceType() || 5626 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5627 // Promotable integers are UB, but enumerations need a bit of 5628 // extra checking to see what their promotable type actually is. 5629 if (!Type->isPromotableIntegerType()) 5630 return false; 5631 if (!Type->isEnumeralType()) 5632 return true; 5633 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5634 return !(ED && 5635 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5636 }()) { 5637 unsigned Reason = 0; 5638 if (Type->isReferenceType()) Reason = 1; 5639 else if (IsCRegister) Reason = 2; 5640 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5641 Diag(ParamLoc, diag::note_parameter_type) << Type; 5642 } 5643 5644 TheCall->setType(Context.VoidTy); 5645 return false; 5646 } 5647 5648 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5649 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5650 // const char *named_addr); 5651 5652 Expr *Func = Call->getCallee(); 5653 5654 if (Call->getNumArgs() < 3) 5655 return Diag(Call->getEndLoc(), 5656 diag::err_typecheck_call_too_few_args_at_least) 5657 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5658 5659 // Type-check the first argument normally. 5660 if (checkBuiltinArgument(*this, Call, 0)) 5661 return true; 5662 5663 // Check that the current function is variadic. 5664 if (checkVAStartIsInVariadicFunction(*this, Func)) 5665 return true; 5666 5667 // __va_start on Windows does not validate the parameter qualifiers 5668 5669 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5670 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5671 5672 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5673 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5674 5675 const QualType &ConstCharPtrTy = 5676 Context.getPointerType(Context.CharTy.withConst()); 5677 if (!Arg1Ty->isPointerType() || 5678 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5679 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5680 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5681 << 0 /* qualifier difference */ 5682 << 3 /* parameter mismatch */ 5683 << 2 << Arg1->getType() << ConstCharPtrTy; 5684 5685 const QualType SizeTy = Context.getSizeType(); 5686 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5687 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5688 << Arg2->getType() << SizeTy << 1 /* different class */ 5689 << 0 /* qualifier difference */ 5690 << 3 /* parameter mismatch */ 5691 << 3 << Arg2->getType() << SizeTy; 5692 5693 return false; 5694 } 5695 5696 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5697 /// friends. This is declared to take (...), so we have to check everything. 5698 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5699 if (TheCall->getNumArgs() < 2) 5700 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5701 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5702 if (TheCall->getNumArgs() > 2) 5703 return Diag(TheCall->getArg(2)->getBeginLoc(), 5704 diag::err_typecheck_call_too_many_args) 5705 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5706 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5707 (*(TheCall->arg_end() - 1))->getEndLoc()); 5708 5709 ExprResult OrigArg0 = TheCall->getArg(0); 5710 ExprResult OrigArg1 = TheCall->getArg(1); 5711 5712 // Do standard promotions between the two arguments, returning their common 5713 // type. 5714 QualType Res = UsualArithmeticConversions( 5715 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5716 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5717 return true; 5718 5719 // Make sure any conversions are pushed back into the call; this is 5720 // type safe since unordered compare builtins are declared as "_Bool 5721 // foo(...)". 5722 TheCall->setArg(0, OrigArg0.get()); 5723 TheCall->setArg(1, OrigArg1.get()); 5724 5725 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5726 return false; 5727 5728 // If the common type isn't a real floating type, then the arguments were 5729 // invalid for this operation. 5730 if (Res.isNull() || !Res->isRealFloatingType()) 5731 return Diag(OrigArg0.get()->getBeginLoc(), 5732 diag::err_typecheck_call_invalid_ordered_compare) 5733 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5734 << SourceRange(OrigArg0.get()->getBeginLoc(), 5735 OrigArg1.get()->getEndLoc()); 5736 5737 return false; 5738 } 5739 5740 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5741 /// __builtin_isnan and friends. This is declared to take (...), so we have 5742 /// to check everything. We expect the last argument to be a floating point 5743 /// value. 5744 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5745 if (TheCall->getNumArgs() < NumArgs) 5746 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5747 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5748 if (TheCall->getNumArgs() > NumArgs) 5749 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5750 diag::err_typecheck_call_too_many_args) 5751 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5752 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5753 (*(TheCall->arg_end() - 1))->getEndLoc()); 5754 5755 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5756 // on all preceding parameters just being int. Try all of those. 5757 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5758 Expr *Arg = TheCall->getArg(i); 5759 5760 if (Arg->isTypeDependent()) 5761 return false; 5762 5763 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5764 5765 if (Res.isInvalid()) 5766 return true; 5767 TheCall->setArg(i, Res.get()); 5768 } 5769 5770 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5771 5772 if (OrigArg->isTypeDependent()) 5773 return false; 5774 5775 // Usual Unary Conversions will convert half to float, which we want for 5776 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5777 // type how it is, but do normal L->Rvalue conversions. 5778 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5779 OrigArg = UsualUnaryConversions(OrigArg).get(); 5780 else 5781 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5782 TheCall->setArg(NumArgs - 1, OrigArg); 5783 5784 // This operation requires a non-_Complex floating-point number. 5785 if (!OrigArg->getType()->isRealFloatingType()) 5786 return Diag(OrigArg->getBeginLoc(), 5787 diag::err_typecheck_call_invalid_unary_fp) 5788 << OrigArg->getType() << OrigArg->getSourceRange(); 5789 5790 return false; 5791 } 5792 5793 /// Perform semantic analysis for a call to __builtin_complex. 5794 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) { 5795 if (checkArgCount(*this, TheCall, 2)) 5796 return true; 5797 5798 bool Dependent = false; 5799 for (unsigned I = 0; I != 2; ++I) { 5800 Expr *Arg = TheCall->getArg(I); 5801 QualType T = Arg->getType(); 5802 if (T->isDependentType()) { 5803 Dependent = true; 5804 continue; 5805 } 5806 5807 // Despite supporting _Complex int, GCC requires a real floating point type 5808 // for the operands of __builtin_complex. 5809 if (!T->isRealFloatingType()) { 5810 return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp) 5811 << Arg->getType() << Arg->getSourceRange(); 5812 } 5813 5814 ExprResult Converted = DefaultLvalueConversion(Arg); 5815 if (Converted.isInvalid()) 5816 return true; 5817 TheCall->setArg(I, Converted.get()); 5818 } 5819 5820 if (Dependent) { 5821 TheCall->setType(Context.DependentTy); 5822 return false; 5823 } 5824 5825 Expr *Real = TheCall->getArg(0); 5826 Expr *Imag = TheCall->getArg(1); 5827 if (!Context.hasSameType(Real->getType(), Imag->getType())) { 5828 return Diag(Real->getBeginLoc(), 5829 diag::err_typecheck_call_different_arg_types) 5830 << Real->getType() << Imag->getType() 5831 << Real->getSourceRange() << Imag->getSourceRange(); 5832 } 5833 5834 // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers; 5835 // don't allow this builtin to form those types either. 5836 // FIXME: Should we allow these types? 5837 if (Real->getType()->isFloat16Type()) 5838 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 5839 << "_Float16"; 5840 if (Real->getType()->isHalfType()) 5841 return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec) 5842 << "half"; 5843 5844 TheCall->setType(Context.getComplexType(Real->getType())); 5845 return false; 5846 } 5847 5848 // Customized Sema Checking for VSX builtins that have the following signature: 5849 // vector [...] builtinName(vector [...], vector [...], const int); 5850 // Which takes the same type of vectors (any legal vector type) for the first 5851 // two arguments and takes compile time constant for the third argument. 5852 // Example builtins are : 5853 // vector double vec_xxpermdi(vector double, vector double, int); 5854 // vector short vec_xxsldwi(vector short, vector short, int); 5855 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5856 unsigned ExpectedNumArgs = 3; 5857 if (TheCall->getNumArgs() < ExpectedNumArgs) 5858 return Diag(TheCall->getEndLoc(), 5859 diag::err_typecheck_call_too_few_args_at_least) 5860 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5861 << TheCall->getSourceRange(); 5862 5863 if (TheCall->getNumArgs() > ExpectedNumArgs) 5864 return Diag(TheCall->getEndLoc(), 5865 diag::err_typecheck_call_too_many_args_at_most) 5866 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5867 << TheCall->getSourceRange(); 5868 5869 // Check the third argument is a compile time constant 5870 if (!TheCall->getArg(2)->isIntegerConstantExpr(Context)) 5871 return Diag(TheCall->getBeginLoc(), 5872 diag::err_vsx_builtin_nonconstant_argument) 5873 << 3 /* argument index */ << TheCall->getDirectCallee() 5874 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5875 TheCall->getArg(2)->getEndLoc()); 5876 5877 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5878 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5879 5880 // Check the type of argument 1 and argument 2 are vectors. 5881 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5882 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5883 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5884 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5885 << TheCall->getDirectCallee() 5886 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5887 TheCall->getArg(1)->getEndLoc()); 5888 } 5889 5890 // Check the first two arguments are the same type. 5891 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5892 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5893 << TheCall->getDirectCallee() 5894 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5895 TheCall->getArg(1)->getEndLoc()); 5896 } 5897 5898 // When default clang type checking is turned off and the customized type 5899 // checking is used, the returning type of the function must be explicitly 5900 // set. Otherwise it is _Bool by default. 5901 TheCall->setType(Arg1Ty); 5902 5903 return false; 5904 } 5905 5906 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5907 // This is declared to take (...), so we have to check everything. 5908 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5909 if (TheCall->getNumArgs() < 2) 5910 return ExprError(Diag(TheCall->getEndLoc(), 5911 diag::err_typecheck_call_too_few_args_at_least) 5912 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5913 << TheCall->getSourceRange()); 5914 5915 // Determine which of the following types of shufflevector we're checking: 5916 // 1) unary, vector mask: (lhs, mask) 5917 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5918 QualType resType = TheCall->getArg(0)->getType(); 5919 unsigned numElements = 0; 5920 5921 if (!TheCall->getArg(0)->isTypeDependent() && 5922 !TheCall->getArg(1)->isTypeDependent()) { 5923 QualType LHSType = TheCall->getArg(0)->getType(); 5924 QualType RHSType = TheCall->getArg(1)->getType(); 5925 5926 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5927 return ExprError( 5928 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5929 << TheCall->getDirectCallee() 5930 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5931 TheCall->getArg(1)->getEndLoc())); 5932 5933 numElements = LHSType->castAs<VectorType>()->getNumElements(); 5934 unsigned numResElements = TheCall->getNumArgs() - 2; 5935 5936 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5937 // with mask. If so, verify that RHS is an integer vector type with the 5938 // same number of elts as lhs. 5939 if (TheCall->getNumArgs() == 2) { 5940 if (!RHSType->hasIntegerRepresentation() || 5941 RHSType->castAs<VectorType>()->getNumElements() != numElements) 5942 return ExprError(Diag(TheCall->getBeginLoc(), 5943 diag::err_vec_builtin_incompatible_vector) 5944 << TheCall->getDirectCallee() 5945 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5946 TheCall->getArg(1)->getEndLoc())); 5947 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5948 return ExprError(Diag(TheCall->getBeginLoc(), 5949 diag::err_vec_builtin_incompatible_vector) 5950 << TheCall->getDirectCallee() 5951 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5952 TheCall->getArg(1)->getEndLoc())); 5953 } else if (numElements != numResElements) { 5954 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 5955 resType = Context.getVectorType(eltType, numResElements, 5956 VectorType::GenericVector); 5957 } 5958 } 5959 5960 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5961 if (TheCall->getArg(i)->isTypeDependent() || 5962 TheCall->getArg(i)->isValueDependent()) 5963 continue; 5964 5965 Optional<llvm::APSInt> Result; 5966 if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context))) 5967 return ExprError(Diag(TheCall->getBeginLoc(), 5968 diag::err_shufflevector_nonconstant_argument) 5969 << TheCall->getArg(i)->getSourceRange()); 5970 5971 // Allow -1 which will be translated to undef in the IR. 5972 if (Result->isSigned() && Result->isAllOnesValue()) 5973 continue; 5974 5975 if (Result->getActiveBits() > 64 || 5976 Result->getZExtValue() >= numElements * 2) 5977 return ExprError(Diag(TheCall->getBeginLoc(), 5978 diag::err_shufflevector_argument_too_large) 5979 << TheCall->getArg(i)->getSourceRange()); 5980 } 5981 5982 SmallVector<Expr*, 32> exprs; 5983 5984 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5985 exprs.push_back(TheCall->getArg(i)); 5986 TheCall->setArg(i, nullptr); 5987 } 5988 5989 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5990 TheCall->getCallee()->getBeginLoc(), 5991 TheCall->getRParenLoc()); 5992 } 5993 5994 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5995 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5996 SourceLocation BuiltinLoc, 5997 SourceLocation RParenLoc) { 5998 ExprValueKind VK = VK_RValue; 5999 ExprObjectKind OK = OK_Ordinary; 6000 QualType DstTy = TInfo->getType(); 6001 QualType SrcTy = E->getType(); 6002 6003 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 6004 return ExprError(Diag(BuiltinLoc, 6005 diag::err_convertvector_non_vector) 6006 << E->getSourceRange()); 6007 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 6008 return ExprError(Diag(BuiltinLoc, 6009 diag::err_convertvector_non_vector_type)); 6010 6011 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 6012 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 6013 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 6014 if (SrcElts != DstElts) 6015 return ExprError(Diag(BuiltinLoc, 6016 diag::err_convertvector_incompatible_vector) 6017 << E->getSourceRange()); 6018 } 6019 6020 return new (Context) 6021 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 6022 } 6023 6024 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 6025 // This is declared to take (const void*, ...) and can take two 6026 // optional constant int args. 6027 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 6028 unsigned NumArgs = TheCall->getNumArgs(); 6029 6030 if (NumArgs > 3) 6031 return Diag(TheCall->getEndLoc(), 6032 diag::err_typecheck_call_too_many_args_at_most) 6033 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6034 6035 // Argument 0 is checked for us and the remaining arguments must be 6036 // constant integers. 6037 for (unsigned i = 1; i != NumArgs; ++i) 6038 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 6039 return true; 6040 6041 return false; 6042 } 6043 6044 /// SemaBuiltinAssume - Handle __assume (MS Extension). 6045 // __assume does not evaluate its arguments, and should warn if its argument 6046 // has side effects. 6047 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 6048 Expr *Arg = TheCall->getArg(0); 6049 if (Arg->isInstantiationDependent()) return false; 6050 6051 if (Arg->HasSideEffects(Context)) 6052 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 6053 << Arg->getSourceRange() 6054 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 6055 6056 return false; 6057 } 6058 6059 /// Handle __builtin_alloca_with_align. This is declared 6060 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 6061 /// than 8. 6062 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 6063 // The alignment must be a constant integer. 6064 Expr *Arg = TheCall->getArg(1); 6065 6066 // We can't check the value of a dependent argument. 6067 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6068 if (const auto *UE = 6069 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 6070 if (UE->getKind() == UETT_AlignOf || 6071 UE->getKind() == UETT_PreferredAlignOf) 6072 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 6073 << Arg->getSourceRange(); 6074 6075 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 6076 6077 if (!Result.isPowerOf2()) 6078 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6079 << Arg->getSourceRange(); 6080 6081 if (Result < Context.getCharWidth()) 6082 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 6083 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 6084 6085 if (Result > std::numeric_limits<int32_t>::max()) 6086 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 6087 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 6088 } 6089 6090 return false; 6091 } 6092 6093 /// Handle __builtin_assume_aligned. This is declared 6094 /// as (const void*, size_t, ...) and can take one optional constant int arg. 6095 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 6096 unsigned NumArgs = TheCall->getNumArgs(); 6097 6098 if (NumArgs > 3) 6099 return Diag(TheCall->getEndLoc(), 6100 diag::err_typecheck_call_too_many_args_at_most) 6101 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 6102 6103 // The alignment must be a constant integer. 6104 Expr *Arg = TheCall->getArg(1); 6105 6106 // We can't check the value of a dependent argument. 6107 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 6108 llvm::APSInt Result; 6109 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6110 return true; 6111 6112 if (!Result.isPowerOf2()) 6113 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 6114 << Arg->getSourceRange(); 6115 6116 if (Result > Sema::MaximumAlignment) 6117 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 6118 << Arg->getSourceRange() << Sema::MaximumAlignment; 6119 } 6120 6121 if (NumArgs > 2) { 6122 ExprResult Arg(TheCall->getArg(2)); 6123 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 6124 Context.getSizeType(), false); 6125 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6126 if (Arg.isInvalid()) return true; 6127 TheCall->setArg(2, Arg.get()); 6128 } 6129 6130 return false; 6131 } 6132 6133 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 6134 unsigned BuiltinID = 6135 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 6136 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 6137 6138 unsigned NumArgs = TheCall->getNumArgs(); 6139 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 6140 if (NumArgs < NumRequiredArgs) { 6141 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 6142 << 0 /* function call */ << NumRequiredArgs << NumArgs 6143 << TheCall->getSourceRange(); 6144 } 6145 if (NumArgs >= NumRequiredArgs + 0x100) { 6146 return Diag(TheCall->getEndLoc(), 6147 diag::err_typecheck_call_too_many_args_at_most) 6148 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 6149 << TheCall->getSourceRange(); 6150 } 6151 unsigned i = 0; 6152 6153 // For formatting call, check buffer arg. 6154 if (!IsSizeCall) { 6155 ExprResult Arg(TheCall->getArg(i)); 6156 InitializedEntity Entity = InitializedEntity::InitializeParameter( 6157 Context, Context.VoidPtrTy, false); 6158 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 6159 if (Arg.isInvalid()) 6160 return true; 6161 TheCall->setArg(i, Arg.get()); 6162 i++; 6163 } 6164 6165 // Check string literal arg. 6166 unsigned FormatIdx = i; 6167 { 6168 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 6169 if (Arg.isInvalid()) 6170 return true; 6171 TheCall->setArg(i, Arg.get()); 6172 i++; 6173 } 6174 6175 // Make sure variadic args are scalar. 6176 unsigned FirstDataArg = i; 6177 while (i < NumArgs) { 6178 ExprResult Arg = DefaultVariadicArgumentPromotion( 6179 TheCall->getArg(i), VariadicFunction, nullptr); 6180 if (Arg.isInvalid()) 6181 return true; 6182 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6183 if (ArgSize.getQuantity() >= 0x100) { 6184 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6185 << i << (int)ArgSize.getQuantity() << 0xff 6186 << TheCall->getSourceRange(); 6187 } 6188 TheCall->setArg(i, Arg.get()); 6189 i++; 6190 } 6191 6192 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6193 // call to avoid duplicate diagnostics. 6194 if (!IsSizeCall) { 6195 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6196 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6197 bool Success = CheckFormatArguments( 6198 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6199 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6200 CheckedVarArgs); 6201 if (!Success) 6202 return true; 6203 } 6204 6205 if (IsSizeCall) { 6206 TheCall->setType(Context.getSizeType()); 6207 } else { 6208 TheCall->setType(Context.VoidPtrTy); 6209 } 6210 return false; 6211 } 6212 6213 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6214 /// TheCall is a constant expression. 6215 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6216 llvm::APSInt &Result) { 6217 Expr *Arg = TheCall->getArg(ArgNum); 6218 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6219 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6220 6221 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6222 6223 Optional<llvm::APSInt> R; 6224 if (!(R = Arg->getIntegerConstantExpr(Context))) 6225 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6226 << FDecl->getDeclName() << Arg->getSourceRange(); 6227 Result = *R; 6228 return false; 6229 } 6230 6231 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6232 /// TheCall is a constant expression in the range [Low, High]. 6233 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6234 int Low, int High, bool RangeIsError) { 6235 if (isConstantEvaluated()) 6236 return false; 6237 llvm::APSInt Result; 6238 6239 // We can't check the value of a dependent argument. 6240 Expr *Arg = TheCall->getArg(ArgNum); 6241 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6242 return false; 6243 6244 // Check constant-ness first. 6245 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6246 return true; 6247 6248 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6249 if (RangeIsError) 6250 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6251 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6252 else 6253 // Defer the warning until we know if the code will be emitted so that 6254 // dead code can ignore this. 6255 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6256 PDiag(diag::warn_argument_invalid_range) 6257 << Result.toString(10) << Low << High 6258 << Arg->getSourceRange()); 6259 } 6260 6261 return false; 6262 } 6263 6264 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6265 /// TheCall is a constant expression is a multiple of Num.. 6266 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6267 unsigned Num) { 6268 llvm::APSInt Result; 6269 6270 // We can't check the value of a dependent argument. 6271 Expr *Arg = TheCall->getArg(ArgNum); 6272 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6273 return false; 6274 6275 // Check constant-ness first. 6276 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6277 return true; 6278 6279 if (Result.getSExtValue() % Num != 0) 6280 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6281 << Num << Arg->getSourceRange(); 6282 6283 return false; 6284 } 6285 6286 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6287 /// constant expression representing a power of 2. 6288 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6289 llvm::APSInt Result; 6290 6291 // We can't check the value of a dependent argument. 6292 Expr *Arg = TheCall->getArg(ArgNum); 6293 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6294 return false; 6295 6296 // Check constant-ness first. 6297 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6298 return true; 6299 6300 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6301 // and only if x is a power of 2. 6302 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6303 return false; 6304 6305 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6306 << Arg->getSourceRange(); 6307 } 6308 6309 static bool IsShiftedByte(llvm::APSInt Value) { 6310 if (Value.isNegative()) 6311 return false; 6312 6313 // Check if it's a shifted byte, by shifting it down 6314 while (true) { 6315 // If the value fits in the bottom byte, the check passes. 6316 if (Value < 0x100) 6317 return true; 6318 6319 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6320 // fails. 6321 if ((Value & 0xFF) != 0) 6322 return false; 6323 6324 // If the bottom 8 bits are all 0, but something above that is nonzero, 6325 // then shifting the value right by 8 bits won't affect whether it's a 6326 // shifted byte or not. So do that, and go round again. 6327 Value >>= 8; 6328 } 6329 } 6330 6331 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6332 /// a constant expression representing an arbitrary byte value shifted left by 6333 /// a multiple of 8 bits. 6334 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6335 unsigned ArgBits) { 6336 llvm::APSInt Result; 6337 6338 // We can't check the value of a dependent argument. 6339 Expr *Arg = TheCall->getArg(ArgNum); 6340 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6341 return false; 6342 6343 // Check constant-ness first. 6344 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6345 return true; 6346 6347 // Truncate to the given size. 6348 Result = Result.getLoBits(ArgBits); 6349 Result.setIsUnsigned(true); 6350 6351 if (IsShiftedByte(Result)) 6352 return false; 6353 6354 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6355 << Arg->getSourceRange(); 6356 } 6357 6358 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6359 /// TheCall is a constant expression representing either a shifted byte value, 6360 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6361 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6362 /// Arm MVE intrinsics. 6363 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6364 int ArgNum, 6365 unsigned ArgBits) { 6366 llvm::APSInt Result; 6367 6368 // We can't check the value of a dependent argument. 6369 Expr *Arg = TheCall->getArg(ArgNum); 6370 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6371 return false; 6372 6373 // Check constant-ness first. 6374 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6375 return true; 6376 6377 // Truncate to the given size. 6378 Result = Result.getLoBits(ArgBits); 6379 Result.setIsUnsigned(true); 6380 6381 // Check to see if it's in either of the required forms. 6382 if (IsShiftedByte(Result) || 6383 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6384 return false; 6385 6386 return Diag(TheCall->getBeginLoc(), 6387 diag::err_argument_not_shifted_byte_or_xxff) 6388 << Arg->getSourceRange(); 6389 } 6390 6391 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6392 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6393 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6394 if (checkArgCount(*this, TheCall, 2)) 6395 return true; 6396 Expr *Arg0 = TheCall->getArg(0); 6397 Expr *Arg1 = TheCall->getArg(1); 6398 6399 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6400 if (FirstArg.isInvalid()) 6401 return true; 6402 QualType FirstArgType = FirstArg.get()->getType(); 6403 if (!FirstArgType->isAnyPointerType()) 6404 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6405 << "first" << FirstArgType << Arg0->getSourceRange(); 6406 TheCall->setArg(0, FirstArg.get()); 6407 6408 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6409 if (SecArg.isInvalid()) 6410 return true; 6411 QualType SecArgType = SecArg.get()->getType(); 6412 if (!SecArgType->isIntegerType()) 6413 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6414 << "second" << SecArgType << Arg1->getSourceRange(); 6415 6416 // Derive the return type from the pointer argument. 6417 TheCall->setType(FirstArgType); 6418 return false; 6419 } 6420 6421 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6422 if (checkArgCount(*this, TheCall, 2)) 6423 return true; 6424 6425 Expr *Arg0 = TheCall->getArg(0); 6426 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6427 if (FirstArg.isInvalid()) 6428 return true; 6429 QualType FirstArgType = FirstArg.get()->getType(); 6430 if (!FirstArgType->isAnyPointerType()) 6431 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6432 << "first" << FirstArgType << Arg0->getSourceRange(); 6433 TheCall->setArg(0, FirstArg.get()); 6434 6435 // Derive the return type from the pointer argument. 6436 TheCall->setType(FirstArgType); 6437 6438 // Second arg must be an constant in range [0,15] 6439 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6440 } 6441 6442 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6443 if (checkArgCount(*this, TheCall, 2)) 6444 return true; 6445 Expr *Arg0 = TheCall->getArg(0); 6446 Expr *Arg1 = TheCall->getArg(1); 6447 6448 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6449 if (FirstArg.isInvalid()) 6450 return true; 6451 QualType FirstArgType = FirstArg.get()->getType(); 6452 if (!FirstArgType->isAnyPointerType()) 6453 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6454 << "first" << FirstArgType << Arg0->getSourceRange(); 6455 6456 QualType SecArgType = Arg1->getType(); 6457 if (!SecArgType->isIntegerType()) 6458 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6459 << "second" << SecArgType << Arg1->getSourceRange(); 6460 TheCall->setType(Context.IntTy); 6461 return false; 6462 } 6463 6464 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6465 BuiltinID == AArch64::BI__builtin_arm_stg) { 6466 if (checkArgCount(*this, TheCall, 1)) 6467 return true; 6468 Expr *Arg0 = TheCall->getArg(0); 6469 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6470 if (FirstArg.isInvalid()) 6471 return true; 6472 6473 QualType FirstArgType = FirstArg.get()->getType(); 6474 if (!FirstArgType->isAnyPointerType()) 6475 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6476 << "first" << FirstArgType << Arg0->getSourceRange(); 6477 TheCall->setArg(0, FirstArg.get()); 6478 6479 // Derive the return type from the pointer argument. 6480 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6481 TheCall->setType(FirstArgType); 6482 return false; 6483 } 6484 6485 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6486 Expr *ArgA = TheCall->getArg(0); 6487 Expr *ArgB = TheCall->getArg(1); 6488 6489 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6490 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6491 6492 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6493 return true; 6494 6495 QualType ArgTypeA = ArgExprA.get()->getType(); 6496 QualType ArgTypeB = ArgExprB.get()->getType(); 6497 6498 auto isNull = [&] (Expr *E) -> bool { 6499 return E->isNullPointerConstant( 6500 Context, Expr::NPC_ValueDependentIsNotNull); }; 6501 6502 // argument should be either a pointer or null 6503 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6504 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6505 << "first" << ArgTypeA << ArgA->getSourceRange(); 6506 6507 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6508 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6509 << "second" << ArgTypeB << ArgB->getSourceRange(); 6510 6511 // Ensure Pointee types are compatible 6512 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6513 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6514 QualType pointeeA = ArgTypeA->getPointeeType(); 6515 QualType pointeeB = ArgTypeB->getPointeeType(); 6516 if (!Context.typesAreCompatible( 6517 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6518 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6519 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6520 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6521 << ArgB->getSourceRange(); 6522 } 6523 } 6524 6525 // at least one argument should be pointer type 6526 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6527 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6528 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6529 6530 if (isNull(ArgA)) // adopt type of the other pointer 6531 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6532 6533 if (isNull(ArgB)) 6534 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6535 6536 TheCall->setArg(0, ArgExprA.get()); 6537 TheCall->setArg(1, ArgExprB.get()); 6538 TheCall->setType(Context.LongLongTy); 6539 return false; 6540 } 6541 assert(false && "Unhandled ARM MTE intrinsic"); 6542 return true; 6543 } 6544 6545 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6546 /// TheCall is an ARM/AArch64 special register string literal. 6547 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6548 int ArgNum, unsigned ExpectedFieldNum, 6549 bool AllowName) { 6550 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6551 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6552 BuiltinID == ARM::BI__builtin_arm_rsr || 6553 BuiltinID == ARM::BI__builtin_arm_rsrp || 6554 BuiltinID == ARM::BI__builtin_arm_wsr || 6555 BuiltinID == ARM::BI__builtin_arm_wsrp; 6556 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6557 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6558 BuiltinID == AArch64::BI__builtin_arm_rsr || 6559 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6560 BuiltinID == AArch64::BI__builtin_arm_wsr || 6561 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6562 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6563 6564 // We can't check the value of a dependent argument. 6565 Expr *Arg = TheCall->getArg(ArgNum); 6566 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6567 return false; 6568 6569 // Check if the argument is a string literal. 6570 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6571 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6572 << Arg->getSourceRange(); 6573 6574 // Check the type of special register given. 6575 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6576 SmallVector<StringRef, 6> Fields; 6577 Reg.split(Fields, ":"); 6578 6579 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6580 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6581 << Arg->getSourceRange(); 6582 6583 // If the string is the name of a register then we cannot check that it is 6584 // valid here but if the string is of one the forms described in ACLE then we 6585 // can check that the supplied fields are integers and within the valid 6586 // ranges. 6587 if (Fields.size() > 1) { 6588 bool FiveFields = Fields.size() == 5; 6589 6590 bool ValidString = true; 6591 if (IsARMBuiltin) { 6592 ValidString &= Fields[0].startswith_lower("cp") || 6593 Fields[0].startswith_lower("p"); 6594 if (ValidString) 6595 Fields[0] = 6596 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6597 6598 ValidString &= Fields[2].startswith_lower("c"); 6599 if (ValidString) 6600 Fields[2] = Fields[2].drop_front(1); 6601 6602 if (FiveFields) { 6603 ValidString &= Fields[3].startswith_lower("c"); 6604 if (ValidString) 6605 Fields[3] = Fields[3].drop_front(1); 6606 } 6607 } 6608 6609 SmallVector<int, 5> Ranges; 6610 if (FiveFields) 6611 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6612 else 6613 Ranges.append({15, 7, 15}); 6614 6615 for (unsigned i=0; i<Fields.size(); ++i) { 6616 int IntField; 6617 ValidString &= !Fields[i].getAsInteger(10, IntField); 6618 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6619 } 6620 6621 if (!ValidString) 6622 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6623 << Arg->getSourceRange(); 6624 } else if (IsAArch64Builtin && Fields.size() == 1) { 6625 // If the register name is one of those that appear in the condition below 6626 // and the special register builtin being used is one of the write builtins, 6627 // then we require that the argument provided for writing to the register 6628 // is an integer constant expression. This is because it will be lowered to 6629 // an MSR (immediate) instruction, so we need to know the immediate at 6630 // compile time. 6631 if (TheCall->getNumArgs() != 2) 6632 return false; 6633 6634 std::string RegLower = Reg.lower(); 6635 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6636 RegLower != "pan" && RegLower != "uao") 6637 return false; 6638 6639 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6640 } 6641 6642 return false; 6643 } 6644 6645 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6646 /// This checks that the target supports __builtin_longjmp and 6647 /// that val is a constant 1. 6648 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6649 if (!Context.getTargetInfo().hasSjLjLowering()) 6650 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6651 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6652 6653 Expr *Arg = TheCall->getArg(1); 6654 llvm::APSInt Result; 6655 6656 // TODO: This is less than ideal. Overload this to take a value. 6657 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6658 return true; 6659 6660 if (Result != 1) 6661 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6662 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6663 6664 return false; 6665 } 6666 6667 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6668 /// This checks that the target supports __builtin_setjmp. 6669 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6670 if (!Context.getTargetInfo().hasSjLjLowering()) 6671 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6672 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6673 return false; 6674 } 6675 6676 namespace { 6677 6678 class UncoveredArgHandler { 6679 enum { Unknown = -1, AllCovered = -2 }; 6680 6681 signed FirstUncoveredArg = Unknown; 6682 SmallVector<const Expr *, 4> DiagnosticExprs; 6683 6684 public: 6685 UncoveredArgHandler() = default; 6686 6687 bool hasUncoveredArg() const { 6688 return (FirstUncoveredArg >= 0); 6689 } 6690 6691 unsigned getUncoveredArg() const { 6692 assert(hasUncoveredArg() && "no uncovered argument"); 6693 return FirstUncoveredArg; 6694 } 6695 6696 void setAllCovered() { 6697 // A string has been found with all arguments covered, so clear out 6698 // the diagnostics. 6699 DiagnosticExprs.clear(); 6700 FirstUncoveredArg = AllCovered; 6701 } 6702 6703 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6704 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6705 6706 // Don't update if a previous string covers all arguments. 6707 if (FirstUncoveredArg == AllCovered) 6708 return; 6709 6710 // UncoveredArgHandler tracks the highest uncovered argument index 6711 // and with it all the strings that match this index. 6712 if (NewFirstUncoveredArg == FirstUncoveredArg) 6713 DiagnosticExprs.push_back(StrExpr); 6714 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6715 DiagnosticExprs.clear(); 6716 DiagnosticExprs.push_back(StrExpr); 6717 FirstUncoveredArg = NewFirstUncoveredArg; 6718 } 6719 } 6720 6721 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6722 }; 6723 6724 enum StringLiteralCheckType { 6725 SLCT_NotALiteral, 6726 SLCT_UncheckedLiteral, 6727 SLCT_CheckedLiteral 6728 }; 6729 6730 } // namespace 6731 6732 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6733 BinaryOperatorKind BinOpKind, 6734 bool AddendIsRight) { 6735 unsigned BitWidth = Offset.getBitWidth(); 6736 unsigned AddendBitWidth = Addend.getBitWidth(); 6737 // There might be negative interim results. 6738 if (Addend.isUnsigned()) { 6739 Addend = Addend.zext(++AddendBitWidth); 6740 Addend.setIsSigned(true); 6741 } 6742 // Adjust the bit width of the APSInts. 6743 if (AddendBitWidth > BitWidth) { 6744 Offset = Offset.sext(AddendBitWidth); 6745 BitWidth = AddendBitWidth; 6746 } else if (BitWidth > AddendBitWidth) { 6747 Addend = Addend.sext(BitWidth); 6748 } 6749 6750 bool Ov = false; 6751 llvm::APSInt ResOffset = Offset; 6752 if (BinOpKind == BO_Add) 6753 ResOffset = Offset.sadd_ov(Addend, Ov); 6754 else { 6755 assert(AddendIsRight && BinOpKind == BO_Sub && 6756 "operator must be add or sub with addend on the right"); 6757 ResOffset = Offset.ssub_ov(Addend, Ov); 6758 } 6759 6760 // We add an offset to a pointer here so we should support an offset as big as 6761 // possible. 6762 if (Ov) { 6763 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6764 "index (intermediate) result too big"); 6765 Offset = Offset.sext(2 * BitWidth); 6766 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6767 return; 6768 } 6769 6770 Offset = ResOffset; 6771 } 6772 6773 namespace { 6774 6775 // This is a wrapper class around StringLiteral to support offsetted string 6776 // literals as format strings. It takes the offset into account when returning 6777 // the string and its length or the source locations to display notes correctly. 6778 class FormatStringLiteral { 6779 const StringLiteral *FExpr; 6780 int64_t Offset; 6781 6782 public: 6783 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6784 : FExpr(fexpr), Offset(Offset) {} 6785 6786 StringRef getString() const { 6787 return FExpr->getString().drop_front(Offset); 6788 } 6789 6790 unsigned getByteLength() const { 6791 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6792 } 6793 6794 unsigned getLength() const { return FExpr->getLength() - Offset; } 6795 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6796 6797 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6798 6799 QualType getType() const { return FExpr->getType(); } 6800 6801 bool isAscii() const { return FExpr->isAscii(); } 6802 bool isWide() const { return FExpr->isWide(); } 6803 bool isUTF8() const { return FExpr->isUTF8(); } 6804 bool isUTF16() const { return FExpr->isUTF16(); } 6805 bool isUTF32() const { return FExpr->isUTF32(); } 6806 bool isPascal() const { return FExpr->isPascal(); } 6807 6808 SourceLocation getLocationOfByte( 6809 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6810 const TargetInfo &Target, unsigned *StartToken = nullptr, 6811 unsigned *StartTokenByteOffset = nullptr) const { 6812 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6813 StartToken, StartTokenByteOffset); 6814 } 6815 6816 SourceLocation getBeginLoc() const LLVM_READONLY { 6817 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6818 } 6819 6820 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6821 }; 6822 6823 } // namespace 6824 6825 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6826 const Expr *OrigFormatExpr, 6827 ArrayRef<const Expr *> Args, 6828 bool HasVAListArg, unsigned format_idx, 6829 unsigned firstDataArg, 6830 Sema::FormatStringType Type, 6831 bool inFunctionCall, 6832 Sema::VariadicCallType CallType, 6833 llvm::SmallBitVector &CheckedVarArgs, 6834 UncoveredArgHandler &UncoveredArg, 6835 bool IgnoreStringsWithoutSpecifiers); 6836 6837 // Determine if an expression is a string literal or constant string. 6838 // If this function returns false on the arguments to a function expecting a 6839 // format string, we will usually need to emit a warning. 6840 // True string literals are then checked by CheckFormatString. 6841 static StringLiteralCheckType 6842 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6843 bool HasVAListArg, unsigned format_idx, 6844 unsigned firstDataArg, Sema::FormatStringType Type, 6845 Sema::VariadicCallType CallType, bool InFunctionCall, 6846 llvm::SmallBitVector &CheckedVarArgs, 6847 UncoveredArgHandler &UncoveredArg, 6848 llvm::APSInt Offset, 6849 bool IgnoreStringsWithoutSpecifiers = false) { 6850 if (S.isConstantEvaluated()) 6851 return SLCT_NotALiteral; 6852 tryAgain: 6853 assert(Offset.isSigned() && "invalid offset"); 6854 6855 if (E->isTypeDependent() || E->isValueDependent()) 6856 return SLCT_NotALiteral; 6857 6858 E = E->IgnoreParenCasts(); 6859 6860 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6861 // Technically -Wformat-nonliteral does not warn about this case. 6862 // The behavior of printf and friends in this case is implementation 6863 // dependent. Ideally if the format string cannot be null then 6864 // it should have a 'nonnull' attribute in the function prototype. 6865 return SLCT_UncheckedLiteral; 6866 6867 switch (E->getStmtClass()) { 6868 case Stmt::BinaryConditionalOperatorClass: 6869 case Stmt::ConditionalOperatorClass: { 6870 // The expression is a literal if both sub-expressions were, and it was 6871 // completely checked only if both sub-expressions were checked. 6872 const AbstractConditionalOperator *C = 6873 cast<AbstractConditionalOperator>(E); 6874 6875 // Determine whether it is necessary to check both sub-expressions, for 6876 // example, because the condition expression is a constant that can be 6877 // evaluated at compile time. 6878 bool CheckLeft = true, CheckRight = true; 6879 6880 bool Cond; 6881 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6882 S.isConstantEvaluated())) { 6883 if (Cond) 6884 CheckRight = false; 6885 else 6886 CheckLeft = false; 6887 } 6888 6889 // We need to maintain the offsets for the right and the left hand side 6890 // separately to check if every possible indexed expression is a valid 6891 // string literal. They might have different offsets for different string 6892 // literals in the end. 6893 StringLiteralCheckType Left; 6894 if (!CheckLeft) 6895 Left = SLCT_UncheckedLiteral; 6896 else { 6897 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6898 HasVAListArg, format_idx, firstDataArg, 6899 Type, CallType, InFunctionCall, 6900 CheckedVarArgs, UncoveredArg, Offset, 6901 IgnoreStringsWithoutSpecifiers); 6902 if (Left == SLCT_NotALiteral || !CheckRight) { 6903 return Left; 6904 } 6905 } 6906 6907 StringLiteralCheckType Right = checkFormatStringExpr( 6908 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6909 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6910 IgnoreStringsWithoutSpecifiers); 6911 6912 return (CheckLeft && Left < Right) ? Left : Right; 6913 } 6914 6915 case Stmt::ImplicitCastExprClass: 6916 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6917 goto tryAgain; 6918 6919 case Stmt::OpaqueValueExprClass: 6920 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6921 E = src; 6922 goto tryAgain; 6923 } 6924 return SLCT_NotALiteral; 6925 6926 case Stmt::PredefinedExprClass: 6927 // While __func__, etc., are technically not string literals, they 6928 // cannot contain format specifiers and thus are not a security 6929 // liability. 6930 return SLCT_UncheckedLiteral; 6931 6932 case Stmt::DeclRefExprClass: { 6933 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6934 6935 // As an exception, do not flag errors for variables binding to 6936 // const string literals. 6937 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6938 bool isConstant = false; 6939 QualType T = DR->getType(); 6940 6941 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6942 isConstant = AT->getElementType().isConstant(S.Context); 6943 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6944 isConstant = T.isConstant(S.Context) && 6945 PT->getPointeeType().isConstant(S.Context); 6946 } else if (T->isObjCObjectPointerType()) { 6947 // In ObjC, there is usually no "const ObjectPointer" type, 6948 // so don't check if the pointee type is constant. 6949 isConstant = T.isConstant(S.Context); 6950 } 6951 6952 if (isConstant) { 6953 if (const Expr *Init = VD->getAnyInitializer()) { 6954 // Look through initializers like const char c[] = { "foo" } 6955 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6956 if (InitList->isStringLiteralInit()) 6957 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6958 } 6959 return checkFormatStringExpr(S, Init, Args, 6960 HasVAListArg, format_idx, 6961 firstDataArg, Type, CallType, 6962 /*InFunctionCall*/ false, CheckedVarArgs, 6963 UncoveredArg, Offset); 6964 } 6965 } 6966 6967 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6968 // special check to see if the format string is a function parameter 6969 // of the function calling the printf function. If the function 6970 // has an attribute indicating it is a printf-like function, then we 6971 // should suppress warnings concerning non-literals being used in a call 6972 // to a vprintf function. For example: 6973 // 6974 // void 6975 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6976 // va_list ap; 6977 // va_start(ap, fmt); 6978 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6979 // ... 6980 // } 6981 if (HasVAListArg) { 6982 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6983 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6984 int PVIndex = PV->getFunctionScopeIndex() + 1; 6985 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6986 // adjust for implicit parameter 6987 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6988 if (MD->isInstance()) 6989 ++PVIndex; 6990 // We also check if the formats are compatible. 6991 // We can't pass a 'scanf' string to a 'printf' function. 6992 if (PVIndex == PVFormat->getFormatIdx() && 6993 Type == S.GetFormatStringType(PVFormat)) 6994 return SLCT_UncheckedLiteral; 6995 } 6996 } 6997 } 6998 } 6999 } 7000 7001 return SLCT_NotALiteral; 7002 } 7003 7004 case Stmt::CallExprClass: 7005 case Stmt::CXXMemberCallExprClass: { 7006 const CallExpr *CE = cast<CallExpr>(E); 7007 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 7008 bool IsFirst = true; 7009 StringLiteralCheckType CommonResult; 7010 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 7011 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 7012 StringLiteralCheckType Result = checkFormatStringExpr( 7013 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7014 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7015 IgnoreStringsWithoutSpecifiers); 7016 if (IsFirst) { 7017 CommonResult = Result; 7018 IsFirst = false; 7019 } 7020 } 7021 if (!IsFirst) 7022 return CommonResult; 7023 7024 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 7025 unsigned BuiltinID = FD->getBuiltinID(); 7026 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 7027 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 7028 const Expr *Arg = CE->getArg(0); 7029 return checkFormatStringExpr(S, Arg, Args, 7030 HasVAListArg, format_idx, 7031 firstDataArg, Type, CallType, 7032 InFunctionCall, CheckedVarArgs, 7033 UncoveredArg, Offset, 7034 IgnoreStringsWithoutSpecifiers); 7035 } 7036 } 7037 } 7038 7039 return SLCT_NotALiteral; 7040 } 7041 case Stmt::ObjCMessageExprClass: { 7042 const auto *ME = cast<ObjCMessageExpr>(E); 7043 if (const auto *MD = ME->getMethodDecl()) { 7044 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 7045 // As a special case heuristic, if we're using the method -[NSBundle 7046 // localizedStringForKey:value:table:], ignore any key strings that lack 7047 // format specifiers. The idea is that if the key doesn't have any 7048 // format specifiers then its probably just a key to map to the 7049 // localized strings. If it does have format specifiers though, then its 7050 // likely that the text of the key is the format string in the 7051 // programmer's language, and should be checked. 7052 const ObjCInterfaceDecl *IFace; 7053 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 7054 IFace->getIdentifier()->isStr("NSBundle") && 7055 MD->getSelector().isKeywordSelector( 7056 {"localizedStringForKey", "value", "table"})) { 7057 IgnoreStringsWithoutSpecifiers = true; 7058 } 7059 7060 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 7061 return checkFormatStringExpr( 7062 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 7063 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 7064 IgnoreStringsWithoutSpecifiers); 7065 } 7066 } 7067 7068 return SLCT_NotALiteral; 7069 } 7070 case Stmt::ObjCStringLiteralClass: 7071 case Stmt::StringLiteralClass: { 7072 const StringLiteral *StrE = nullptr; 7073 7074 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 7075 StrE = ObjCFExpr->getString(); 7076 else 7077 StrE = cast<StringLiteral>(E); 7078 7079 if (StrE) { 7080 if (Offset.isNegative() || Offset > StrE->getLength()) { 7081 // TODO: It would be better to have an explicit warning for out of 7082 // bounds literals. 7083 return SLCT_NotALiteral; 7084 } 7085 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 7086 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 7087 firstDataArg, Type, InFunctionCall, CallType, 7088 CheckedVarArgs, UncoveredArg, 7089 IgnoreStringsWithoutSpecifiers); 7090 return SLCT_CheckedLiteral; 7091 } 7092 7093 return SLCT_NotALiteral; 7094 } 7095 case Stmt::BinaryOperatorClass: { 7096 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 7097 7098 // A string literal + an int offset is still a string literal. 7099 if (BinOp->isAdditiveOp()) { 7100 Expr::EvalResult LResult, RResult; 7101 7102 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 7103 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7104 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 7105 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 7106 7107 if (LIsInt != RIsInt) { 7108 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 7109 7110 if (LIsInt) { 7111 if (BinOpKind == BO_Add) { 7112 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 7113 E = BinOp->getRHS(); 7114 goto tryAgain; 7115 } 7116 } else { 7117 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 7118 E = BinOp->getLHS(); 7119 goto tryAgain; 7120 } 7121 } 7122 } 7123 7124 return SLCT_NotALiteral; 7125 } 7126 case Stmt::UnaryOperatorClass: { 7127 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 7128 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 7129 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 7130 Expr::EvalResult IndexResult; 7131 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 7132 Expr::SE_NoSideEffects, 7133 S.isConstantEvaluated())) { 7134 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 7135 /*RHS is int*/ true); 7136 E = ASE->getBase(); 7137 goto tryAgain; 7138 } 7139 } 7140 7141 return SLCT_NotALiteral; 7142 } 7143 7144 default: 7145 return SLCT_NotALiteral; 7146 } 7147 } 7148 7149 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 7150 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 7151 .Case("scanf", FST_Scanf) 7152 .Cases("printf", "printf0", FST_Printf) 7153 .Cases("NSString", "CFString", FST_NSString) 7154 .Case("strftime", FST_Strftime) 7155 .Case("strfmon", FST_Strfmon) 7156 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 7157 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 7158 .Case("os_trace", FST_OSLog) 7159 .Case("os_log", FST_OSLog) 7160 .Default(FST_Unknown); 7161 } 7162 7163 /// CheckFormatArguments - Check calls to printf and scanf (and similar 7164 /// functions) for correct use of format strings. 7165 /// Returns true if a format string has been fully checked. 7166 bool Sema::CheckFormatArguments(const FormatAttr *Format, 7167 ArrayRef<const Expr *> Args, 7168 bool IsCXXMember, 7169 VariadicCallType CallType, 7170 SourceLocation Loc, SourceRange Range, 7171 llvm::SmallBitVector &CheckedVarArgs) { 7172 FormatStringInfo FSI; 7173 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 7174 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 7175 FSI.FirstDataArg, GetFormatStringType(Format), 7176 CallType, Loc, Range, CheckedVarArgs); 7177 return false; 7178 } 7179 7180 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 7181 bool HasVAListArg, unsigned format_idx, 7182 unsigned firstDataArg, FormatStringType Type, 7183 VariadicCallType CallType, 7184 SourceLocation Loc, SourceRange Range, 7185 llvm::SmallBitVector &CheckedVarArgs) { 7186 // CHECK: printf/scanf-like function is called with no format string. 7187 if (format_idx >= Args.size()) { 7188 Diag(Loc, diag::warn_missing_format_string) << Range; 7189 return false; 7190 } 7191 7192 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7193 7194 // CHECK: format string is not a string literal. 7195 // 7196 // Dynamically generated format strings are difficult to 7197 // automatically vet at compile time. Requiring that format strings 7198 // are string literals: (1) permits the checking of format strings by 7199 // the compiler and thereby (2) can practically remove the source of 7200 // many format string exploits. 7201 7202 // Format string can be either ObjC string (e.g. @"%d") or 7203 // C string (e.g. "%d") 7204 // ObjC string uses the same format specifiers as C string, so we can use 7205 // the same format string checking logic for both ObjC and C strings. 7206 UncoveredArgHandler UncoveredArg; 7207 StringLiteralCheckType CT = 7208 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7209 format_idx, firstDataArg, Type, CallType, 7210 /*IsFunctionCall*/ true, CheckedVarArgs, 7211 UncoveredArg, 7212 /*no string offset*/ llvm::APSInt(64, false) = 0); 7213 7214 // Generate a diagnostic where an uncovered argument is detected. 7215 if (UncoveredArg.hasUncoveredArg()) { 7216 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7217 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7218 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7219 } 7220 7221 if (CT != SLCT_NotALiteral) 7222 // Literal format string found, check done! 7223 return CT == SLCT_CheckedLiteral; 7224 7225 // Strftime is particular as it always uses a single 'time' argument, 7226 // so it is safe to pass a non-literal string. 7227 if (Type == FST_Strftime) 7228 return false; 7229 7230 // Do not emit diag when the string param is a macro expansion and the 7231 // format is either NSString or CFString. This is a hack to prevent 7232 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7233 // which are usually used in place of NS and CF string literals. 7234 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7235 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7236 return false; 7237 7238 // If there are no arguments specified, warn with -Wformat-security, otherwise 7239 // warn only with -Wformat-nonliteral. 7240 if (Args.size() == firstDataArg) { 7241 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7242 << OrigFormatExpr->getSourceRange(); 7243 switch (Type) { 7244 default: 7245 break; 7246 case FST_Kprintf: 7247 case FST_FreeBSDKPrintf: 7248 case FST_Printf: 7249 Diag(FormatLoc, diag::note_format_security_fixit) 7250 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7251 break; 7252 case FST_NSString: 7253 Diag(FormatLoc, diag::note_format_security_fixit) 7254 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7255 break; 7256 } 7257 } else { 7258 Diag(FormatLoc, diag::warn_format_nonliteral) 7259 << OrigFormatExpr->getSourceRange(); 7260 } 7261 return false; 7262 } 7263 7264 namespace { 7265 7266 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7267 protected: 7268 Sema &S; 7269 const FormatStringLiteral *FExpr; 7270 const Expr *OrigFormatExpr; 7271 const Sema::FormatStringType FSType; 7272 const unsigned FirstDataArg; 7273 const unsigned NumDataArgs; 7274 const char *Beg; // Start of format string. 7275 const bool HasVAListArg; 7276 ArrayRef<const Expr *> Args; 7277 unsigned FormatIdx; 7278 llvm::SmallBitVector CoveredArgs; 7279 bool usesPositionalArgs = false; 7280 bool atFirstArg = true; 7281 bool inFunctionCall; 7282 Sema::VariadicCallType CallType; 7283 llvm::SmallBitVector &CheckedVarArgs; 7284 UncoveredArgHandler &UncoveredArg; 7285 7286 public: 7287 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7288 const Expr *origFormatExpr, 7289 const Sema::FormatStringType type, unsigned firstDataArg, 7290 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7291 ArrayRef<const Expr *> Args, unsigned formatIdx, 7292 bool inFunctionCall, Sema::VariadicCallType callType, 7293 llvm::SmallBitVector &CheckedVarArgs, 7294 UncoveredArgHandler &UncoveredArg) 7295 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7296 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7297 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7298 inFunctionCall(inFunctionCall), CallType(callType), 7299 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7300 CoveredArgs.resize(numDataArgs); 7301 CoveredArgs.reset(); 7302 } 7303 7304 void DoneProcessing(); 7305 7306 void HandleIncompleteSpecifier(const char *startSpecifier, 7307 unsigned specifierLen) override; 7308 7309 void HandleInvalidLengthModifier( 7310 const analyze_format_string::FormatSpecifier &FS, 7311 const analyze_format_string::ConversionSpecifier &CS, 7312 const char *startSpecifier, unsigned specifierLen, 7313 unsigned DiagID); 7314 7315 void HandleNonStandardLengthModifier( 7316 const analyze_format_string::FormatSpecifier &FS, 7317 const char *startSpecifier, unsigned specifierLen); 7318 7319 void HandleNonStandardConversionSpecifier( 7320 const analyze_format_string::ConversionSpecifier &CS, 7321 const char *startSpecifier, unsigned specifierLen); 7322 7323 void HandlePosition(const char *startPos, unsigned posLen) override; 7324 7325 void HandleInvalidPosition(const char *startSpecifier, 7326 unsigned specifierLen, 7327 analyze_format_string::PositionContext p) override; 7328 7329 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7330 7331 void HandleNullChar(const char *nullCharacter) override; 7332 7333 template <typename Range> 7334 static void 7335 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7336 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7337 bool IsStringLocation, Range StringRange, 7338 ArrayRef<FixItHint> Fixit = None); 7339 7340 protected: 7341 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7342 const char *startSpec, 7343 unsigned specifierLen, 7344 const char *csStart, unsigned csLen); 7345 7346 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7347 const char *startSpec, 7348 unsigned specifierLen); 7349 7350 SourceRange getFormatStringRange(); 7351 CharSourceRange getSpecifierRange(const char *startSpecifier, 7352 unsigned specifierLen); 7353 SourceLocation getLocationOfByte(const char *x); 7354 7355 const Expr *getDataArg(unsigned i) const; 7356 7357 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7358 const analyze_format_string::ConversionSpecifier &CS, 7359 const char *startSpecifier, unsigned specifierLen, 7360 unsigned argIndex); 7361 7362 template <typename Range> 7363 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7364 bool IsStringLocation, Range StringRange, 7365 ArrayRef<FixItHint> Fixit = None); 7366 }; 7367 7368 } // namespace 7369 7370 SourceRange CheckFormatHandler::getFormatStringRange() { 7371 return OrigFormatExpr->getSourceRange(); 7372 } 7373 7374 CharSourceRange CheckFormatHandler:: 7375 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7376 SourceLocation Start = getLocationOfByte(startSpecifier); 7377 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7378 7379 // Advance the end SourceLocation by one due to half-open ranges. 7380 End = End.getLocWithOffset(1); 7381 7382 return CharSourceRange::getCharRange(Start, End); 7383 } 7384 7385 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7386 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7387 S.getLangOpts(), S.Context.getTargetInfo()); 7388 } 7389 7390 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7391 unsigned specifierLen){ 7392 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7393 getLocationOfByte(startSpecifier), 7394 /*IsStringLocation*/true, 7395 getSpecifierRange(startSpecifier, specifierLen)); 7396 } 7397 7398 void CheckFormatHandler::HandleInvalidLengthModifier( 7399 const analyze_format_string::FormatSpecifier &FS, 7400 const analyze_format_string::ConversionSpecifier &CS, 7401 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7402 using namespace analyze_format_string; 7403 7404 const LengthModifier &LM = FS.getLengthModifier(); 7405 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7406 7407 // See if we know how to fix this length modifier. 7408 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7409 if (FixedLM) { 7410 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7411 getLocationOfByte(LM.getStart()), 7412 /*IsStringLocation*/true, 7413 getSpecifierRange(startSpecifier, specifierLen)); 7414 7415 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7416 << FixedLM->toString() 7417 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7418 7419 } else { 7420 FixItHint Hint; 7421 if (DiagID == diag::warn_format_nonsensical_length) 7422 Hint = FixItHint::CreateRemoval(LMRange); 7423 7424 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7425 getLocationOfByte(LM.getStart()), 7426 /*IsStringLocation*/true, 7427 getSpecifierRange(startSpecifier, specifierLen), 7428 Hint); 7429 } 7430 } 7431 7432 void CheckFormatHandler::HandleNonStandardLengthModifier( 7433 const analyze_format_string::FormatSpecifier &FS, 7434 const char *startSpecifier, unsigned specifierLen) { 7435 using namespace analyze_format_string; 7436 7437 const LengthModifier &LM = FS.getLengthModifier(); 7438 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7439 7440 // See if we know how to fix this length modifier. 7441 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7442 if (FixedLM) { 7443 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7444 << LM.toString() << 0, 7445 getLocationOfByte(LM.getStart()), 7446 /*IsStringLocation*/true, 7447 getSpecifierRange(startSpecifier, specifierLen)); 7448 7449 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7450 << FixedLM->toString() 7451 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7452 7453 } else { 7454 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7455 << LM.toString() << 0, 7456 getLocationOfByte(LM.getStart()), 7457 /*IsStringLocation*/true, 7458 getSpecifierRange(startSpecifier, specifierLen)); 7459 } 7460 } 7461 7462 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7463 const analyze_format_string::ConversionSpecifier &CS, 7464 const char *startSpecifier, unsigned specifierLen) { 7465 using namespace analyze_format_string; 7466 7467 // See if we know how to fix this conversion specifier. 7468 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7469 if (FixedCS) { 7470 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7471 << CS.toString() << /*conversion specifier*/1, 7472 getLocationOfByte(CS.getStart()), 7473 /*IsStringLocation*/true, 7474 getSpecifierRange(startSpecifier, specifierLen)); 7475 7476 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7477 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7478 << FixedCS->toString() 7479 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7480 } else { 7481 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7482 << CS.toString() << /*conversion specifier*/1, 7483 getLocationOfByte(CS.getStart()), 7484 /*IsStringLocation*/true, 7485 getSpecifierRange(startSpecifier, specifierLen)); 7486 } 7487 } 7488 7489 void CheckFormatHandler::HandlePosition(const char *startPos, 7490 unsigned posLen) { 7491 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7492 getLocationOfByte(startPos), 7493 /*IsStringLocation*/true, 7494 getSpecifierRange(startPos, posLen)); 7495 } 7496 7497 void 7498 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7499 analyze_format_string::PositionContext p) { 7500 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7501 << (unsigned) p, 7502 getLocationOfByte(startPos), /*IsStringLocation*/true, 7503 getSpecifierRange(startPos, posLen)); 7504 } 7505 7506 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7507 unsigned posLen) { 7508 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7509 getLocationOfByte(startPos), 7510 /*IsStringLocation*/true, 7511 getSpecifierRange(startPos, posLen)); 7512 } 7513 7514 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7515 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7516 // The presence of a null character is likely an error. 7517 EmitFormatDiagnostic( 7518 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7519 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7520 getFormatStringRange()); 7521 } 7522 } 7523 7524 // Note that this may return NULL if there was an error parsing or building 7525 // one of the argument expressions. 7526 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7527 return Args[FirstDataArg + i]; 7528 } 7529 7530 void CheckFormatHandler::DoneProcessing() { 7531 // Does the number of data arguments exceed the number of 7532 // format conversions in the format string? 7533 if (!HasVAListArg) { 7534 // Find any arguments that weren't covered. 7535 CoveredArgs.flip(); 7536 signed notCoveredArg = CoveredArgs.find_first(); 7537 if (notCoveredArg >= 0) { 7538 assert((unsigned)notCoveredArg < NumDataArgs); 7539 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7540 } else { 7541 UncoveredArg.setAllCovered(); 7542 } 7543 } 7544 } 7545 7546 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7547 const Expr *ArgExpr) { 7548 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7549 "Invalid state"); 7550 7551 if (!ArgExpr) 7552 return; 7553 7554 SourceLocation Loc = ArgExpr->getBeginLoc(); 7555 7556 if (S.getSourceManager().isInSystemMacro(Loc)) 7557 return; 7558 7559 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7560 for (auto E : DiagnosticExprs) 7561 PDiag << E->getSourceRange(); 7562 7563 CheckFormatHandler::EmitFormatDiagnostic( 7564 S, IsFunctionCall, DiagnosticExprs[0], 7565 PDiag, Loc, /*IsStringLocation*/false, 7566 DiagnosticExprs[0]->getSourceRange()); 7567 } 7568 7569 bool 7570 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7571 SourceLocation Loc, 7572 const char *startSpec, 7573 unsigned specifierLen, 7574 const char *csStart, 7575 unsigned csLen) { 7576 bool keepGoing = true; 7577 if (argIndex < NumDataArgs) { 7578 // Consider the argument coverered, even though the specifier doesn't 7579 // make sense. 7580 CoveredArgs.set(argIndex); 7581 } 7582 else { 7583 // If argIndex exceeds the number of data arguments we 7584 // don't issue a warning because that is just a cascade of warnings (and 7585 // they may have intended '%%' anyway). We don't want to continue processing 7586 // the format string after this point, however, as we will like just get 7587 // gibberish when trying to match arguments. 7588 keepGoing = false; 7589 } 7590 7591 StringRef Specifier(csStart, csLen); 7592 7593 // If the specifier in non-printable, it could be the first byte of a UTF-8 7594 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7595 // hex value. 7596 std::string CodePointStr; 7597 if (!llvm::sys::locale::isPrint(*csStart)) { 7598 llvm::UTF32 CodePoint; 7599 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7600 const llvm::UTF8 *E = 7601 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7602 llvm::ConversionResult Result = 7603 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7604 7605 if (Result != llvm::conversionOK) { 7606 unsigned char FirstChar = *csStart; 7607 CodePoint = (llvm::UTF32)FirstChar; 7608 } 7609 7610 llvm::raw_string_ostream OS(CodePointStr); 7611 if (CodePoint < 256) 7612 OS << "\\x" << llvm::format("%02x", CodePoint); 7613 else if (CodePoint <= 0xFFFF) 7614 OS << "\\u" << llvm::format("%04x", CodePoint); 7615 else 7616 OS << "\\U" << llvm::format("%08x", CodePoint); 7617 OS.flush(); 7618 Specifier = CodePointStr; 7619 } 7620 7621 EmitFormatDiagnostic( 7622 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7623 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7624 7625 return keepGoing; 7626 } 7627 7628 void 7629 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7630 const char *startSpec, 7631 unsigned specifierLen) { 7632 EmitFormatDiagnostic( 7633 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7634 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7635 } 7636 7637 bool 7638 CheckFormatHandler::CheckNumArgs( 7639 const analyze_format_string::FormatSpecifier &FS, 7640 const analyze_format_string::ConversionSpecifier &CS, 7641 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7642 7643 if (argIndex >= NumDataArgs) { 7644 PartialDiagnostic PDiag = FS.usesPositionalArg() 7645 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7646 << (argIndex+1) << NumDataArgs) 7647 : S.PDiag(diag::warn_printf_insufficient_data_args); 7648 EmitFormatDiagnostic( 7649 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7650 getSpecifierRange(startSpecifier, specifierLen)); 7651 7652 // Since more arguments than conversion tokens are given, by extension 7653 // all arguments are covered, so mark this as so. 7654 UncoveredArg.setAllCovered(); 7655 return false; 7656 } 7657 return true; 7658 } 7659 7660 template<typename Range> 7661 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7662 SourceLocation Loc, 7663 bool IsStringLocation, 7664 Range StringRange, 7665 ArrayRef<FixItHint> FixIt) { 7666 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7667 Loc, IsStringLocation, StringRange, FixIt); 7668 } 7669 7670 /// If the format string is not within the function call, emit a note 7671 /// so that the function call and string are in diagnostic messages. 7672 /// 7673 /// \param InFunctionCall if true, the format string is within the function 7674 /// call and only one diagnostic message will be produced. Otherwise, an 7675 /// extra note will be emitted pointing to location of the format string. 7676 /// 7677 /// \param ArgumentExpr the expression that is passed as the format string 7678 /// argument in the function call. Used for getting locations when two 7679 /// diagnostics are emitted. 7680 /// 7681 /// \param PDiag the callee should already have provided any strings for the 7682 /// diagnostic message. This function only adds locations and fixits 7683 /// to diagnostics. 7684 /// 7685 /// \param Loc primary location for diagnostic. If two diagnostics are 7686 /// required, one will be at Loc and a new SourceLocation will be created for 7687 /// the other one. 7688 /// 7689 /// \param IsStringLocation if true, Loc points to the format string should be 7690 /// used for the note. Otherwise, Loc points to the argument list and will 7691 /// be used with PDiag. 7692 /// 7693 /// \param StringRange some or all of the string to highlight. This is 7694 /// templated so it can accept either a CharSourceRange or a SourceRange. 7695 /// 7696 /// \param FixIt optional fix it hint for the format string. 7697 template <typename Range> 7698 void CheckFormatHandler::EmitFormatDiagnostic( 7699 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7700 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7701 Range StringRange, ArrayRef<FixItHint> FixIt) { 7702 if (InFunctionCall) { 7703 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7704 D << StringRange; 7705 D << FixIt; 7706 } else { 7707 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7708 << ArgumentExpr->getSourceRange(); 7709 7710 const Sema::SemaDiagnosticBuilder &Note = 7711 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7712 diag::note_format_string_defined); 7713 7714 Note << StringRange; 7715 Note << FixIt; 7716 } 7717 } 7718 7719 //===--- CHECK: Printf format string checking ------------------------------===// 7720 7721 namespace { 7722 7723 class CheckPrintfHandler : public CheckFormatHandler { 7724 public: 7725 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7726 const Expr *origFormatExpr, 7727 const Sema::FormatStringType type, unsigned firstDataArg, 7728 unsigned numDataArgs, bool isObjC, const char *beg, 7729 bool hasVAListArg, ArrayRef<const Expr *> Args, 7730 unsigned formatIdx, bool inFunctionCall, 7731 Sema::VariadicCallType CallType, 7732 llvm::SmallBitVector &CheckedVarArgs, 7733 UncoveredArgHandler &UncoveredArg) 7734 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7735 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7736 inFunctionCall, CallType, CheckedVarArgs, 7737 UncoveredArg) {} 7738 7739 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7740 7741 /// Returns true if '%@' specifiers are allowed in the format string. 7742 bool allowsObjCArg() const { 7743 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7744 FSType == Sema::FST_OSTrace; 7745 } 7746 7747 bool HandleInvalidPrintfConversionSpecifier( 7748 const analyze_printf::PrintfSpecifier &FS, 7749 const char *startSpecifier, 7750 unsigned specifierLen) override; 7751 7752 void handleInvalidMaskType(StringRef MaskType) override; 7753 7754 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7755 const char *startSpecifier, 7756 unsigned specifierLen) override; 7757 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7758 const char *StartSpecifier, 7759 unsigned SpecifierLen, 7760 const Expr *E); 7761 7762 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7763 const char *startSpecifier, unsigned specifierLen); 7764 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7765 const analyze_printf::OptionalAmount &Amt, 7766 unsigned type, 7767 const char *startSpecifier, unsigned specifierLen); 7768 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7769 const analyze_printf::OptionalFlag &flag, 7770 const char *startSpecifier, unsigned specifierLen); 7771 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7772 const analyze_printf::OptionalFlag &ignoredFlag, 7773 const analyze_printf::OptionalFlag &flag, 7774 const char *startSpecifier, unsigned specifierLen); 7775 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7776 const Expr *E); 7777 7778 void HandleEmptyObjCModifierFlag(const char *startFlag, 7779 unsigned flagLen) override; 7780 7781 void HandleInvalidObjCModifierFlag(const char *startFlag, 7782 unsigned flagLen) override; 7783 7784 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7785 const char *flagsEnd, 7786 const char *conversionPosition) 7787 override; 7788 }; 7789 7790 } // namespace 7791 7792 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7793 const analyze_printf::PrintfSpecifier &FS, 7794 const char *startSpecifier, 7795 unsigned specifierLen) { 7796 const analyze_printf::PrintfConversionSpecifier &CS = 7797 FS.getConversionSpecifier(); 7798 7799 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7800 getLocationOfByte(CS.getStart()), 7801 startSpecifier, specifierLen, 7802 CS.getStart(), CS.getLength()); 7803 } 7804 7805 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7806 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7807 } 7808 7809 bool CheckPrintfHandler::HandleAmount( 7810 const analyze_format_string::OptionalAmount &Amt, 7811 unsigned k, const char *startSpecifier, 7812 unsigned specifierLen) { 7813 if (Amt.hasDataArgument()) { 7814 if (!HasVAListArg) { 7815 unsigned argIndex = Amt.getArgIndex(); 7816 if (argIndex >= NumDataArgs) { 7817 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7818 << k, 7819 getLocationOfByte(Amt.getStart()), 7820 /*IsStringLocation*/true, 7821 getSpecifierRange(startSpecifier, specifierLen)); 7822 // Don't do any more checking. We will just emit 7823 // spurious errors. 7824 return false; 7825 } 7826 7827 // Type check the data argument. It should be an 'int'. 7828 // Although not in conformance with C99, we also allow the argument to be 7829 // an 'unsigned int' as that is a reasonably safe case. GCC also 7830 // doesn't emit a warning for that case. 7831 CoveredArgs.set(argIndex); 7832 const Expr *Arg = getDataArg(argIndex); 7833 if (!Arg) 7834 return false; 7835 7836 QualType T = Arg->getType(); 7837 7838 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7839 assert(AT.isValid()); 7840 7841 if (!AT.matchesType(S.Context, T)) { 7842 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7843 << k << AT.getRepresentativeTypeName(S.Context) 7844 << T << Arg->getSourceRange(), 7845 getLocationOfByte(Amt.getStart()), 7846 /*IsStringLocation*/true, 7847 getSpecifierRange(startSpecifier, specifierLen)); 7848 // Don't do any more checking. We will just emit 7849 // spurious errors. 7850 return false; 7851 } 7852 } 7853 } 7854 return true; 7855 } 7856 7857 void CheckPrintfHandler::HandleInvalidAmount( 7858 const analyze_printf::PrintfSpecifier &FS, 7859 const analyze_printf::OptionalAmount &Amt, 7860 unsigned type, 7861 const char *startSpecifier, 7862 unsigned specifierLen) { 7863 const analyze_printf::PrintfConversionSpecifier &CS = 7864 FS.getConversionSpecifier(); 7865 7866 FixItHint fixit = 7867 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7868 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7869 Amt.getConstantLength())) 7870 : FixItHint(); 7871 7872 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7873 << type << CS.toString(), 7874 getLocationOfByte(Amt.getStart()), 7875 /*IsStringLocation*/true, 7876 getSpecifierRange(startSpecifier, specifierLen), 7877 fixit); 7878 } 7879 7880 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7881 const analyze_printf::OptionalFlag &flag, 7882 const char *startSpecifier, 7883 unsigned specifierLen) { 7884 // Warn about pointless flag with a fixit removal. 7885 const analyze_printf::PrintfConversionSpecifier &CS = 7886 FS.getConversionSpecifier(); 7887 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7888 << flag.toString() << CS.toString(), 7889 getLocationOfByte(flag.getPosition()), 7890 /*IsStringLocation*/true, 7891 getSpecifierRange(startSpecifier, specifierLen), 7892 FixItHint::CreateRemoval( 7893 getSpecifierRange(flag.getPosition(), 1))); 7894 } 7895 7896 void CheckPrintfHandler::HandleIgnoredFlag( 7897 const analyze_printf::PrintfSpecifier &FS, 7898 const analyze_printf::OptionalFlag &ignoredFlag, 7899 const analyze_printf::OptionalFlag &flag, 7900 const char *startSpecifier, 7901 unsigned specifierLen) { 7902 // Warn about ignored flag with a fixit removal. 7903 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7904 << ignoredFlag.toString() << flag.toString(), 7905 getLocationOfByte(ignoredFlag.getPosition()), 7906 /*IsStringLocation*/true, 7907 getSpecifierRange(startSpecifier, specifierLen), 7908 FixItHint::CreateRemoval( 7909 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7910 } 7911 7912 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7913 unsigned flagLen) { 7914 // Warn about an empty flag. 7915 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7916 getLocationOfByte(startFlag), 7917 /*IsStringLocation*/true, 7918 getSpecifierRange(startFlag, flagLen)); 7919 } 7920 7921 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7922 unsigned flagLen) { 7923 // Warn about an invalid flag. 7924 auto Range = getSpecifierRange(startFlag, flagLen); 7925 StringRef flag(startFlag, flagLen); 7926 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7927 getLocationOfByte(startFlag), 7928 /*IsStringLocation*/true, 7929 Range, FixItHint::CreateRemoval(Range)); 7930 } 7931 7932 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7933 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7934 // Warn about using '[...]' without a '@' conversion. 7935 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7936 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7937 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7938 getLocationOfByte(conversionPosition), 7939 /*IsStringLocation*/true, 7940 Range, FixItHint::CreateRemoval(Range)); 7941 } 7942 7943 // Determines if the specified is a C++ class or struct containing 7944 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7945 // "c_str()"). 7946 template<typename MemberKind> 7947 static llvm::SmallPtrSet<MemberKind*, 1> 7948 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7949 const RecordType *RT = Ty->getAs<RecordType>(); 7950 llvm::SmallPtrSet<MemberKind*, 1> Results; 7951 7952 if (!RT) 7953 return Results; 7954 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7955 if (!RD || !RD->getDefinition()) 7956 return Results; 7957 7958 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7959 Sema::LookupMemberName); 7960 R.suppressDiagnostics(); 7961 7962 // We just need to include all members of the right kind turned up by the 7963 // filter, at this point. 7964 if (S.LookupQualifiedName(R, RT->getDecl())) 7965 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7966 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7967 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7968 Results.insert(FK); 7969 } 7970 return Results; 7971 } 7972 7973 /// Check if we could call '.c_str()' on an object. 7974 /// 7975 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7976 /// allow the call, or if it would be ambiguous). 7977 bool Sema::hasCStrMethod(const Expr *E) { 7978 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7979 7980 MethodSet Results = 7981 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7982 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7983 MI != ME; ++MI) 7984 if ((*MI)->getMinRequiredArguments() == 0) 7985 return true; 7986 return false; 7987 } 7988 7989 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7990 // better diagnostic if so. AT is assumed to be valid. 7991 // Returns true when a c_str() conversion method is found. 7992 bool CheckPrintfHandler::checkForCStrMembers( 7993 const analyze_printf::ArgType &AT, const Expr *E) { 7994 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7995 7996 MethodSet Results = 7997 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7998 7999 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 8000 MI != ME; ++MI) { 8001 const CXXMethodDecl *Method = *MI; 8002 if (Method->getMinRequiredArguments() == 0 && 8003 AT.matchesType(S.Context, Method->getReturnType())) { 8004 // FIXME: Suggest parens if the expression needs them. 8005 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 8006 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 8007 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 8008 return true; 8009 } 8010 } 8011 8012 return false; 8013 } 8014 8015 bool 8016 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 8017 &FS, 8018 const char *startSpecifier, 8019 unsigned specifierLen) { 8020 using namespace analyze_format_string; 8021 using namespace analyze_printf; 8022 8023 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 8024 8025 if (FS.consumesDataArgument()) { 8026 if (atFirstArg) { 8027 atFirstArg = false; 8028 usesPositionalArgs = FS.usesPositionalArg(); 8029 } 8030 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8031 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8032 startSpecifier, specifierLen); 8033 return false; 8034 } 8035 } 8036 8037 // First check if the field width, precision, and conversion specifier 8038 // have matching data arguments. 8039 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 8040 startSpecifier, specifierLen)) { 8041 return false; 8042 } 8043 8044 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 8045 startSpecifier, specifierLen)) { 8046 return false; 8047 } 8048 8049 if (!CS.consumesDataArgument()) { 8050 // FIXME: Technically specifying a precision or field width here 8051 // makes no sense. Worth issuing a warning at some point. 8052 return true; 8053 } 8054 8055 // Consume the argument. 8056 unsigned argIndex = FS.getArgIndex(); 8057 if (argIndex < NumDataArgs) { 8058 // The check to see if the argIndex is valid will come later. 8059 // We set the bit here because we may exit early from this 8060 // function if we encounter some other error. 8061 CoveredArgs.set(argIndex); 8062 } 8063 8064 // FreeBSD kernel extensions. 8065 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 8066 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 8067 // We need at least two arguments. 8068 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 8069 return false; 8070 8071 // Claim the second argument. 8072 CoveredArgs.set(argIndex + 1); 8073 8074 // Type check the first argument (int for %b, pointer for %D) 8075 const Expr *Ex = getDataArg(argIndex); 8076 const analyze_printf::ArgType &AT = 8077 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 8078 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 8079 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 8080 EmitFormatDiagnostic( 8081 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8082 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 8083 << false << Ex->getSourceRange(), 8084 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8085 getSpecifierRange(startSpecifier, specifierLen)); 8086 8087 // Type check the second argument (char * for both %b and %D) 8088 Ex = getDataArg(argIndex + 1); 8089 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 8090 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 8091 EmitFormatDiagnostic( 8092 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8093 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 8094 << false << Ex->getSourceRange(), 8095 Ex->getBeginLoc(), /*IsStringLocation*/ false, 8096 getSpecifierRange(startSpecifier, specifierLen)); 8097 8098 return true; 8099 } 8100 8101 // Check for using an Objective-C specific conversion specifier 8102 // in a non-ObjC literal. 8103 if (!allowsObjCArg() && CS.isObjCArg()) { 8104 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8105 specifierLen); 8106 } 8107 8108 // %P can only be used with os_log. 8109 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 8110 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8111 specifierLen); 8112 } 8113 8114 // %n is not allowed with os_log. 8115 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 8116 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 8117 getLocationOfByte(CS.getStart()), 8118 /*IsStringLocation*/ false, 8119 getSpecifierRange(startSpecifier, specifierLen)); 8120 8121 return true; 8122 } 8123 8124 // Only scalars are allowed for os_trace. 8125 if (FSType == Sema::FST_OSTrace && 8126 (CS.getKind() == ConversionSpecifier::PArg || 8127 CS.getKind() == ConversionSpecifier::sArg || 8128 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 8129 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 8130 specifierLen); 8131 } 8132 8133 // Check for use of public/private annotation outside of os_log(). 8134 if (FSType != Sema::FST_OSLog) { 8135 if (FS.isPublic().isSet()) { 8136 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8137 << "public", 8138 getLocationOfByte(FS.isPublic().getPosition()), 8139 /*IsStringLocation*/ false, 8140 getSpecifierRange(startSpecifier, specifierLen)); 8141 } 8142 if (FS.isPrivate().isSet()) { 8143 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 8144 << "private", 8145 getLocationOfByte(FS.isPrivate().getPosition()), 8146 /*IsStringLocation*/ false, 8147 getSpecifierRange(startSpecifier, specifierLen)); 8148 } 8149 } 8150 8151 // Check for invalid use of field width 8152 if (!FS.hasValidFieldWidth()) { 8153 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 8154 startSpecifier, specifierLen); 8155 } 8156 8157 // Check for invalid use of precision 8158 if (!FS.hasValidPrecision()) { 8159 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 8160 startSpecifier, specifierLen); 8161 } 8162 8163 // Precision is mandatory for %P specifier. 8164 if (CS.getKind() == ConversionSpecifier::PArg && 8165 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 8166 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 8167 getLocationOfByte(startSpecifier), 8168 /*IsStringLocation*/ false, 8169 getSpecifierRange(startSpecifier, specifierLen)); 8170 } 8171 8172 // Check each flag does not conflict with any other component. 8173 if (!FS.hasValidThousandsGroupingPrefix()) 8174 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 8175 if (!FS.hasValidLeadingZeros()) 8176 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 8177 if (!FS.hasValidPlusPrefix()) 8178 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 8179 if (!FS.hasValidSpacePrefix()) 8180 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 8181 if (!FS.hasValidAlternativeForm()) 8182 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 8183 if (!FS.hasValidLeftJustified()) 8184 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8185 8186 // Check that flags are not ignored by another flag 8187 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8188 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8189 startSpecifier, specifierLen); 8190 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8191 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8192 startSpecifier, specifierLen); 8193 8194 // Check the length modifier is valid with the given conversion specifier. 8195 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8196 S.getLangOpts())) 8197 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8198 diag::warn_format_nonsensical_length); 8199 else if (!FS.hasStandardLengthModifier()) 8200 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8201 else if (!FS.hasStandardLengthConversionCombination()) 8202 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8203 diag::warn_format_non_standard_conversion_spec); 8204 8205 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8206 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8207 8208 // The remaining checks depend on the data arguments. 8209 if (HasVAListArg) 8210 return true; 8211 8212 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8213 return false; 8214 8215 const Expr *Arg = getDataArg(argIndex); 8216 if (!Arg) 8217 return true; 8218 8219 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8220 } 8221 8222 static bool requiresParensToAddCast(const Expr *E) { 8223 // FIXME: We should have a general way to reason about operator 8224 // precedence and whether parens are actually needed here. 8225 // Take care of a few common cases where they aren't. 8226 const Expr *Inside = E->IgnoreImpCasts(); 8227 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8228 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8229 8230 switch (Inside->getStmtClass()) { 8231 case Stmt::ArraySubscriptExprClass: 8232 case Stmt::CallExprClass: 8233 case Stmt::CharacterLiteralClass: 8234 case Stmt::CXXBoolLiteralExprClass: 8235 case Stmt::DeclRefExprClass: 8236 case Stmt::FloatingLiteralClass: 8237 case Stmt::IntegerLiteralClass: 8238 case Stmt::MemberExprClass: 8239 case Stmt::ObjCArrayLiteralClass: 8240 case Stmt::ObjCBoolLiteralExprClass: 8241 case Stmt::ObjCBoxedExprClass: 8242 case Stmt::ObjCDictionaryLiteralClass: 8243 case Stmt::ObjCEncodeExprClass: 8244 case Stmt::ObjCIvarRefExprClass: 8245 case Stmt::ObjCMessageExprClass: 8246 case Stmt::ObjCPropertyRefExprClass: 8247 case Stmt::ObjCStringLiteralClass: 8248 case Stmt::ObjCSubscriptRefExprClass: 8249 case Stmt::ParenExprClass: 8250 case Stmt::StringLiteralClass: 8251 case Stmt::UnaryOperatorClass: 8252 return false; 8253 default: 8254 return true; 8255 } 8256 } 8257 8258 static std::pair<QualType, StringRef> 8259 shouldNotPrintDirectly(const ASTContext &Context, 8260 QualType IntendedTy, 8261 const Expr *E) { 8262 // Use a 'while' to peel off layers of typedefs. 8263 QualType TyTy = IntendedTy; 8264 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8265 StringRef Name = UserTy->getDecl()->getName(); 8266 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8267 .Case("CFIndex", Context.getNSIntegerType()) 8268 .Case("NSInteger", Context.getNSIntegerType()) 8269 .Case("NSUInteger", Context.getNSUIntegerType()) 8270 .Case("SInt32", Context.IntTy) 8271 .Case("UInt32", Context.UnsignedIntTy) 8272 .Default(QualType()); 8273 8274 if (!CastTy.isNull()) 8275 return std::make_pair(CastTy, Name); 8276 8277 TyTy = UserTy->desugar(); 8278 } 8279 8280 // Strip parens if necessary. 8281 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8282 return shouldNotPrintDirectly(Context, 8283 PE->getSubExpr()->getType(), 8284 PE->getSubExpr()); 8285 8286 // If this is a conditional expression, then its result type is constructed 8287 // via usual arithmetic conversions and thus there might be no necessary 8288 // typedef sugar there. Recurse to operands to check for NSInteger & 8289 // Co. usage condition. 8290 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8291 QualType TrueTy, FalseTy; 8292 StringRef TrueName, FalseName; 8293 8294 std::tie(TrueTy, TrueName) = 8295 shouldNotPrintDirectly(Context, 8296 CO->getTrueExpr()->getType(), 8297 CO->getTrueExpr()); 8298 std::tie(FalseTy, FalseName) = 8299 shouldNotPrintDirectly(Context, 8300 CO->getFalseExpr()->getType(), 8301 CO->getFalseExpr()); 8302 8303 if (TrueTy == FalseTy) 8304 return std::make_pair(TrueTy, TrueName); 8305 else if (TrueTy.isNull()) 8306 return std::make_pair(FalseTy, FalseName); 8307 else if (FalseTy.isNull()) 8308 return std::make_pair(TrueTy, TrueName); 8309 } 8310 8311 return std::make_pair(QualType(), StringRef()); 8312 } 8313 8314 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8315 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8316 /// type do not count. 8317 static bool 8318 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8319 QualType From = ICE->getSubExpr()->getType(); 8320 QualType To = ICE->getType(); 8321 // It's an integer promotion if the destination type is the promoted 8322 // source type. 8323 if (ICE->getCastKind() == CK_IntegralCast && 8324 From->isPromotableIntegerType() && 8325 S.Context.getPromotedIntegerType(From) == To) 8326 return true; 8327 // Look through vector types, since we do default argument promotion for 8328 // those in OpenCL. 8329 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8330 From = VecTy->getElementType(); 8331 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8332 To = VecTy->getElementType(); 8333 // It's a floating promotion if the source type is a lower rank. 8334 return ICE->getCastKind() == CK_FloatingCast && 8335 S.Context.getFloatingTypeOrder(From, To) < 0; 8336 } 8337 8338 bool 8339 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8340 const char *StartSpecifier, 8341 unsigned SpecifierLen, 8342 const Expr *E) { 8343 using namespace analyze_format_string; 8344 using namespace analyze_printf; 8345 8346 // Now type check the data expression that matches the 8347 // format specifier. 8348 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8349 if (!AT.isValid()) 8350 return true; 8351 8352 QualType ExprTy = E->getType(); 8353 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8354 ExprTy = TET->getUnderlyingExpr()->getType(); 8355 } 8356 8357 // Diagnose attempts to print a boolean value as a character. Unlike other 8358 // -Wformat diagnostics, this is fine from a type perspective, but it still 8359 // doesn't make sense. 8360 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8361 E->isKnownToHaveBooleanValue()) { 8362 const CharSourceRange &CSR = 8363 getSpecifierRange(StartSpecifier, SpecifierLen); 8364 SmallString<4> FSString; 8365 llvm::raw_svector_ostream os(FSString); 8366 FS.toString(os); 8367 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8368 << FSString, 8369 E->getExprLoc(), false, CSR); 8370 return true; 8371 } 8372 8373 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8374 if (Match == analyze_printf::ArgType::Match) 8375 return true; 8376 8377 // Look through argument promotions for our error message's reported type. 8378 // This includes the integral and floating promotions, but excludes array 8379 // and function pointer decay (seeing that an argument intended to be a 8380 // string has type 'char [6]' is probably more confusing than 'char *') and 8381 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8382 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8383 if (isArithmeticArgumentPromotion(S, ICE)) { 8384 E = ICE->getSubExpr(); 8385 ExprTy = E->getType(); 8386 8387 // Check if we didn't match because of an implicit cast from a 'char' 8388 // or 'short' to an 'int'. This is done because printf is a varargs 8389 // function. 8390 if (ICE->getType() == S.Context.IntTy || 8391 ICE->getType() == S.Context.UnsignedIntTy) { 8392 // All further checking is done on the subexpression 8393 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8394 AT.matchesType(S.Context, ExprTy); 8395 if (ImplicitMatch == analyze_printf::ArgType::Match) 8396 return true; 8397 if (ImplicitMatch == ArgType::NoMatchPedantic || 8398 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8399 Match = ImplicitMatch; 8400 } 8401 } 8402 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8403 // Special case for 'a', which has type 'int' in C. 8404 // Note, however, that we do /not/ want to treat multibyte constants like 8405 // 'MooV' as characters! This form is deprecated but still exists. 8406 if (ExprTy == S.Context.IntTy) 8407 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8408 ExprTy = S.Context.CharTy; 8409 } 8410 8411 // Look through enums to their underlying type. 8412 bool IsEnum = false; 8413 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8414 ExprTy = EnumTy->getDecl()->getIntegerType(); 8415 IsEnum = true; 8416 } 8417 8418 // %C in an Objective-C context prints a unichar, not a wchar_t. 8419 // If the argument is an integer of some kind, believe the %C and suggest 8420 // a cast instead of changing the conversion specifier. 8421 QualType IntendedTy = ExprTy; 8422 if (isObjCContext() && 8423 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8424 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8425 !ExprTy->isCharType()) { 8426 // 'unichar' is defined as a typedef of unsigned short, but we should 8427 // prefer using the typedef if it is visible. 8428 IntendedTy = S.Context.UnsignedShortTy; 8429 8430 // While we are here, check if the value is an IntegerLiteral that happens 8431 // to be within the valid range. 8432 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8433 const llvm::APInt &V = IL->getValue(); 8434 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8435 return true; 8436 } 8437 8438 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8439 Sema::LookupOrdinaryName); 8440 if (S.LookupName(Result, S.getCurScope())) { 8441 NamedDecl *ND = Result.getFoundDecl(); 8442 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8443 if (TD->getUnderlyingType() == IntendedTy) 8444 IntendedTy = S.Context.getTypedefType(TD); 8445 } 8446 } 8447 } 8448 8449 // Special-case some of Darwin's platform-independence types by suggesting 8450 // casts to primitive types that are known to be large enough. 8451 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8452 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8453 QualType CastTy; 8454 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8455 if (!CastTy.isNull()) { 8456 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8457 // (long in ASTContext). Only complain to pedants. 8458 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8459 (AT.isSizeT() || AT.isPtrdiffT()) && 8460 AT.matchesType(S.Context, CastTy)) 8461 Match = ArgType::NoMatchPedantic; 8462 IntendedTy = CastTy; 8463 ShouldNotPrintDirectly = true; 8464 } 8465 } 8466 8467 // We may be able to offer a FixItHint if it is a supported type. 8468 PrintfSpecifier fixedFS = FS; 8469 bool Success = 8470 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8471 8472 if (Success) { 8473 // Get the fix string from the fixed format specifier 8474 SmallString<16> buf; 8475 llvm::raw_svector_ostream os(buf); 8476 fixedFS.toString(os); 8477 8478 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8479 8480 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8481 unsigned Diag; 8482 switch (Match) { 8483 case ArgType::Match: llvm_unreachable("expected non-matching"); 8484 case ArgType::NoMatchPedantic: 8485 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8486 break; 8487 case ArgType::NoMatchTypeConfusion: 8488 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8489 break; 8490 case ArgType::NoMatch: 8491 Diag = diag::warn_format_conversion_argument_type_mismatch; 8492 break; 8493 } 8494 8495 // In this case, the specifier is wrong and should be changed to match 8496 // the argument. 8497 EmitFormatDiagnostic(S.PDiag(Diag) 8498 << AT.getRepresentativeTypeName(S.Context) 8499 << IntendedTy << IsEnum << E->getSourceRange(), 8500 E->getBeginLoc(), 8501 /*IsStringLocation*/ false, SpecRange, 8502 FixItHint::CreateReplacement(SpecRange, os.str())); 8503 } else { 8504 // The canonical type for formatting this value is different from the 8505 // actual type of the expression. (This occurs, for example, with Darwin's 8506 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8507 // should be printed as 'long' for 64-bit compatibility.) 8508 // Rather than emitting a normal format/argument mismatch, we want to 8509 // add a cast to the recommended type (and correct the format string 8510 // if necessary). 8511 SmallString<16> CastBuf; 8512 llvm::raw_svector_ostream CastFix(CastBuf); 8513 CastFix << "("; 8514 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8515 CastFix << ")"; 8516 8517 SmallVector<FixItHint,4> Hints; 8518 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8519 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8520 8521 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8522 // If there's already a cast present, just replace it. 8523 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8524 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8525 8526 } else if (!requiresParensToAddCast(E)) { 8527 // If the expression has high enough precedence, 8528 // just write the C-style cast. 8529 Hints.push_back( 8530 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8531 } else { 8532 // Otherwise, add parens around the expression as well as the cast. 8533 CastFix << "("; 8534 Hints.push_back( 8535 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8536 8537 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8538 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8539 } 8540 8541 if (ShouldNotPrintDirectly) { 8542 // The expression has a type that should not be printed directly. 8543 // We extract the name from the typedef because we don't want to show 8544 // the underlying type in the diagnostic. 8545 StringRef Name; 8546 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8547 Name = TypedefTy->getDecl()->getName(); 8548 else 8549 Name = CastTyName; 8550 unsigned Diag = Match == ArgType::NoMatchPedantic 8551 ? diag::warn_format_argument_needs_cast_pedantic 8552 : diag::warn_format_argument_needs_cast; 8553 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8554 << E->getSourceRange(), 8555 E->getBeginLoc(), /*IsStringLocation=*/false, 8556 SpecRange, Hints); 8557 } else { 8558 // In this case, the expression could be printed using a different 8559 // specifier, but we've decided that the specifier is probably correct 8560 // and we should cast instead. Just use the normal warning message. 8561 EmitFormatDiagnostic( 8562 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8563 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8564 << E->getSourceRange(), 8565 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8566 } 8567 } 8568 } else { 8569 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8570 SpecifierLen); 8571 // Since the warning for passing non-POD types to variadic functions 8572 // was deferred until now, we emit a warning for non-POD 8573 // arguments here. 8574 switch (S.isValidVarArgType(ExprTy)) { 8575 case Sema::VAK_Valid: 8576 case Sema::VAK_ValidInCXX11: { 8577 unsigned Diag; 8578 switch (Match) { 8579 case ArgType::Match: llvm_unreachable("expected non-matching"); 8580 case ArgType::NoMatchPedantic: 8581 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8582 break; 8583 case ArgType::NoMatchTypeConfusion: 8584 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8585 break; 8586 case ArgType::NoMatch: 8587 Diag = diag::warn_format_conversion_argument_type_mismatch; 8588 break; 8589 } 8590 8591 EmitFormatDiagnostic( 8592 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8593 << IsEnum << CSR << E->getSourceRange(), 8594 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8595 break; 8596 } 8597 case Sema::VAK_Undefined: 8598 case Sema::VAK_MSVCUndefined: 8599 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8600 << S.getLangOpts().CPlusPlus11 << ExprTy 8601 << CallType 8602 << AT.getRepresentativeTypeName(S.Context) << CSR 8603 << E->getSourceRange(), 8604 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8605 checkForCStrMembers(AT, E); 8606 break; 8607 8608 case Sema::VAK_Invalid: 8609 if (ExprTy->isObjCObjectType()) 8610 EmitFormatDiagnostic( 8611 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8612 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8613 << AT.getRepresentativeTypeName(S.Context) << CSR 8614 << E->getSourceRange(), 8615 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8616 else 8617 // FIXME: If this is an initializer list, suggest removing the braces 8618 // or inserting a cast to the target type. 8619 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8620 << isa<InitListExpr>(E) << ExprTy << CallType 8621 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8622 break; 8623 } 8624 8625 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8626 "format string specifier index out of range"); 8627 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8628 } 8629 8630 return true; 8631 } 8632 8633 //===--- CHECK: Scanf format string checking ------------------------------===// 8634 8635 namespace { 8636 8637 class CheckScanfHandler : public CheckFormatHandler { 8638 public: 8639 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8640 const Expr *origFormatExpr, Sema::FormatStringType type, 8641 unsigned firstDataArg, unsigned numDataArgs, 8642 const char *beg, bool hasVAListArg, 8643 ArrayRef<const Expr *> Args, unsigned formatIdx, 8644 bool inFunctionCall, Sema::VariadicCallType CallType, 8645 llvm::SmallBitVector &CheckedVarArgs, 8646 UncoveredArgHandler &UncoveredArg) 8647 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8648 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8649 inFunctionCall, CallType, CheckedVarArgs, 8650 UncoveredArg) {} 8651 8652 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8653 const char *startSpecifier, 8654 unsigned specifierLen) override; 8655 8656 bool HandleInvalidScanfConversionSpecifier( 8657 const analyze_scanf::ScanfSpecifier &FS, 8658 const char *startSpecifier, 8659 unsigned specifierLen) override; 8660 8661 void HandleIncompleteScanList(const char *start, const char *end) override; 8662 }; 8663 8664 } // namespace 8665 8666 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8667 const char *end) { 8668 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8669 getLocationOfByte(end), /*IsStringLocation*/true, 8670 getSpecifierRange(start, end - start)); 8671 } 8672 8673 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8674 const analyze_scanf::ScanfSpecifier &FS, 8675 const char *startSpecifier, 8676 unsigned specifierLen) { 8677 const analyze_scanf::ScanfConversionSpecifier &CS = 8678 FS.getConversionSpecifier(); 8679 8680 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8681 getLocationOfByte(CS.getStart()), 8682 startSpecifier, specifierLen, 8683 CS.getStart(), CS.getLength()); 8684 } 8685 8686 bool CheckScanfHandler::HandleScanfSpecifier( 8687 const analyze_scanf::ScanfSpecifier &FS, 8688 const char *startSpecifier, 8689 unsigned specifierLen) { 8690 using namespace analyze_scanf; 8691 using namespace analyze_format_string; 8692 8693 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8694 8695 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8696 // be used to decide if we are using positional arguments consistently. 8697 if (FS.consumesDataArgument()) { 8698 if (atFirstArg) { 8699 atFirstArg = false; 8700 usesPositionalArgs = FS.usesPositionalArg(); 8701 } 8702 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8703 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8704 startSpecifier, specifierLen); 8705 return false; 8706 } 8707 } 8708 8709 // Check if the field with is non-zero. 8710 const OptionalAmount &Amt = FS.getFieldWidth(); 8711 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8712 if (Amt.getConstantAmount() == 0) { 8713 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8714 Amt.getConstantLength()); 8715 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8716 getLocationOfByte(Amt.getStart()), 8717 /*IsStringLocation*/true, R, 8718 FixItHint::CreateRemoval(R)); 8719 } 8720 } 8721 8722 if (!FS.consumesDataArgument()) { 8723 // FIXME: Technically specifying a precision or field width here 8724 // makes no sense. Worth issuing a warning at some point. 8725 return true; 8726 } 8727 8728 // Consume the argument. 8729 unsigned argIndex = FS.getArgIndex(); 8730 if (argIndex < NumDataArgs) { 8731 // The check to see if the argIndex is valid will come later. 8732 // We set the bit here because we may exit early from this 8733 // function if we encounter some other error. 8734 CoveredArgs.set(argIndex); 8735 } 8736 8737 // Check the length modifier is valid with the given conversion specifier. 8738 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8739 S.getLangOpts())) 8740 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8741 diag::warn_format_nonsensical_length); 8742 else if (!FS.hasStandardLengthModifier()) 8743 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8744 else if (!FS.hasStandardLengthConversionCombination()) 8745 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8746 diag::warn_format_non_standard_conversion_spec); 8747 8748 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8749 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8750 8751 // The remaining checks depend on the data arguments. 8752 if (HasVAListArg) 8753 return true; 8754 8755 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8756 return false; 8757 8758 // Check that the argument type matches the format specifier. 8759 const Expr *Ex = getDataArg(argIndex); 8760 if (!Ex) 8761 return true; 8762 8763 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8764 8765 if (!AT.isValid()) { 8766 return true; 8767 } 8768 8769 analyze_format_string::ArgType::MatchKind Match = 8770 AT.matchesType(S.Context, Ex->getType()); 8771 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8772 if (Match == analyze_format_string::ArgType::Match) 8773 return true; 8774 8775 ScanfSpecifier fixedFS = FS; 8776 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8777 S.getLangOpts(), S.Context); 8778 8779 unsigned Diag = 8780 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8781 : diag::warn_format_conversion_argument_type_mismatch; 8782 8783 if (Success) { 8784 // Get the fix string from the fixed format specifier. 8785 SmallString<128> buf; 8786 llvm::raw_svector_ostream os(buf); 8787 fixedFS.toString(os); 8788 8789 EmitFormatDiagnostic( 8790 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8791 << Ex->getType() << false << Ex->getSourceRange(), 8792 Ex->getBeginLoc(), 8793 /*IsStringLocation*/ false, 8794 getSpecifierRange(startSpecifier, specifierLen), 8795 FixItHint::CreateReplacement( 8796 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8797 } else { 8798 EmitFormatDiagnostic(S.PDiag(Diag) 8799 << AT.getRepresentativeTypeName(S.Context) 8800 << Ex->getType() << false << Ex->getSourceRange(), 8801 Ex->getBeginLoc(), 8802 /*IsStringLocation*/ false, 8803 getSpecifierRange(startSpecifier, specifierLen)); 8804 } 8805 8806 return true; 8807 } 8808 8809 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8810 const Expr *OrigFormatExpr, 8811 ArrayRef<const Expr *> Args, 8812 bool HasVAListArg, unsigned format_idx, 8813 unsigned firstDataArg, 8814 Sema::FormatStringType Type, 8815 bool inFunctionCall, 8816 Sema::VariadicCallType CallType, 8817 llvm::SmallBitVector &CheckedVarArgs, 8818 UncoveredArgHandler &UncoveredArg, 8819 bool IgnoreStringsWithoutSpecifiers) { 8820 // CHECK: is the format string a wide literal? 8821 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8822 CheckFormatHandler::EmitFormatDiagnostic( 8823 S, inFunctionCall, Args[format_idx], 8824 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8825 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8826 return; 8827 } 8828 8829 // Str - The format string. NOTE: this is NOT null-terminated! 8830 StringRef StrRef = FExpr->getString(); 8831 const char *Str = StrRef.data(); 8832 // Account for cases where the string literal is truncated in a declaration. 8833 const ConstantArrayType *T = 8834 S.Context.getAsConstantArrayType(FExpr->getType()); 8835 assert(T && "String literal not of constant array type!"); 8836 size_t TypeSize = T->getSize().getZExtValue(); 8837 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8838 const unsigned numDataArgs = Args.size() - firstDataArg; 8839 8840 if (IgnoreStringsWithoutSpecifiers && 8841 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8842 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8843 return; 8844 8845 // Emit a warning if the string literal is truncated and does not contain an 8846 // embedded null character. 8847 if (TypeSize <= StrRef.size() && 8848 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8849 CheckFormatHandler::EmitFormatDiagnostic( 8850 S, inFunctionCall, Args[format_idx], 8851 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8852 FExpr->getBeginLoc(), 8853 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8854 return; 8855 } 8856 8857 // CHECK: empty format string? 8858 if (StrLen == 0 && numDataArgs > 0) { 8859 CheckFormatHandler::EmitFormatDiagnostic( 8860 S, inFunctionCall, Args[format_idx], 8861 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8862 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8863 return; 8864 } 8865 8866 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8867 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8868 Type == Sema::FST_OSTrace) { 8869 CheckPrintfHandler H( 8870 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8871 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8872 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8873 CheckedVarArgs, UncoveredArg); 8874 8875 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8876 S.getLangOpts(), 8877 S.Context.getTargetInfo(), 8878 Type == Sema::FST_FreeBSDKPrintf)) 8879 H.DoneProcessing(); 8880 } else if (Type == Sema::FST_Scanf) { 8881 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8882 numDataArgs, Str, HasVAListArg, Args, format_idx, 8883 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8884 8885 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8886 S.getLangOpts(), 8887 S.Context.getTargetInfo())) 8888 H.DoneProcessing(); 8889 } // TODO: handle other formats 8890 } 8891 8892 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8893 // Str - The format string. NOTE: this is NOT null-terminated! 8894 StringRef StrRef = FExpr->getString(); 8895 const char *Str = StrRef.data(); 8896 // Account for cases where the string literal is truncated in a declaration. 8897 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8898 assert(T && "String literal not of constant array type!"); 8899 size_t TypeSize = T->getSize().getZExtValue(); 8900 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8901 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8902 getLangOpts(), 8903 Context.getTargetInfo()); 8904 } 8905 8906 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8907 8908 // Returns the related absolute value function that is larger, of 0 if one 8909 // does not exist. 8910 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8911 switch (AbsFunction) { 8912 default: 8913 return 0; 8914 8915 case Builtin::BI__builtin_abs: 8916 return Builtin::BI__builtin_labs; 8917 case Builtin::BI__builtin_labs: 8918 return Builtin::BI__builtin_llabs; 8919 case Builtin::BI__builtin_llabs: 8920 return 0; 8921 8922 case Builtin::BI__builtin_fabsf: 8923 return Builtin::BI__builtin_fabs; 8924 case Builtin::BI__builtin_fabs: 8925 return Builtin::BI__builtin_fabsl; 8926 case Builtin::BI__builtin_fabsl: 8927 return 0; 8928 8929 case Builtin::BI__builtin_cabsf: 8930 return Builtin::BI__builtin_cabs; 8931 case Builtin::BI__builtin_cabs: 8932 return Builtin::BI__builtin_cabsl; 8933 case Builtin::BI__builtin_cabsl: 8934 return 0; 8935 8936 case Builtin::BIabs: 8937 return Builtin::BIlabs; 8938 case Builtin::BIlabs: 8939 return Builtin::BIllabs; 8940 case Builtin::BIllabs: 8941 return 0; 8942 8943 case Builtin::BIfabsf: 8944 return Builtin::BIfabs; 8945 case Builtin::BIfabs: 8946 return Builtin::BIfabsl; 8947 case Builtin::BIfabsl: 8948 return 0; 8949 8950 case Builtin::BIcabsf: 8951 return Builtin::BIcabs; 8952 case Builtin::BIcabs: 8953 return Builtin::BIcabsl; 8954 case Builtin::BIcabsl: 8955 return 0; 8956 } 8957 } 8958 8959 // Returns the argument type of the absolute value function. 8960 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8961 unsigned AbsType) { 8962 if (AbsType == 0) 8963 return QualType(); 8964 8965 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8966 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8967 if (Error != ASTContext::GE_None) 8968 return QualType(); 8969 8970 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8971 if (!FT) 8972 return QualType(); 8973 8974 if (FT->getNumParams() != 1) 8975 return QualType(); 8976 8977 return FT->getParamType(0); 8978 } 8979 8980 // Returns the best absolute value function, or zero, based on type and 8981 // current absolute value function. 8982 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8983 unsigned AbsFunctionKind) { 8984 unsigned BestKind = 0; 8985 uint64_t ArgSize = Context.getTypeSize(ArgType); 8986 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8987 Kind = getLargerAbsoluteValueFunction(Kind)) { 8988 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8989 if (Context.getTypeSize(ParamType) >= ArgSize) { 8990 if (BestKind == 0) 8991 BestKind = Kind; 8992 else if (Context.hasSameType(ParamType, ArgType)) { 8993 BestKind = Kind; 8994 break; 8995 } 8996 } 8997 } 8998 return BestKind; 8999 } 9000 9001 enum AbsoluteValueKind { 9002 AVK_Integer, 9003 AVK_Floating, 9004 AVK_Complex 9005 }; 9006 9007 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 9008 if (T->isIntegralOrEnumerationType()) 9009 return AVK_Integer; 9010 if (T->isRealFloatingType()) 9011 return AVK_Floating; 9012 if (T->isAnyComplexType()) 9013 return AVK_Complex; 9014 9015 llvm_unreachable("Type not integer, floating, or complex"); 9016 } 9017 9018 // Changes the absolute value function to a different type. Preserves whether 9019 // the function is a builtin. 9020 static unsigned changeAbsFunction(unsigned AbsKind, 9021 AbsoluteValueKind ValueKind) { 9022 switch (ValueKind) { 9023 case AVK_Integer: 9024 switch (AbsKind) { 9025 default: 9026 return 0; 9027 case Builtin::BI__builtin_fabsf: 9028 case Builtin::BI__builtin_fabs: 9029 case Builtin::BI__builtin_fabsl: 9030 case Builtin::BI__builtin_cabsf: 9031 case Builtin::BI__builtin_cabs: 9032 case Builtin::BI__builtin_cabsl: 9033 return Builtin::BI__builtin_abs; 9034 case Builtin::BIfabsf: 9035 case Builtin::BIfabs: 9036 case Builtin::BIfabsl: 9037 case Builtin::BIcabsf: 9038 case Builtin::BIcabs: 9039 case Builtin::BIcabsl: 9040 return Builtin::BIabs; 9041 } 9042 case AVK_Floating: 9043 switch (AbsKind) { 9044 default: 9045 return 0; 9046 case Builtin::BI__builtin_abs: 9047 case Builtin::BI__builtin_labs: 9048 case Builtin::BI__builtin_llabs: 9049 case Builtin::BI__builtin_cabsf: 9050 case Builtin::BI__builtin_cabs: 9051 case Builtin::BI__builtin_cabsl: 9052 return Builtin::BI__builtin_fabsf; 9053 case Builtin::BIabs: 9054 case Builtin::BIlabs: 9055 case Builtin::BIllabs: 9056 case Builtin::BIcabsf: 9057 case Builtin::BIcabs: 9058 case Builtin::BIcabsl: 9059 return Builtin::BIfabsf; 9060 } 9061 case AVK_Complex: 9062 switch (AbsKind) { 9063 default: 9064 return 0; 9065 case Builtin::BI__builtin_abs: 9066 case Builtin::BI__builtin_labs: 9067 case Builtin::BI__builtin_llabs: 9068 case Builtin::BI__builtin_fabsf: 9069 case Builtin::BI__builtin_fabs: 9070 case Builtin::BI__builtin_fabsl: 9071 return Builtin::BI__builtin_cabsf; 9072 case Builtin::BIabs: 9073 case Builtin::BIlabs: 9074 case Builtin::BIllabs: 9075 case Builtin::BIfabsf: 9076 case Builtin::BIfabs: 9077 case Builtin::BIfabsl: 9078 return Builtin::BIcabsf; 9079 } 9080 } 9081 llvm_unreachable("Unable to convert function"); 9082 } 9083 9084 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 9085 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 9086 if (!FnInfo) 9087 return 0; 9088 9089 switch (FDecl->getBuiltinID()) { 9090 default: 9091 return 0; 9092 case Builtin::BI__builtin_abs: 9093 case Builtin::BI__builtin_fabs: 9094 case Builtin::BI__builtin_fabsf: 9095 case Builtin::BI__builtin_fabsl: 9096 case Builtin::BI__builtin_labs: 9097 case Builtin::BI__builtin_llabs: 9098 case Builtin::BI__builtin_cabs: 9099 case Builtin::BI__builtin_cabsf: 9100 case Builtin::BI__builtin_cabsl: 9101 case Builtin::BIabs: 9102 case Builtin::BIlabs: 9103 case Builtin::BIllabs: 9104 case Builtin::BIfabs: 9105 case Builtin::BIfabsf: 9106 case Builtin::BIfabsl: 9107 case Builtin::BIcabs: 9108 case Builtin::BIcabsf: 9109 case Builtin::BIcabsl: 9110 return FDecl->getBuiltinID(); 9111 } 9112 llvm_unreachable("Unknown Builtin type"); 9113 } 9114 9115 // If the replacement is valid, emit a note with replacement function. 9116 // Additionally, suggest including the proper header if not already included. 9117 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 9118 unsigned AbsKind, QualType ArgType) { 9119 bool EmitHeaderHint = true; 9120 const char *HeaderName = nullptr; 9121 const char *FunctionName = nullptr; 9122 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 9123 FunctionName = "std::abs"; 9124 if (ArgType->isIntegralOrEnumerationType()) { 9125 HeaderName = "cstdlib"; 9126 } else if (ArgType->isRealFloatingType()) { 9127 HeaderName = "cmath"; 9128 } else { 9129 llvm_unreachable("Invalid Type"); 9130 } 9131 9132 // Lookup all std::abs 9133 if (NamespaceDecl *Std = S.getStdNamespace()) { 9134 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 9135 R.suppressDiagnostics(); 9136 S.LookupQualifiedName(R, Std); 9137 9138 for (const auto *I : R) { 9139 const FunctionDecl *FDecl = nullptr; 9140 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 9141 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 9142 } else { 9143 FDecl = dyn_cast<FunctionDecl>(I); 9144 } 9145 if (!FDecl) 9146 continue; 9147 9148 // Found std::abs(), check that they are the right ones. 9149 if (FDecl->getNumParams() != 1) 9150 continue; 9151 9152 // Check that the parameter type can handle the argument. 9153 QualType ParamType = FDecl->getParamDecl(0)->getType(); 9154 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 9155 S.Context.getTypeSize(ArgType) <= 9156 S.Context.getTypeSize(ParamType)) { 9157 // Found a function, don't need the header hint. 9158 EmitHeaderHint = false; 9159 break; 9160 } 9161 } 9162 } 9163 } else { 9164 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 9165 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 9166 9167 if (HeaderName) { 9168 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 9169 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 9170 R.suppressDiagnostics(); 9171 S.LookupName(R, S.getCurScope()); 9172 9173 if (R.isSingleResult()) { 9174 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 9175 if (FD && FD->getBuiltinID() == AbsKind) { 9176 EmitHeaderHint = false; 9177 } else { 9178 return; 9179 } 9180 } else if (!R.empty()) { 9181 return; 9182 } 9183 } 9184 } 9185 9186 S.Diag(Loc, diag::note_replace_abs_function) 9187 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9188 9189 if (!HeaderName) 9190 return; 9191 9192 if (!EmitHeaderHint) 9193 return; 9194 9195 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9196 << FunctionName; 9197 } 9198 9199 template <std::size_t StrLen> 9200 static bool IsStdFunction(const FunctionDecl *FDecl, 9201 const char (&Str)[StrLen]) { 9202 if (!FDecl) 9203 return false; 9204 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9205 return false; 9206 if (!FDecl->isInStdNamespace()) 9207 return false; 9208 9209 return true; 9210 } 9211 9212 // Warn when using the wrong abs() function. 9213 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9214 const FunctionDecl *FDecl) { 9215 if (Call->getNumArgs() != 1) 9216 return; 9217 9218 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9219 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9220 if (AbsKind == 0 && !IsStdAbs) 9221 return; 9222 9223 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9224 QualType ParamType = Call->getArg(0)->getType(); 9225 9226 // Unsigned types cannot be negative. Suggest removing the absolute value 9227 // function call. 9228 if (ArgType->isUnsignedIntegerType()) { 9229 const char *FunctionName = 9230 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9231 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9232 Diag(Call->getExprLoc(), diag::note_remove_abs) 9233 << FunctionName 9234 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9235 return; 9236 } 9237 9238 // Taking the absolute value of a pointer is very suspicious, they probably 9239 // wanted to index into an array, dereference a pointer, call a function, etc. 9240 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9241 unsigned DiagType = 0; 9242 if (ArgType->isFunctionType()) 9243 DiagType = 1; 9244 else if (ArgType->isArrayType()) 9245 DiagType = 2; 9246 9247 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9248 return; 9249 } 9250 9251 // std::abs has overloads which prevent most of the absolute value problems 9252 // from occurring. 9253 if (IsStdAbs) 9254 return; 9255 9256 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9257 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9258 9259 // The argument and parameter are the same kind. Check if they are the right 9260 // size. 9261 if (ArgValueKind == ParamValueKind) { 9262 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9263 return; 9264 9265 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9266 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9267 << FDecl << ArgType << ParamType; 9268 9269 if (NewAbsKind == 0) 9270 return; 9271 9272 emitReplacement(*this, Call->getExprLoc(), 9273 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9274 return; 9275 } 9276 9277 // ArgValueKind != ParamValueKind 9278 // The wrong type of absolute value function was used. Attempt to find the 9279 // proper one. 9280 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9281 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9282 if (NewAbsKind == 0) 9283 return; 9284 9285 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9286 << FDecl << ParamValueKind << ArgValueKind; 9287 9288 emitReplacement(*this, Call->getExprLoc(), 9289 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9290 } 9291 9292 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9293 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9294 const FunctionDecl *FDecl) { 9295 if (!Call || !FDecl) return; 9296 9297 // Ignore template specializations and macros. 9298 if (inTemplateInstantiation()) return; 9299 if (Call->getExprLoc().isMacroID()) return; 9300 9301 // Only care about the one template argument, two function parameter std::max 9302 if (Call->getNumArgs() != 2) return; 9303 if (!IsStdFunction(FDecl, "max")) return; 9304 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9305 if (!ArgList) return; 9306 if (ArgList->size() != 1) return; 9307 9308 // Check that template type argument is unsigned integer. 9309 const auto& TA = ArgList->get(0); 9310 if (TA.getKind() != TemplateArgument::Type) return; 9311 QualType ArgType = TA.getAsType(); 9312 if (!ArgType->isUnsignedIntegerType()) return; 9313 9314 // See if either argument is a literal zero. 9315 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9316 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9317 if (!MTE) return false; 9318 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9319 if (!Num) return false; 9320 if (Num->getValue() != 0) return false; 9321 return true; 9322 }; 9323 9324 const Expr *FirstArg = Call->getArg(0); 9325 const Expr *SecondArg = Call->getArg(1); 9326 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9327 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9328 9329 // Only warn when exactly one argument is zero. 9330 if (IsFirstArgZero == IsSecondArgZero) return; 9331 9332 SourceRange FirstRange = FirstArg->getSourceRange(); 9333 SourceRange SecondRange = SecondArg->getSourceRange(); 9334 9335 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9336 9337 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9338 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9339 9340 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9341 SourceRange RemovalRange; 9342 if (IsFirstArgZero) { 9343 RemovalRange = SourceRange(FirstRange.getBegin(), 9344 SecondRange.getBegin().getLocWithOffset(-1)); 9345 } else { 9346 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9347 SecondRange.getEnd()); 9348 } 9349 9350 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9351 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9352 << FixItHint::CreateRemoval(RemovalRange); 9353 } 9354 9355 //===--- CHECK: Standard memory functions ---------------------------------===// 9356 9357 /// Takes the expression passed to the size_t parameter of functions 9358 /// such as memcmp, strncat, etc and warns if it's a comparison. 9359 /// 9360 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9361 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9362 IdentifierInfo *FnName, 9363 SourceLocation FnLoc, 9364 SourceLocation RParenLoc) { 9365 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9366 if (!Size) 9367 return false; 9368 9369 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9370 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9371 return false; 9372 9373 SourceRange SizeRange = Size->getSourceRange(); 9374 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9375 << SizeRange << FnName; 9376 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9377 << FnName 9378 << FixItHint::CreateInsertion( 9379 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9380 << FixItHint::CreateRemoval(RParenLoc); 9381 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9382 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9383 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9384 ")"); 9385 9386 return true; 9387 } 9388 9389 /// Determine whether the given type is or contains a dynamic class type 9390 /// (e.g., whether it has a vtable). 9391 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9392 bool &IsContained) { 9393 // Look through array types while ignoring qualifiers. 9394 const Type *Ty = T->getBaseElementTypeUnsafe(); 9395 IsContained = false; 9396 9397 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9398 RD = RD ? RD->getDefinition() : nullptr; 9399 if (!RD || RD->isInvalidDecl()) 9400 return nullptr; 9401 9402 if (RD->isDynamicClass()) 9403 return RD; 9404 9405 // Check all the fields. If any bases were dynamic, the class is dynamic. 9406 // It's impossible for a class to transitively contain itself by value, so 9407 // infinite recursion is impossible. 9408 for (auto *FD : RD->fields()) { 9409 bool SubContained; 9410 if (const CXXRecordDecl *ContainedRD = 9411 getContainedDynamicClass(FD->getType(), SubContained)) { 9412 IsContained = true; 9413 return ContainedRD; 9414 } 9415 } 9416 9417 return nullptr; 9418 } 9419 9420 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9421 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9422 if (Unary->getKind() == UETT_SizeOf) 9423 return Unary; 9424 return nullptr; 9425 } 9426 9427 /// If E is a sizeof expression, returns its argument expression, 9428 /// otherwise returns NULL. 9429 static const Expr *getSizeOfExprArg(const Expr *E) { 9430 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9431 if (!SizeOf->isArgumentType()) 9432 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9433 return nullptr; 9434 } 9435 9436 /// If E is a sizeof expression, returns its argument type. 9437 static QualType getSizeOfArgType(const Expr *E) { 9438 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9439 return SizeOf->getTypeOfArgument(); 9440 return QualType(); 9441 } 9442 9443 namespace { 9444 9445 struct SearchNonTrivialToInitializeField 9446 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9447 using Super = 9448 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9449 9450 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9451 9452 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9453 SourceLocation SL) { 9454 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9455 asDerived().visitArray(PDIK, AT, SL); 9456 return; 9457 } 9458 9459 Super::visitWithKind(PDIK, FT, SL); 9460 } 9461 9462 void visitARCStrong(QualType FT, SourceLocation SL) { 9463 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9464 } 9465 void visitARCWeak(QualType FT, SourceLocation SL) { 9466 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9467 } 9468 void visitStruct(QualType FT, SourceLocation SL) { 9469 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9470 visit(FD->getType(), FD->getLocation()); 9471 } 9472 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9473 const ArrayType *AT, SourceLocation SL) { 9474 visit(getContext().getBaseElementType(AT), SL); 9475 } 9476 void visitTrivial(QualType FT, SourceLocation SL) {} 9477 9478 static void diag(QualType RT, const Expr *E, Sema &S) { 9479 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9480 } 9481 9482 ASTContext &getContext() { return S.getASTContext(); } 9483 9484 const Expr *E; 9485 Sema &S; 9486 }; 9487 9488 struct SearchNonTrivialToCopyField 9489 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9490 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9491 9492 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9493 9494 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9495 SourceLocation SL) { 9496 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9497 asDerived().visitArray(PCK, AT, SL); 9498 return; 9499 } 9500 9501 Super::visitWithKind(PCK, FT, SL); 9502 } 9503 9504 void visitARCStrong(QualType FT, SourceLocation SL) { 9505 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9506 } 9507 void visitARCWeak(QualType FT, SourceLocation SL) { 9508 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9509 } 9510 void visitStruct(QualType FT, SourceLocation SL) { 9511 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9512 visit(FD->getType(), FD->getLocation()); 9513 } 9514 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9515 SourceLocation SL) { 9516 visit(getContext().getBaseElementType(AT), SL); 9517 } 9518 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9519 SourceLocation SL) {} 9520 void visitTrivial(QualType FT, SourceLocation SL) {} 9521 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9522 9523 static void diag(QualType RT, const Expr *E, Sema &S) { 9524 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9525 } 9526 9527 ASTContext &getContext() { return S.getASTContext(); } 9528 9529 const Expr *E; 9530 Sema &S; 9531 }; 9532 9533 } 9534 9535 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9536 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9537 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9538 9539 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9540 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9541 return false; 9542 9543 return doesExprLikelyComputeSize(BO->getLHS()) || 9544 doesExprLikelyComputeSize(BO->getRHS()); 9545 } 9546 9547 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9548 } 9549 9550 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9551 /// 9552 /// \code 9553 /// #define MACRO 0 9554 /// foo(MACRO); 9555 /// foo(0); 9556 /// \endcode 9557 /// 9558 /// This should return true for the first call to foo, but not for the second 9559 /// (regardless of whether foo is a macro or function). 9560 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9561 SourceLocation CallLoc, 9562 SourceLocation ArgLoc) { 9563 if (!CallLoc.isMacroID()) 9564 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9565 9566 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9567 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9568 } 9569 9570 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9571 /// last two arguments transposed. 9572 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9573 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9574 return; 9575 9576 const Expr *SizeArg = 9577 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9578 9579 auto isLiteralZero = [](const Expr *E) { 9580 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9581 }; 9582 9583 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9584 SourceLocation CallLoc = Call->getRParenLoc(); 9585 SourceManager &SM = S.getSourceManager(); 9586 if (isLiteralZero(SizeArg) && 9587 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9588 9589 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9590 9591 // Some platforms #define bzero to __builtin_memset. See if this is the 9592 // case, and if so, emit a better diagnostic. 9593 if (BId == Builtin::BIbzero || 9594 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9595 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9596 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9597 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9598 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9599 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9600 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9601 } 9602 return; 9603 } 9604 9605 // If the second argument to a memset is a sizeof expression and the third 9606 // isn't, this is also likely an error. This should catch 9607 // 'memset(buf, sizeof(buf), 0xff)'. 9608 if (BId == Builtin::BImemset && 9609 doesExprLikelyComputeSize(Call->getArg(1)) && 9610 !doesExprLikelyComputeSize(Call->getArg(2))) { 9611 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9612 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9613 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9614 return; 9615 } 9616 } 9617 9618 /// Check for dangerous or invalid arguments to memset(). 9619 /// 9620 /// This issues warnings on known problematic, dangerous or unspecified 9621 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9622 /// function calls. 9623 /// 9624 /// \param Call The call expression to diagnose. 9625 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9626 unsigned BId, 9627 IdentifierInfo *FnName) { 9628 assert(BId != 0); 9629 9630 // It is possible to have a non-standard definition of memset. Validate 9631 // we have enough arguments, and if not, abort further checking. 9632 unsigned ExpectedNumArgs = 9633 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9634 if (Call->getNumArgs() < ExpectedNumArgs) 9635 return; 9636 9637 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9638 BId == Builtin::BIstrndup ? 1 : 2); 9639 unsigned LenArg = 9640 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9641 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9642 9643 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9644 Call->getBeginLoc(), Call->getRParenLoc())) 9645 return; 9646 9647 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9648 CheckMemaccessSize(*this, BId, Call); 9649 9650 // We have special checking when the length is a sizeof expression. 9651 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9652 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9653 llvm::FoldingSetNodeID SizeOfArgID; 9654 9655 // Although widely used, 'bzero' is not a standard function. Be more strict 9656 // with the argument types before allowing diagnostics and only allow the 9657 // form bzero(ptr, sizeof(...)). 9658 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9659 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9660 return; 9661 9662 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9663 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9664 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9665 9666 QualType DestTy = Dest->getType(); 9667 QualType PointeeTy; 9668 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9669 PointeeTy = DestPtrTy->getPointeeType(); 9670 9671 // Never warn about void type pointers. This can be used to suppress 9672 // false positives. 9673 if (PointeeTy->isVoidType()) 9674 continue; 9675 9676 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9677 // actually comparing the expressions for equality. Because computing the 9678 // expression IDs can be expensive, we only do this if the diagnostic is 9679 // enabled. 9680 if (SizeOfArg && 9681 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9682 SizeOfArg->getExprLoc())) { 9683 // We only compute IDs for expressions if the warning is enabled, and 9684 // cache the sizeof arg's ID. 9685 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9686 SizeOfArg->Profile(SizeOfArgID, Context, true); 9687 llvm::FoldingSetNodeID DestID; 9688 Dest->Profile(DestID, Context, true); 9689 if (DestID == SizeOfArgID) { 9690 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9691 // over sizeof(src) as well. 9692 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9693 StringRef ReadableName = FnName->getName(); 9694 9695 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9696 if (UnaryOp->getOpcode() == UO_AddrOf) 9697 ActionIdx = 1; // If its an address-of operator, just remove it. 9698 if (!PointeeTy->isIncompleteType() && 9699 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9700 ActionIdx = 2; // If the pointee's size is sizeof(char), 9701 // suggest an explicit length. 9702 9703 // If the function is defined as a builtin macro, do not show macro 9704 // expansion. 9705 SourceLocation SL = SizeOfArg->getExprLoc(); 9706 SourceRange DSR = Dest->getSourceRange(); 9707 SourceRange SSR = SizeOfArg->getSourceRange(); 9708 SourceManager &SM = getSourceManager(); 9709 9710 if (SM.isMacroArgExpansion(SL)) { 9711 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9712 SL = SM.getSpellingLoc(SL); 9713 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9714 SM.getSpellingLoc(DSR.getEnd())); 9715 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9716 SM.getSpellingLoc(SSR.getEnd())); 9717 } 9718 9719 DiagRuntimeBehavior(SL, SizeOfArg, 9720 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9721 << ReadableName 9722 << PointeeTy 9723 << DestTy 9724 << DSR 9725 << SSR); 9726 DiagRuntimeBehavior(SL, SizeOfArg, 9727 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9728 << ActionIdx 9729 << SSR); 9730 9731 break; 9732 } 9733 } 9734 9735 // Also check for cases where the sizeof argument is the exact same 9736 // type as the memory argument, and where it points to a user-defined 9737 // record type. 9738 if (SizeOfArgTy != QualType()) { 9739 if (PointeeTy->isRecordType() && 9740 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9741 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9742 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9743 << FnName << SizeOfArgTy << ArgIdx 9744 << PointeeTy << Dest->getSourceRange() 9745 << LenExpr->getSourceRange()); 9746 break; 9747 } 9748 } 9749 } else if (DestTy->isArrayType()) { 9750 PointeeTy = DestTy; 9751 } 9752 9753 if (PointeeTy == QualType()) 9754 continue; 9755 9756 // Always complain about dynamic classes. 9757 bool IsContained; 9758 if (const CXXRecordDecl *ContainedRD = 9759 getContainedDynamicClass(PointeeTy, IsContained)) { 9760 9761 unsigned OperationType = 0; 9762 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9763 // "overwritten" if we're warning about the destination for any call 9764 // but memcmp; otherwise a verb appropriate to the call. 9765 if (ArgIdx != 0 || IsCmp) { 9766 if (BId == Builtin::BImemcpy) 9767 OperationType = 1; 9768 else if(BId == Builtin::BImemmove) 9769 OperationType = 2; 9770 else if (IsCmp) 9771 OperationType = 3; 9772 } 9773 9774 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9775 PDiag(diag::warn_dyn_class_memaccess) 9776 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9777 << IsContained << ContainedRD << OperationType 9778 << Call->getCallee()->getSourceRange()); 9779 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9780 BId != Builtin::BImemset) 9781 DiagRuntimeBehavior( 9782 Dest->getExprLoc(), Dest, 9783 PDiag(diag::warn_arc_object_memaccess) 9784 << ArgIdx << FnName << PointeeTy 9785 << Call->getCallee()->getSourceRange()); 9786 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9787 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9788 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9789 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9790 PDiag(diag::warn_cstruct_memaccess) 9791 << ArgIdx << FnName << PointeeTy << 0); 9792 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9793 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9794 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9795 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9796 PDiag(diag::warn_cstruct_memaccess) 9797 << ArgIdx << FnName << PointeeTy << 1); 9798 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9799 } else { 9800 continue; 9801 } 9802 } else 9803 continue; 9804 9805 DiagRuntimeBehavior( 9806 Dest->getExprLoc(), Dest, 9807 PDiag(diag::note_bad_memaccess_silence) 9808 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9809 break; 9810 } 9811 } 9812 9813 // A little helper routine: ignore addition and subtraction of integer literals. 9814 // This intentionally does not ignore all integer constant expressions because 9815 // we don't want to remove sizeof(). 9816 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9817 Ex = Ex->IgnoreParenCasts(); 9818 9819 while (true) { 9820 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9821 if (!BO || !BO->isAdditiveOp()) 9822 break; 9823 9824 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9825 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9826 9827 if (isa<IntegerLiteral>(RHS)) 9828 Ex = LHS; 9829 else if (isa<IntegerLiteral>(LHS)) 9830 Ex = RHS; 9831 else 9832 break; 9833 } 9834 9835 return Ex; 9836 } 9837 9838 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9839 ASTContext &Context) { 9840 // Only handle constant-sized or VLAs, but not flexible members. 9841 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9842 // Only issue the FIXIT for arrays of size > 1. 9843 if (CAT->getSize().getSExtValue() <= 1) 9844 return false; 9845 } else if (!Ty->isVariableArrayType()) { 9846 return false; 9847 } 9848 return true; 9849 } 9850 9851 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9852 // be the size of the source, instead of the destination. 9853 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9854 IdentifierInfo *FnName) { 9855 9856 // Don't crash if the user has the wrong number of arguments 9857 unsigned NumArgs = Call->getNumArgs(); 9858 if ((NumArgs != 3) && (NumArgs != 4)) 9859 return; 9860 9861 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9862 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9863 const Expr *CompareWithSrc = nullptr; 9864 9865 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9866 Call->getBeginLoc(), Call->getRParenLoc())) 9867 return; 9868 9869 // Look for 'strlcpy(dst, x, sizeof(x))' 9870 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9871 CompareWithSrc = Ex; 9872 else { 9873 // Look for 'strlcpy(dst, x, strlen(x))' 9874 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9875 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9876 SizeCall->getNumArgs() == 1) 9877 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9878 } 9879 } 9880 9881 if (!CompareWithSrc) 9882 return; 9883 9884 // Determine if the argument to sizeof/strlen is equal to the source 9885 // argument. In principle there's all kinds of things you could do 9886 // here, for instance creating an == expression and evaluating it with 9887 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9888 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9889 if (!SrcArgDRE) 9890 return; 9891 9892 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9893 if (!CompareWithSrcDRE || 9894 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9895 return; 9896 9897 const Expr *OriginalSizeArg = Call->getArg(2); 9898 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9899 << OriginalSizeArg->getSourceRange() << FnName; 9900 9901 // Output a FIXIT hint if the destination is an array (rather than a 9902 // pointer to an array). This could be enhanced to handle some 9903 // pointers if we know the actual size, like if DstArg is 'array+2' 9904 // we could say 'sizeof(array)-2'. 9905 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9906 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9907 return; 9908 9909 SmallString<128> sizeString; 9910 llvm::raw_svector_ostream OS(sizeString); 9911 OS << "sizeof("; 9912 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9913 OS << ")"; 9914 9915 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9916 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9917 OS.str()); 9918 } 9919 9920 /// Check if two expressions refer to the same declaration. 9921 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9922 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9923 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9924 return D1->getDecl() == D2->getDecl(); 9925 return false; 9926 } 9927 9928 static const Expr *getStrlenExprArg(const Expr *E) { 9929 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9930 const FunctionDecl *FD = CE->getDirectCallee(); 9931 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9932 return nullptr; 9933 return CE->getArg(0)->IgnoreParenCasts(); 9934 } 9935 return nullptr; 9936 } 9937 9938 // Warn on anti-patterns as the 'size' argument to strncat. 9939 // The correct size argument should look like following: 9940 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9941 void Sema::CheckStrncatArguments(const CallExpr *CE, 9942 IdentifierInfo *FnName) { 9943 // Don't crash if the user has the wrong number of arguments. 9944 if (CE->getNumArgs() < 3) 9945 return; 9946 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9947 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9948 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9949 9950 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9951 CE->getRParenLoc())) 9952 return; 9953 9954 // Identify common expressions, which are wrongly used as the size argument 9955 // to strncat and may lead to buffer overflows. 9956 unsigned PatternType = 0; 9957 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9958 // - sizeof(dst) 9959 if (referToTheSameDecl(SizeOfArg, DstArg)) 9960 PatternType = 1; 9961 // - sizeof(src) 9962 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9963 PatternType = 2; 9964 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9965 if (BE->getOpcode() == BO_Sub) { 9966 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9967 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9968 // - sizeof(dst) - strlen(dst) 9969 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9970 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9971 PatternType = 1; 9972 // - sizeof(src) - (anything) 9973 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9974 PatternType = 2; 9975 } 9976 } 9977 9978 if (PatternType == 0) 9979 return; 9980 9981 // Generate the diagnostic. 9982 SourceLocation SL = LenArg->getBeginLoc(); 9983 SourceRange SR = LenArg->getSourceRange(); 9984 SourceManager &SM = getSourceManager(); 9985 9986 // If the function is defined as a builtin macro, do not show macro expansion. 9987 if (SM.isMacroArgExpansion(SL)) { 9988 SL = SM.getSpellingLoc(SL); 9989 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9990 SM.getSpellingLoc(SR.getEnd())); 9991 } 9992 9993 // Check if the destination is an array (rather than a pointer to an array). 9994 QualType DstTy = DstArg->getType(); 9995 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9996 Context); 9997 if (!isKnownSizeArray) { 9998 if (PatternType == 1) 9999 Diag(SL, diag::warn_strncat_wrong_size) << SR; 10000 else 10001 Diag(SL, diag::warn_strncat_src_size) << SR; 10002 return; 10003 } 10004 10005 if (PatternType == 1) 10006 Diag(SL, diag::warn_strncat_large_size) << SR; 10007 else 10008 Diag(SL, diag::warn_strncat_src_size) << SR; 10009 10010 SmallString<128> sizeString; 10011 llvm::raw_svector_ostream OS(sizeString); 10012 OS << "sizeof("; 10013 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10014 OS << ") - "; 10015 OS << "strlen("; 10016 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 10017 OS << ") - 1"; 10018 10019 Diag(SL, diag::note_strncat_wrong_size) 10020 << FixItHint::CreateReplacement(SR, OS.str()); 10021 } 10022 10023 void 10024 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 10025 SourceLocation ReturnLoc, 10026 bool isObjCMethod, 10027 const AttrVec *Attrs, 10028 const FunctionDecl *FD) { 10029 // Check if the return value is null but should not be. 10030 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 10031 (!isObjCMethod && isNonNullType(Context, lhsType))) && 10032 CheckNonNullExpr(*this, RetValExp)) 10033 Diag(ReturnLoc, diag::warn_null_ret) 10034 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 10035 10036 // C++11 [basic.stc.dynamic.allocation]p4: 10037 // If an allocation function declared with a non-throwing 10038 // exception-specification fails to allocate storage, it shall return 10039 // a null pointer. Any other allocation function that fails to allocate 10040 // storage shall indicate failure only by throwing an exception [...] 10041 if (FD) { 10042 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 10043 if (Op == OO_New || Op == OO_Array_New) { 10044 const FunctionProtoType *Proto 10045 = FD->getType()->castAs<FunctionProtoType>(); 10046 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 10047 CheckNonNullExpr(*this, RetValExp)) 10048 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 10049 << FD << getLangOpts().CPlusPlus11; 10050 } 10051 } 10052 } 10053 10054 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 10055 10056 /// Check for comparisons of floating point operands using != and ==. 10057 /// Issue a warning if these are no self-comparisons, as they are not likely 10058 /// to do what the programmer intended. 10059 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 10060 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 10061 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 10062 10063 // Special case: check for x == x (which is OK). 10064 // Do not emit warnings for such cases. 10065 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 10066 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 10067 if (DRL->getDecl() == DRR->getDecl()) 10068 return; 10069 10070 // Special case: check for comparisons against literals that can be exactly 10071 // represented by APFloat. In such cases, do not emit a warning. This 10072 // is a heuristic: often comparison against such literals are used to 10073 // detect if a value in a variable has not changed. This clearly can 10074 // lead to false negatives. 10075 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 10076 if (FLL->isExact()) 10077 return; 10078 } else 10079 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 10080 if (FLR->isExact()) 10081 return; 10082 10083 // Check for comparisons with builtin types. 10084 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 10085 if (CL->getBuiltinCallee()) 10086 return; 10087 10088 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 10089 if (CR->getBuiltinCallee()) 10090 return; 10091 10092 // Emit the diagnostic. 10093 Diag(Loc, diag::warn_floatingpoint_eq) 10094 << LHS->getSourceRange() << RHS->getSourceRange(); 10095 } 10096 10097 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 10098 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 10099 10100 namespace { 10101 10102 /// Structure recording the 'active' range of an integer-valued 10103 /// expression. 10104 struct IntRange { 10105 /// The number of bits active in the int. 10106 unsigned Width; 10107 10108 /// True if the int is known not to have negative values. 10109 bool NonNegative; 10110 10111 IntRange(unsigned Width, bool NonNegative) 10112 : Width(Width), NonNegative(NonNegative) {} 10113 10114 /// Returns the range of the bool type. 10115 static IntRange forBoolType() { 10116 return IntRange(1, true); 10117 } 10118 10119 /// Returns the range of an opaque value of the given integral type. 10120 static IntRange forValueOfType(ASTContext &C, QualType T) { 10121 return forValueOfCanonicalType(C, 10122 T->getCanonicalTypeInternal().getTypePtr()); 10123 } 10124 10125 /// Returns the range of an opaque value of a canonical integral type. 10126 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 10127 assert(T->isCanonicalUnqualified()); 10128 10129 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10130 T = VT->getElementType().getTypePtr(); 10131 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10132 T = CT->getElementType().getTypePtr(); 10133 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10134 T = AT->getValueType().getTypePtr(); 10135 10136 if (!C.getLangOpts().CPlusPlus) { 10137 // For enum types in C code, use the underlying datatype. 10138 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10139 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 10140 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 10141 // For enum types in C++, use the known bit width of the enumerators. 10142 EnumDecl *Enum = ET->getDecl(); 10143 // In C++11, enums can have a fixed underlying type. Use this type to 10144 // compute the range. 10145 if (Enum->isFixed()) { 10146 return IntRange(C.getIntWidth(QualType(T, 0)), 10147 !ET->isSignedIntegerOrEnumerationType()); 10148 } 10149 10150 unsigned NumPositive = Enum->getNumPositiveBits(); 10151 unsigned NumNegative = Enum->getNumNegativeBits(); 10152 10153 if (NumNegative == 0) 10154 return IntRange(NumPositive, true/*NonNegative*/); 10155 else 10156 return IntRange(std::max(NumPositive + 1, NumNegative), 10157 false/*NonNegative*/); 10158 } 10159 10160 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10161 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10162 10163 const BuiltinType *BT = cast<BuiltinType>(T); 10164 assert(BT->isInteger()); 10165 10166 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10167 } 10168 10169 /// Returns the "target" range of a canonical integral type, i.e. 10170 /// the range of values expressible in the type. 10171 /// 10172 /// This matches forValueOfCanonicalType except that enums have the 10173 /// full range of their type, not the range of their enumerators. 10174 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 10175 assert(T->isCanonicalUnqualified()); 10176 10177 if (const VectorType *VT = dyn_cast<VectorType>(T)) 10178 T = VT->getElementType().getTypePtr(); 10179 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 10180 T = CT->getElementType().getTypePtr(); 10181 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 10182 T = AT->getValueType().getTypePtr(); 10183 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10184 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10185 10186 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10187 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10188 10189 const BuiltinType *BT = cast<BuiltinType>(T); 10190 assert(BT->isInteger()); 10191 10192 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10193 } 10194 10195 /// Returns the supremum of two ranges: i.e. their conservative merge. 10196 static IntRange join(IntRange L, IntRange R) { 10197 return IntRange(std::max(L.Width, R.Width), 10198 L.NonNegative && R.NonNegative); 10199 } 10200 10201 /// Returns the infinum of two ranges: i.e. their aggressive merge. 10202 static IntRange meet(IntRange L, IntRange R) { 10203 return IntRange(std::min(L.Width, R.Width), 10204 L.NonNegative || R.NonNegative); 10205 } 10206 }; 10207 10208 } // namespace 10209 10210 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10211 unsigned MaxWidth) { 10212 if (value.isSigned() && value.isNegative()) 10213 return IntRange(value.getMinSignedBits(), false); 10214 10215 if (value.getBitWidth() > MaxWidth) 10216 value = value.trunc(MaxWidth); 10217 10218 // isNonNegative() just checks the sign bit without considering 10219 // signedness. 10220 return IntRange(value.getActiveBits(), true); 10221 } 10222 10223 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10224 unsigned MaxWidth) { 10225 if (result.isInt()) 10226 return GetValueRange(C, result.getInt(), MaxWidth); 10227 10228 if (result.isVector()) { 10229 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10230 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10231 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10232 R = IntRange::join(R, El); 10233 } 10234 return R; 10235 } 10236 10237 if (result.isComplexInt()) { 10238 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10239 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10240 return IntRange::join(R, I); 10241 } 10242 10243 // This can happen with lossless casts to intptr_t of "based" lvalues. 10244 // Assume it might use arbitrary bits. 10245 // FIXME: The only reason we need to pass the type in here is to get 10246 // the sign right on this one case. It would be nice if APValue 10247 // preserved this. 10248 assert(result.isLValue() || result.isAddrLabelDiff()); 10249 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10250 } 10251 10252 static QualType GetExprType(const Expr *E) { 10253 QualType Ty = E->getType(); 10254 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10255 Ty = AtomicRHS->getValueType(); 10256 return Ty; 10257 } 10258 10259 /// Pseudo-evaluate the given integer expression, estimating the 10260 /// range of values it might take. 10261 /// 10262 /// \param MaxWidth - the width to which the value will be truncated 10263 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10264 bool InConstantContext) { 10265 E = E->IgnoreParens(); 10266 10267 // Try a full evaluation first. 10268 Expr::EvalResult result; 10269 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10270 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10271 10272 // I think we only want to look through implicit casts here; if the 10273 // user has an explicit widening cast, we should treat the value as 10274 // being of the new, wider type. 10275 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10276 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10277 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 10278 10279 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10280 10281 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10282 CE->getCastKind() == CK_BooleanToSignedIntegral; 10283 10284 // Assume that non-integer casts can span the full range of the type. 10285 if (!isIntegerCast) 10286 return OutputTypeRange; 10287 10288 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10289 std::min(MaxWidth, OutputTypeRange.Width), 10290 InConstantContext); 10291 10292 // Bail out if the subexpr's range is as wide as the cast type. 10293 if (SubRange.Width >= OutputTypeRange.Width) 10294 return OutputTypeRange; 10295 10296 // Otherwise, we take the smaller width, and we're non-negative if 10297 // either the output type or the subexpr is. 10298 return IntRange(SubRange.Width, 10299 SubRange.NonNegative || OutputTypeRange.NonNegative); 10300 } 10301 10302 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10303 // If we can fold the condition, just take that operand. 10304 bool CondResult; 10305 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10306 return GetExprRange(C, 10307 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10308 MaxWidth, InConstantContext); 10309 10310 // Otherwise, conservatively merge. 10311 IntRange L = 10312 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 10313 IntRange R = 10314 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 10315 return IntRange::join(L, R); 10316 } 10317 10318 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10319 switch (BO->getOpcode()) { 10320 case BO_Cmp: 10321 llvm_unreachable("builtin <=> should have class type"); 10322 10323 // Boolean-valued operations are single-bit and positive. 10324 case BO_LAnd: 10325 case BO_LOr: 10326 case BO_LT: 10327 case BO_GT: 10328 case BO_LE: 10329 case BO_GE: 10330 case BO_EQ: 10331 case BO_NE: 10332 return IntRange::forBoolType(); 10333 10334 // The type of the assignments is the type of the LHS, so the RHS 10335 // is not necessarily the same type. 10336 case BO_MulAssign: 10337 case BO_DivAssign: 10338 case BO_RemAssign: 10339 case BO_AddAssign: 10340 case BO_SubAssign: 10341 case BO_XorAssign: 10342 case BO_OrAssign: 10343 // TODO: bitfields? 10344 return IntRange::forValueOfType(C, GetExprType(E)); 10345 10346 // Simple assignments just pass through the RHS, which will have 10347 // been coerced to the LHS type. 10348 case BO_Assign: 10349 // TODO: bitfields? 10350 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10351 10352 // Operations with opaque sources are black-listed. 10353 case BO_PtrMemD: 10354 case BO_PtrMemI: 10355 return IntRange::forValueOfType(C, GetExprType(E)); 10356 10357 // Bitwise-and uses the *infinum* of the two source ranges. 10358 case BO_And: 10359 case BO_AndAssign: 10360 return IntRange::meet( 10361 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 10362 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 10363 10364 // Left shift gets black-listed based on a judgement call. 10365 case BO_Shl: 10366 // ...except that we want to treat '1 << (blah)' as logically 10367 // positive. It's an important idiom. 10368 if (IntegerLiteral *I 10369 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10370 if (I->getValue() == 1) { 10371 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10372 return IntRange(R.Width, /*NonNegative*/ true); 10373 } 10374 } 10375 LLVM_FALLTHROUGH; 10376 10377 case BO_ShlAssign: 10378 return IntRange::forValueOfType(C, GetExprType(E)); 10379 10380 // Right shift by a constant can narrow its left argument. 10381 case BO_Shr: 10382 case BO_ShrAssign: { 10383 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10384 10385 // If the shift amount is a positive constant, drop the width by 10386 // that much. 10387 if (Optional<llvm::APSInt> shift = 10388 BO->getRHS()->getIntegerConstantExpr(C)) { 10389 if (shift->isNonNegative()) { 10390 unsigned zext = shift->getZExtValue(); 10391 if (zext >= L.Width) 10392 L.Width = (L.NonNegative ? 0 : 1); 10393 else 10394 L.Width -= zext; 10395 } 10396 } 10397 10398 return L; 10399 } 10400 10401 // Comma acts as its right operand. 10402 case BO_Comma: 10403 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10404 10405 // Black-list pointer subtractions. 10406 case BO_Sub: 10407 if (BO->getLHS()->getType()->isPointerType()) 10408 return IntRange::forValueOfType(C, GetExprType(E)); 10409 break; 10410 10411 // The width of a division result is mostly determined by the size 10412 // of the LHS. 10413 case BO_Div: { 10414 // Don't 'pre-truncate' the operands. 10415 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10416 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10417 10418 // If the divisor is constant, use that. 10419 if (Optional<llvm::APSInt> divisor = 10420 BO->getRHS()->getIntegerConstantExpr(C)) { 10421 unsigned log2 = divisor->logBase2(); // floor(log_2(divisor)) 10422 if (log2 >= L.Width) 10423 L.Width = (L.NonNegative ? 0 : 1); 10424 else 10425 L.Width = std::min(L.Width - log2, MaxWidth); 10426 return L; 10427 } 10428 10429 // Otherwise, just use the LHS's width. 10430 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10431 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10432 } 10433 10434 // The result of a remainder can't be larger than the result of 10435 // either side. 10436 case BO_Rem: { 10437 // Don't 'pre-truncate' the operands. 10438 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10439 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10440 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10441 10442 IntRange meet = IntRange::meet(L, R); 10443 meet.Width = std::min(meet.Width, MaxWidth); 10444 return meet; 10445 } 10446 10447 // The default behavior is okay for these. 10448 case BO_Mul: 10449 case BO_Add: 10450 case BO_Xor: 10451 case BO_Or: 10452 break; 10453 } 10454 10455 // The default case is to treat the operation as if it were closed 10456 // on the narrowest type that encompasses both operands. 10457 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10458 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10459 return IntRange::join(L, R); 10460 } 10461 10462 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10463 switch (UO->getOpcode()) { 10464 // Boolean-valued operations are white-listed. 10465 case UO_LNot: 10466 return IntRange::forBoolType(); 10467 10468 // Operations with opaque sources are black-listed. 10469 case UO_Deref: 10470 case UO_AddrOf: // should be impossible 10471 return IntRange::forValueOfType(C, GetExprType(E)); 10472 10473 default: 10474 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10475 } 10476 } 10477 10478 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10479 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10480 10481 if (const auto *BitField = E->getSourceBitField()) 10482 return IntRange(BitField->getBitWidthValue(C), 10483 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10484 10485 return IntRange::forValueOfType(C, GetExprType(E)); 10486 } 10487 10488 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10489 bool InConstantContext) { 10490 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10491 } 10492 10493 /// Checks whether the given value, which currently has the given 10494 /// source semantics, has the same value when coerced through the 10495 /// target semantics. 10496 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10497 const llvm::fltSemantics &Src, 10498 const llvm::fltSemantics &Tgt) { 10499 llvm::APFloat truncated = value; 10500 10501 bool ignored; 10502 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10503 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10504 10505 return truncated.bitwiseIsEqual(value); 10506 } 10507 10508 /// Checks whether the given value, which currently has the given 10509 /// source semantics, has the same value when coerced through the 10510 /// target semantics. 10511 /// 10512 /// The value might be a vector of floats (or a complex number). 10513 static bool IsSameFloatAfterCast(const APValue &value, 10514 const llvm::fltSemantics &Src, 10515 const llvm::fltSemantics &Tgt) { 10516 if (value.isFloat()) 10517 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10518 10519 if (value.isVector()) { 10520 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10521 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10522 return false; 10523 return true; 10524 } 10525 10526 assert(value.isComplexFloat()); 10527 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10528 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10529 } 10530 10531 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10532 bool IsListInit = false); 10533 10534 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10535 // Suppress cases where we are comparing against an enum constant. 10536 if (const DeclRefExpr *DR = 10537 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10538 if (isa<EnumConstantDecl>(DR->getDecl())) 10539 return true; 10540 10541 // Suppress cases where the value is expanded from a macro, unless that macro 10542 // is how a language represents a boolean literal. This is the case in both C 10543 // and Objective-C. 10544 SourceLocation BeginLoc = E->getBeginLoc(); 10545 if (BeginLoc.isMacroID()) { 10546 StringRef MacroName = Lexer::getImmediateMacroName( 10547 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10548 return MacroName != "YES" && MacroName != "NO" && 10549 MacroName != "true" && MacroName != "false"; 10550 } 10551 10552 return false; 10553 } 10554 10555 static bool isKnownToHaveUnsignedValue(Expr *E) { 10556 return E->getType()->isIntegerType() && 10557 (!E->getType()->isSignedIntegerType() || 10558 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10559 } 10560 10561 namespace { 10562 /// The promoted range of values of a type. In general this has the 10563 /// following structure: 10564 /// 10565 /// |-----------| . . . |-----------| 10566 /// ^ ^ ^ ^ 10567 /// Min HoleMin HoleMax Max 10568 /// 10569 /// ... where there is only a hole if a signed type is promoted to unsigned 10570 /// (in which case Min and Max are the smallest and largest representable 10571 /// values). 10572 struct PromotedRange { 10573 // Min, or HoleMax if there is a hole. 10574 llvm::APSInt PromotedMin; 10575 // Max, or HoleMin if there is a hole. 10576 llvm::APSInt PromotedMax; 10577 10578 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10579 if (R.Width == 0) 10580 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10581 else if (R.Width >= BitWidth && !Unsigned) { 10582 // Promotion made the type *narrower*. This happens when promoting 10583 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10584 // Treat all values of 'signed int' as being in range for now. 10585 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10586 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10587 } else { 10588 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10589 .extOrTrunc(BitWidth); 10590 PromotedMin.setIsUnsigned(Unsigned); 10591 10592 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10593 .extOrTrunc(BitWidth); 10594 PromotedMax.setIsUnsigned(Unsigned); 10595 } 10596 } 10597 10598 // Determine whether this range is contiguous (has no hole). 10599 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10600 10601 // Where a constant value is within the range. 10602 enum ComparisonResult { 10603 LT = 0x1, 10604 LE = 0x2, 10605 GT = 0x4, 10606 GE = 0x8, 10607 EQ = 0x10, 10608 NE = 0x20, 10609 InRangeFlag = 0x40, 10610 10611 Less = LE | LT | NE, 10612 Min = LE | InRangeFlag, 10613 InRange = InRangeFlag, 10614 Max = GE | InRangeFlag, 10615 Greater = GE | GT | NE, 10616 10617 OnlyValue = LE | GE | EQ | InRangeFlag, 10618 InHole = NE 10619 }; 10620 10621 ComparisonResult compare(const llvm::APSInt &Value) const { 10622 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10623 Value.isUnsigned() == PromotedMin.isUnsigned()); 10624 if (!isContiguous()) { 10625 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10626 if (Value.isMinValue()) return Min; 10627 if (Value.isMaxValue()) return Max; 10628 if (Value >= PromotedMin) return InRange; 10629 if (Value <= PromotedMax) return InRange; 10630 return InHole; 10631 } 10632 10633 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10634 case -1: return Less; 10635 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10636 case 1: 10637 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10638 case -1: return InRange; 10639 case 0: return Max; 10640 case 1: return Greater; 10641 } 10642 } 10643 10644 llvm_unreachable("impossible compare result"); 10645 } 10646 10647 static llvm::Optional<StringRef> 10648 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10649 if (Op == BO_Cmp) { 10650 ComparisonResult LTFlag = LT, GTFlag = GT; 10651 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10652 10653 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10654 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10655 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10656 return llvm::None; 10657 } 10658 10659 ComparisonResult TrueFlag, FalseFlag; 10660 if (Op == BO_EQ) { 10661 TrueFlag = EQ; 10662 FalseFlag = NE; 10663 } else if (Op == BO_NE) { 10664 TrueFlag = NE; 10665 FalseFlag = EQ; 10666 } else { 10667 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10668 TrueFlag = LT; 10669 FalseFlag = GE; 10670 } else { 10671 TrueFlag = GT; 10672 FalseFlag = LE; 10673 } 10674 if (Op == BO_GE || Op == BO_LE) 10675 std::swap(TrueFlag, FalseFlag); 10676 } 10677 if (R & TrueFlag) 10678 return StringRef("true"); 10679 if (R & FalseFlag) 10680 return StringRef("false"); 10681 return llvm::None; 10682 } 10683 }; 10684 } 10685 10686 static bool HasEnumType(Expr *E) { 10687 // Strip off implicit integral promotions. 10688 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10689 if (ICE->getCastKind() != CK_IntegralCast && 10690 ICE->getCastKind() != CK_NoOp) 10691 break; 10692 E = ICE->getSubExpr(); 10693 } 10694 10695 return E->getType()->isEnumeralType(); 10696 } 10697 10698 static int classifyConstantValue(Expr *Constant) { 10699 // The values of this enumeration are used in the diagnostics 10700 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10701 enum ConstantValueKind { 10702 Miscellaneous = 0, 10703 LiteralTrue, 10704 LiteralFalse 10705 }; 10706 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10707 return BL->getValue() ? ConstantValueKind::LiteralTrue 10708 : ConstantValueKind::LiteralFalse; 10709 return ConstantValueKind::Miscellaneous; 10710 } 10711 10712 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10713 Expr *Constant, Expr *Other, 10714 const llvm::APSInt &Value, 10715 bool RhsConstant) { 10716 if (S.inTemplateInstantiation()) 10717 return false; 10718 10719 Expr *OriginalOther = Other; 10720 10721 Constant = Constant->IgnoreParenImpCasts(); 10722 Other = Other->IgnoreParenImpCasts(); 10723 10724 // Suppress warnings on tautological comparisons between values of the same 10725 // enumeration type. There are only two ways we could warn on this: 10726 // - If the constant is outside the range of representable values of 10727 // the enumeration. In such a case, we should warn about the cast 10728 // to enumeration type, not about the comparison. 10729 // - If the constant is the maximum / minimum in-range value. For an 10730 // enumeratin type, such comparisons can be meaningful and useful. 10731 if (Constant->getType()->isEnumeralType() && 10732 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10733 return false; 10734 10735 // TODO: Investigate using GetExprRange() to get tighter bounds 10736 // on the bit ranges. 10737 QualType OtherT = Other->getType(); 10738 if (const auto *AT = OtherT->getAs<AtomicType>()) 10739 OtherT = AT->getValueType(); 10740 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10741 10742 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10743 // (Namely, macOS). 10744 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10745 S.NSAPIObj->isObjCBOOLType(OtherT) && 10746 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10747 10748 // Whether we're treating Other as being a bool because of the form of 10749 // expression despite it having another type (typically 'int' in C). 10750 bool OtherIsBooleanDespiteType = 10751 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10752 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10753 OtherRange = IntRange::forBoolType(); 10754 10755 // Determine the promoted range of the other type and see if a comparison of 10756 // the constant against that range is tautological. 10757 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10758 Value.isUnsigned()); 10759 auto Cmp = OtherPromotedRange.compare(Value); 10760 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10761 if (!Result) 10762 return false; 10763 10764 // Suppress the diagnostic for an in-range comparison if the constant comes 10765 // from a macro or enumerator. We don't want to diagnose 10766 // 10767 // some_long_value <= INT_MAX 10768 // 10769 // when sizeof(int) == sizeof(long). 10770 bool InRange = Cmp & PromotedRange::InRangeFlag; 10771 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10772 return false; 10773 10774 // If this is a comparison to an enum constant, include that 10775 // constant in the diagnostic. 10776 const EnumConstantDecl *ED = nullptr; 10777 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10778 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10779 10780 // Should be enough for uint128 (39 decimal digits) 10781 SmallString<64> PrettySourceValue; 10782 llvm::raw_svector_ostream OS(PrettySourceValue); 10783 if (ED) { 10784 OS << '\'' << *ED << "' (" << Value << ")"; 10785 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10786 Constant->IgnoreParenImpCasts())) { 10787 OS << (BL->getValue() ? "YES" : "NO"); 10788 } else { 10789 OS << Value; 10790 } 10791 10792 if (IsObjCSignedCharBool) { 10793 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10794 S.PDiag(diag::warn_tautological_compare_objc_bool) 10795 << OS.str() << *Result); 10796 return true; 10797 } 10798 10799 // FIXME: We use a somewhat different formatting for the in-range cases and 10800 // cases involving boolean values for historical reasons. We should pick a 10801 // consistent way of presenting these diagnostics. 10802 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10803 10804 S.DiagRuntimeBehavior( 10805 E->getOperatorLoc(), E, 10806 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10807 : diag::warn_tautological_bool_compare) 10808 << OS.str() << classifyConstantValue(Constant) << OtherT 10809 << OtherIsBooleanDespiteType << *Result 10810 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10811 } else { 10812 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10813 ? (HasEnumType(OriginalOther) 10814 ? diag::warn_unsigned_enum_always_true_comparison 10815 : diag::warn_unsigned_always_true_comparison) 10816 : diag::warn_tautological_constant_compare; 10817 10818 S.Diag(E->getOperatorLoc(), Diag) 10819 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10820 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10821 } 10822 10823 return true; 10824 } 10825 10826 /// Analyze the operands of the given comparison. Implements the 10827 /// fallback case from AnalyzeComparison. 10828 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10829 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10830 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10831 } 10832 10833 /// Implements -Wsign-compare. 10834 /// 10835 /// \param E the binary operator to check for warnings 10836 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10837 // The type the comparison is being performed in. 10838 QualType T = E->getLHS()->getType(); 10839 10840 // Only analyze comparison operators where both sides have been converted to 10841 // the same type. 10842 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10843 return AnalyzeImpConvsInComparison(S, E); 10844 10845 // Don't analyze value-dependent comparisons directly. 10846 if (E->isValueDependent()) 10847 return AnalyzeImpConvsInComparison(S, E); 10848 10849 Expr *LHS = E->getLHS(); 10850 Expr *RHS = E->getRHS(); 10851 10852 if (T->isIntegralType(S.Context)) { 10853 Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context); 10854 Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context); 10855 10856 // We don't care about expressions whose result is a constant. 10857 if (RHSValue && LHSValue) 10858 return AnalyzeImpConvsInComparison(S, E); 10859 10860 // We only care about expressions where just one side is literal 10861 if ((bool)RHSValue ^ (bool)LHSValue) { 10862 // Is the constant on the RHS or LHS? 10863 const bool RhsConstant = (bool)RHSValue; 10864 Expr *Const = RhsConstant ? RHS : LHS; 10865 Expr *Other = RhsConstant ? LHS : RHS; 10866 const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue; 10867 10868 // Check whether an integer constant comparison results in a value 10869 // of 'true' or 'false'. 10870 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10871 return AnalyzeImpConvsInComparison(S, E); 10872 } 10873 } 10874 10875 if (!T->hasUnsignedIntegerRepresentation()) { 10876 // We don't do anything special if this isn't an unsigned integral 10877 // comparison: we're only interested in integral comparisons, and 10878 // signed comparisons only happen in cases we don't care to warn about. 10879 return AnalyzeImpConvsInComparison(S, E); 10880 } 10881 10882 LHS = LHS->IgnoreParenImpCasts(); 10883 RHS = RHS->IgnoreParenImpCasts(); 10884 10885 if (!S.getLangOpts().CPlusPlus) { 10886 // Avoid warning about comparison of integers with different signs when 10887 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10888 // the type of `E`. 10889 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10890 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10891 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10892 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10893 } 10894 10895 // Check to see if one of the (unmodified) operands is of different 10896 // signedness. 10897 Expr *signedOperand, *unsignedOperand; 10898 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10899 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10900 "unsigned comparison between two signed integer expressions?"); 10901 signedOperand = LHS; 10902 unsignedOperand = RHS; 10903 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10904 signedOperand = RHS; 10905 unsignedOperand = LHS; 10906 } else { 10907 return AnalyzeImpConvsInComparison(S, E); 10908 } 10909 10910 // Otherwise, calculate the effective range of the signed operand. 10911 IntRange signedRange = 10912 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10913 10914 // Go ahead and analyze implicit conversions in the operands. Note 10915 // that we skip the implicit conversions on both sides. 10916 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10917 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10918 10919 // If the signed range is non-negative, -Wsign-compare won't fire. 10920 if (signedRange.NonNegative) 10921 return; 10922 10923 // For (in)equality comparisons, if the unsigned operand is a 10924 // constant which cannot collide with a overflowed signed operand, 10925 // then reinterpreting the signed operand as unsigned will not 10926 // change the result of the comparison. 10927 if (E->isEqualityOp()) { 10928 unsigned comparisonWidth = S.Context.getIntWidth(T); 10929 IntRange unsignedRange = 10930 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10931 10932 // We should never be unable to prove that the unsigned operand is 10933 // non-negative. 10934 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10935 10936 if (unsignedRange.Width < comparisonWidth) 10937 return; 10938 } 10939 10940 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10941 S.PDiag(diag::warn_mixed_sign_comparison) 10942 << LHS->getType() << RHS->getType() 10943 << LHS->getSourceRange() << RHS->getSourceRange()); 10944 } 10945 10946 /// Analyzes an attempt to assign the given value to a bitfield. 10947 /// 10948 /// Returns true if there was something fishy about the attempt. 10949 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10950 SourceLocation InitLoc) { 10951 assert(Bitfield->isBitField()); 10952 if (Bitfield->isInvalidDecl()) 10953 return false; 10954 10955 // White-list bool bitfields. 10956 QualType BitfieldType = Bitfield->getType(); 10957 if (BitfieldType->isBooleanType()) 10958 return false; 10959 10960 if (BitfieldType->isEnumeralType()) { 10961 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 10962 // If the underlying enum type was not explicitly specified as an unsigned 10963 // type and the enum contain only positive values, MSVC++ will cause an 10964 // inconsistency by storing this as a signed type. 10965 if (S.getLangOpts().CPlusPlus11 && 10966 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10967 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10968 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10969 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10970 << BitfieldEnumDecl->getNameAsString(); 10971 } 10972 } 10973 10974 if (Bitfield->getType()->isBooleanType()) 10975 return false; 10976 10977 // Ignore value- or type-dependent expressions. 10978 if (Bitfield->getBitWidth()->isValueDependent() || 10979 Bitfield->getBitWidth()->isTypeDependent() || 10980 Init->isValueDependent() || 10981 Init->isTypeDependent()) 10982 return false; 10983 10984 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10985 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10986 10987 Expr::EvalResult Result; 10988 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10989 Expr::SE_AllowSideEffects)) { 10990 // The RHS is not constant. If the RHS has an enum type, make sure the 10991 // bitfield is wide enough to hold all the values of the enum without 10992 // truncation. 10993 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10994 EnumDecl *ED = EnumTy->getDecl(); 10995 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10996 10997 // Enum types are implicitly signed on Windows, so check if there are any 10998 // negative enumerators to see if the enum was intended to be signed or 10999 // not. 11000 bool SignedEnum = ED->getNumNegativeBits() > 0; 11001 11002 // Check for surprising sign changes when assigning enum values to a 11003 // bitfield of different signedness. If the bitfield is signed and we 11004 // have exactly the right number of bits to store this unsigned enum, 11005 // suggest changing the enum to an unsigned type. This typically happens 11006 // on Windows where unfixed enums always use an underlying type of 'int'. 11007 unsigned DiagID = 0; 11008 if (SignedEnum && !SignedBitfield) { 11009 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 11010 } else if (SignedBitfield && !SignedEnum && 11011 ED->getNumPositiveBits() == FieldWidth) { 11012 DiagID = diag::warn_signed_bitfield_enum_conversion; 11013 } 11014 11015 if (DiagID) { 11016 S.Diag(InitLoc, DiagID) << Bitfield << ED; 11017 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 11018 SourceRange TypeRange = 11019 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 11020 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 11021 << SignedEnum << TypeRange; 11022 } 11023 11024 // Compute the required bitwidth. If the enum has negative values, we need 11025 // one more bit than the normal number of positive bits to represent the 11026 // sign bit. 11027 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 11028 ED->getNumNegativeBits()) 11029 : ED->getNumPositiveBits(); 11030 11031 // Check the bitwidth. 11032 if (BitsNeeded > FieldWidth) { 11033 Expr *WidthExpr = Bitfield->getBitWidth(); 11034 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 11035 << Bitfield << ED; 11036 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 11037 << BitsNeeded << ED << WidthExpr->getSourceRange(); 11038 } 11039 } 11040 11041 return false; 11042 } 11043 11044 llvm::APSInt Value = Result.Val.getInt(); 11045 11046 unsigned OriginalWidth = Value.getBitWidth(); 11047 11048 if (!Value.isSigned() || Value.isNegative()) 11049 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 11050 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 11051 OriginalWidth = Value.getMinSignedBits(); 11052 11053 if (OriginalWidth <= FieldWidth) 11054 return false; 11055 11056 // Compute the value which the bitfield will contain. 11057 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 11058 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 11059 11060 // Check whether the stored value is equal to the original value. 11061 TruncatedValue = TruncatedValue.extend(OriginalWidth); 11062 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 11063 return false; 11064 11065 // Special-case bitfields of width 1: booleans are naturally 0/1, and 11066 // therefore don't strictly fit into a signed bitfield of width 1. 11067 if (FieldWidth == 1 && Value == 1) 11068 return false; 11069 11070 std::string PrettyValue = Value.toString(10); 11071 std::string PrettyTrunc = TruncatedValue.toString(10); 11072 11073 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 11074 << PrettyValue << PrettyTrunc << OriginalInit->getType() 11075 << Init->getSourceRange(); 11076 11077 return true; 11078 } 11079 11080 /// Analyze the given simple or compound assignment for warning-worthy 11081 /// operations. 11082 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 11083 // Just recurse on the LHS. 11084 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11085 11086 // We want to recurse on the RHS as normal unless we're assigning to 11087 // a bitfield. 11088 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 11089 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 11090 E->getOperatorLoc())) { 11091 // Recurse, ignoring any implicit conversions on the RHS. 11092 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 11093 E->getOperatorLoc()); 11094 } 11095 } 11096 11097 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11098 11099 // Diagnose implicitly sequentially-consistent atomic assignment. 11100 if (E->getLHS()->getType()->isAtomicType()) 11101 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11102 } 11103 11104 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11105 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 11106 SourceLocation CContext, unsigned diag, 11107 bool pruneControlFlow = false) { 11108 if (pruneControlFlow) { 11109 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11110 S.PDiag(diag) 11111 << SourceType << T << E->getSourceRange() 11112 << SourceRange(CContext)); 11113 return; 11114 } 11115 S.Diag(E->getExprLoc(), diag) 11116 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 11117 } 11118 11119 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 11120 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 11121 SourceLocation CContext, 11122 unsigned diag, bool pruneControlFlow = false) { 11123 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 11124 } 11125 11126 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 11127 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 11128 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 11129 } 11130 11131 static void adornObjCBoolConversionDiagWithTernaryFixit( 11132 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 11133 Expr *Ignored = SourceExpr->IgnoreImplicit(); 11134 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 11135 Ignored = OVE->getSourceExpr(); 11136 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 11137 isa<BinaryOperator>(Ignored) || 11138 isa<CXXOperatorCallExpr>(Ignored); 11139 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 11140 if (NeedsParens) 11141 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 11142 << FixItHint::CreateInsertion(EndLoc, ")"); 11143 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 11144 } 11145 11146 /// Diagnose an implicit cast from a floating point value to an integer value. 11147 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 11148 SourceLocation CContext) { 11149 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 11150 const bool PruneWarnings = S.inTemplateInstantiation(); 11151 11152 Expr *InnerE = E->IgnoreParenImpCasts(); 11153 // We also want to warn on, e.g., "int i = -1.234" 11154 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 11155 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 11156 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 11157 11158 const bool IsLiteral = 11159 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 11160 11161 llvm::APFloat Value(0.0); 11162 bool IsConstant = 11163 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 11164 if (!IsConstant) { 11165 if (isObjCSignedCharBool(S, T)) { 11166 return adornObjCBoolConversionDiagWithTernaryFixit( 11167 S, E, 11168 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 11169 << E->getType()); 11170 } 11171 11172 return DiagnoseImpCast(S, E, T, CContext, 11173 diag::warn_impcast_float_integer, PruneWarnings); 11174 } 11175 11176 bool isExact = false; 11177 11178 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 11179 T->hasUnsignedIntegerRepresentation()); 11180 llvm::APFloat::opStatus Result = Value.convertToInteger( 11181 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11182 11183 // FIXME: Force the precision of the source value down so we don't print 11184 // digits which are usually useless (we don't really care here if we 11185 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11186 // would automatically print the shortest representation, but it's a bit 11187 // tricky to implement. 11188 SmallString<16> PrettySourceValue; 11189 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11190 precision = (precision * 59 + 195) / 196; 11191 Value.toString(PrettySourceValue, precision); 11192 11193 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11194 return adornObjCBoolConversionDiagWithTernaryFixit( 11195 S, E, 11196 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11197 << PrettySourceValue); 11198 } 11199 11200 if (Result == llvm::APFloat::opOK && isExact) { 11201 if (IsLiteral) return; 11202 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11203 PruneWarnings); 11204 } 11205 11206 // Conversion of a floating-point value to a non-bool integer where the 11207 // integral part cannot be represented by the integer type is undefined. 11208 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11209 return DiagnoseImpCast( 11210 S, E, T, CContext, 11211 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11212 : diag::warn_impcast_float_to_integer_out_of_range, 11213 PruneWarnings); 11214 11215 unsigned DiagID = 0; 11216 if (IsLiteral) { 11217 // Warn on floating point literal to integer. 11218 DiagID = diag::warn_impcast_literal_float_to_integer; 11219 } else if (IntegerValue == 0) { 11220 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11221 return DiagnoseImpCast(S, E, T, CContext, 11222 diag::warn_impcast_float_integer, PruneWarnings); 11223 } 11224 // Warn on non-zero to zero conversion. 11225 DiagID = diag::warn_impcast_float_to_integer_zero; 11226 } else { 11227 if (IntegerValue.isUnsigned()) { 11228 if (!IntegerValue.isMaxValue()) { 11229 return DiagnoseImpCast(S, E, T, CContext, 11230 diag::warn_impcast_float_integer, PruneWarnings); 11231 } 11232 } else { // IntegerValue.isSigned() 11233 if (!IntegerValue.isMaxSignedValue() && 11234 !IntegerValue.isMinSignedValue()) { 11235 return DiagnoseImpCast(S, E, T, CContext, 11236 diag::warn_impcast_float_integer, PruneWarnings); 11237 } 11238 } 11239 // Warn on evaluatable floating point expression to integer conversion. 11240 DiagID = diag::warn_impcast_float_to_integer; 11241 } 11242 11243 SmallString<16> PrettyTargetValue; 11244 if (IsBool) 11245 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11246 else 11247 IntegerValue.toString(PrettyTargetValue); 11248 11249 if (PruneWarnings) { 11250 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11251 S.PDiag(DiagID) 11252 << E->getType() << T.getUnqualifiedType() 11253 << PrettySourceValue << PrettyTargetValue 11254 << E->getSourceRange() << SourceRange(CContext)); 11255 } else { 11256 S.Diag(E->getExprLoc(), DiagID) 11257 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11258 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11259 } 11260 } 11261 11262 /// Analyze the given compound assignment for the possible losing of 11263 /// floating-point precision. 11264 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11265 assert(isa<CompoundAssignOperator>(E) && 11266 "Must be compound assignment operation"); 11267 // Recurse on the LHS and RHS in here 11268 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11269 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11270 11271 if (E->getLHS()->getType()->isAtomicType()) 11272 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11273 11274 // Now check the outermost expression 11275 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11276 const auto *RBT = cast<CompoundAssignOperator>(E) 11277 ->getComputationResultType() 11278 ->getAs<BuiltinType>(); 11279 11280 // The below checks assume source is floating point. 11281 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11282 11283 // If source is floating point but target is an integer. 11284 if (ResultBT->isInteger()) 11285 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11286 E->getExprLoc(), diag::warn_impcast_float_integer); 11287 11288 if (!ResultBT->isFloatingPoint()) 11289 return; 11290 11291 // If both source and target are floating points, warn about losing precision. 11292 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11293 QualType(ResultBT, 0), QualType(RBT, 0)); 11294 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11295 // warn about dropping FP rank. 11296 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11297 diag::warn_impcast_float_result_precision); 11298 } 11299 11300 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11301 IntRange Range) { 11302 if (!Range.Width) return "0"; 11303 11304 llvm::APSInt ValueInRange = Value; 11305 ValueInRange.setIsSigned(!Range.NonNegative); 11306 ValueInRange = ValueInRange.trunc(Range.Width); 11307 return ValueInRange.toString(10); 11308 } 11309 11310 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11311 if (!isa<ImplicitCastExpr>(Ex)) 11312 return false; 11313 11314 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11315 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11316 const Type *Source = 11317 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11318 if (Target->isDependentType()) 11319 return false; 11320 11321 const BuiltinType *FloatCandidateBT = 11322 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11323 const Type *BoolCandidateType = ToBool ? Target : Source; 11324 11325 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11326 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11327 } 11328 11329 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11330 SourceLocation CC) { 11331 unsigned NumArgs = TheCall->getNumArgs(); 11332 for (unsigned i = 0; i < NumArgs; ++i) { 11333 Expr *CurrA = TheCall->getArg(i); 11334 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11335 continue; 11336 11337 bool IsSwapped = ((i > 0) && 11338 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11339 IsSwapped |= ((i < (NumArgs - 1)) && 11340 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11341 if (IsSwapped) { 11342 // Warn on this floating-point to bool conversion. 11343 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11344 CurrA->getType(), CC, 11345 diag::warn_impcast_floating_point_to_bool); 11346 } 11347 } 11348 } 11349 11350 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11351 SourceLocation CC) { 11352 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11353 E->getExprLoc())) 11354 return; 11355 11356 // Don't warn on functions which have return type nullptr_t. 11357 if (isa<CallExpr>(E)) 11358 return; 11359 11360 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11361 const Expr::NullPointerConstantKind NullKind = 11362 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11363 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11364 return; 11365 11366 // Return if target type is a safe conversion. 11367 if (T->isAnyPointerType() || T->isBlockPointerType() || 11368 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11369 return; 11370 11371 SourceLocation Loc = E->getSourceRange().getBegin(); 11372 11373 // Venture through the macro stacks to get to the source of macro arguments. 11374 // The new location is a better location than the complete location that was 11375 // passed in. 11376 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11377 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11378 11379 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11380 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11381 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11382 Loc, S.SourceMgr, S.getLangOpts()); 11383 if (MacroName == "NULL") 11384 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11385 } 11386 11387 // Only warn if the null and context location are in the same macro expansion. 11388 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11389 return; 11390 11391 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11392 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11393 << FixItHint::CreateReplacement(Loc, 11394 S.getFixItZeroLiteralForType(T, Loc)); 11395 } 11396 11397 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11398 ObjCArrayLiteral *ArrayLiteral); 11399 11400 static void 11401 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11402 ObjCDictionaryLiteral *DictionaryLiteral); 11403 11404 /// Check a single element within a collection literal against the 11405 /// target element type. 11406 static void checkObjCCollectionLiteralElement(Sema &S, 11407 QualType TargetElementType, 11408 Expr *Element, 11409 unsigned ElementKind) { 11410 // Skip a bitcast to 'id' or qualified 'id'. 11411 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11412 if (ICE->getCastKind() == CK_BitCast && 11413 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11414 Element = ICE->getSubExpr(); 11415 } 11416 11417 QualType ElementType = Element->getType(); 11418 ExprResult ElementResult(Element); 11419 if (ElementType->getAs<ObjCObjectPointerType>() && 11420 S.CheckSingleAssignmentConstraints(TargetElementType, 11421 ElementResult, 11422 false, false) 11423 != Sema::Compatible) { 11424 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11425 << ElementType << ElementKind << TargetElementType 11426 << Element->getSourceRange(); 11427 } 11428 11429 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11430 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11431 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11432 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11433 } 11434 11435 /// Check an Objective-C array literal being converted to the given 11436 /// target type. 11437 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11438 ObjCArrayLiteral *ArrayLiteral) { 11439 if (!S.NSArrayDecl) 11440 return; 11441 11442 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11443 if (!TargetObjCPtr) 11444 return; 11445 11446 if (TargetObjCPtr->isUnspecialized() || 11447 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11448 != S.NSArrayDecl->getCanonicalDecl()) 11449 return; 11450 11451 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11452 if (TypeArgs.size() != 1) 11453 return; 11454 11455 QualType TargetElementType = TypeArgs[0]; 11456 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11457 checkObjCCollectionLiteralElement(S, TargetElementType, 11458 ArrayLiteral->getElement(I), 11459 0); 11460 } 11461 } 11462 11463 /// Check an Objective-C dictionary literal being converted to the given 11464 /// target type. 11465 static void 11466 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11467 ObjCDictionaryLiteral *DictionaryLiteral) { 11468 if (!S.NSDictionaryDecl) 11469 return; 11470 11471 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11472 if (!TargetObjCPtr) 11473 return; 11474 11475 if (TargetObjCPtr->isUnspecialized() || 11476 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11477 != S.NSDictionaryDecl->getCanonicalDecl()) 11478 return; 11479 11480 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11481 if (TypeArgs.size() != 2) 11482 return; 11483 11484 QualType TargetKeyType = TypeArgs[0]; 11485 QualType TargetObjectType = TypeArgs[1]; 11486 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11487 auto Element = DictionaryLiteral->getKeyValueElement(I); 11488 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11489 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11490 } 11491 } 11492 11493 // Helper function to filter out cases for constant width constant conversion. 11494 // Don't warn on char array initialization or for non-decimal values. 11495 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11496 SourceLocation CC) { 11497 // If initializing from a constant, and the constant starts with '0', 11498 // then it is a binary, octal, or hexadecimal. Allow these constants 11499 // to fill all the bits, even if there is a sign change. 11500 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11501 const char FirstLiteralCharacter = 11502 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11503 if (FirstLiteralCharacter == '0') 11504 return false; 11505 } 11506 11507 // If the CC location points to a '{', and the type is char, then assume 11508 // assume it is an array initialization. 11509 if (CC.isValid() && T->isCharType()) { 11510 const char FirstContextCharacter = 11511 S.getSourceManager().getCharacterData(CC)[0]; 11512 if (FirstContextCharacter == '{') 11513 return false; 11514 } 11515 11516 return true; 11517 } 11518 11519 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11520 const auto *IL = dyn_cast<IntegerLiteral>(E); 11521 if (!IL) { 11522 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11523 if (UO->getOpcode() == UO_Minus) 11524 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11525 } 11526 } 11527 11528 return IL; 11529 } 11530 11531 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11532 E = E->IgnoreParenImpCasts(); 11533 SourceLocation ExprLoc = E->getExprLoc(); 11534 11535 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11536 BinaryOperator::Opcode Opc = BO->getOpcode(); 11537 Expr::EvalResult Result; 11538 // Do not diagnose unsigned shifts. 11539 if (Opc == BO_Shl) { 11540 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11541 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11542 if (LHS && LHS->getValue() == 0) 11543 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11544 else if (!E->isValueDependent() && LHS && RHS && 11545 RHS->getValue().isNonNegative() && 11546 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11547 S.Diag(ExprLoc, diag::warn_left_shift_always) 11548 << (Result.Val.getInt() != 0); 11549 else if (E->getType()->isSignedIntegerType()) 11550 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11551 } 11552 } 11553 11554 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11555 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11556 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11557 if (!LHS || !RHS) 11558 return; 11559 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11560 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11561 // Do not diagnose common idioms. 11562 return; 11563 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11564 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11565 } 11566 } 11567 11568 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11569 SourceLocation CC, 11570 bool *ICContext = nullptr, 11571 bool IsListInit = false) { 11572 if (E->isTypeDependent() || E->isValueDependent()) return; 11573 11574 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11575 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11576 if (Source == Target) return; 11577 if (Target->isDependentType()) return; 11578 11579 // If the conversion context location is invalid don't complain. We also 11580 // don't want to emit a warning if the issue occurs from the expansion of 11581 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11582 // delay this check as long as possible. Once we detect we are in that 11583 // scenario, we just return. 11584 if (CC.isInvalid()) 11585 return; 11586 11587 if (Source->isAtomicType()) 11588 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11589 11590 // Diagnose implicit casts to bool. 11591 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11592 if (isa<StringLiteral>(E)) 11593 // Warn on string literal to bool. Checks for string literals in logical 11594 // and expressions, for instance, assert(0 && "error here"), are 11595 // prevented by a check in AnalyzeImplicitConversions(). 11596 return DiagnoseImpCast(S, E, T, CC, 11597 diag::warn_impcast_string_literal_to_bool); 11598 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11599 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11600 // This covers the literal expressions that evaluate to Objective-C 11601 // objects. 11602 return DiagnoseImpCast(S, E, T, CC, 11603 diag::warn_impcast_objective_c_literal_to_bool); 11604 } 11605 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11606 // Warn on pointer to bool conversion that is always true. 11607 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11608 SourceRange(CC)); 11609 } 11610 } 11611 11612 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11613 // is a typedef for signed char (macOS), then that constant value has to be 1 11614 // or 0. 11615 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11616 Expr::EvalResult Result; 11617 if (E->EvaluateAsInt(Result, S.getASTContext(), 11618 Expr::SE_AllowSideEffects)) { 11619 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11620 adornObjCBoolConversionDiagWithTernaryFixit( 11621 S, E, 11622 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11623 << Result.Val.getInt().toString(10)); 11624 } 11625 return; 11626 } 11627 } 11628 11629 // Check implicit casts from Objective-C collection literals to specialized 11630 // collection types, e.g., NSArray<NSString *> *. 11631 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11632 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11633 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11634 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11635 11636 // Strip vector types. 11637 if (isa<VectorType>(Source)) { 11638 if (!isa<VectorType>(Target)) { 11639 if (S.SourceMgr.isInSystemMacro(CC)) 11640 return; 11641 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11642 } 11643 11644 // If the vector cast is cast between two vectors of the same size, it is 11645 // a bitcast, not a conversion. 11646 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11647 return; 11648 11649 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11650 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11651 } 11652 if (auto VecTy = dyn_cast<VectorType>(Target)) 11653 Target = VecTy->getElementType().getTypePtr(); 11654 11655 // Strip complex types. 11656 if (isa<ComplexType>(Source)) { 11657 if (!isa<ComplexType>(Target)) { 11658 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11659 return; 11660 11661 return DiagnoseImpCast(S, E, T, CC, 11662 S.getLangOpts().CPlusPlus 11663 ? diag::err_impcast_complex_scalar 11664 : diag::warn_impcast_complex_scalar); 11665 } 11666 11667 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11668 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11669 } 11670 11671 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11672 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11673 11674 // If the source is floating point... 11675 if (SourceBT && SourceBT->isFloatingPoint()) { 11676 // ...and the target is floating point... 11677 if (TargetBT && TargetBT->isFloatingPoint()) { 11678 // ...then warn if we're dropping FP rank. 11679 11680 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11681 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11682 if (Order > 0) { 11683 // Don't warn about float constants that are precisely 11684 // representable in the target type. 11685 Expr::EvalResult result; 11686 if (E->EvaluateAsRValue(result, S.Context)) { 11687 // Value might be a float, a float vector, or a float complex. 11688 if (IsSameFloatAfterCast(result.Val, 11689 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11690 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11691 return; 11692 } 11693 11694 if (S.SourceMgr.isInSystemMacro(CC)) 11695 return; 11696 11697 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11698 } 11699 // ... or possibly if we're increasing rank, too 11700 else if (Order < 0) { 11701 if (S.SourceMgr.isInSystemMacro(CC)) 11702 return; 11703 11704 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11705 } 11706 return; 11707 } 11708 11709 // If the target is integral, always warn. 11710 if (TargetBT && TargetBT->isInteger()) { 11711 if (S.SourceMgr.isInSystemMacro(CC)) 11712 return; 11713 11714 DiagnoseFloatingImpCast(S, E, T, CC); 11715 } 11716 11717 // Detect the case where a call result is converted from floating-point to 11718 // to bool, and the final argument to the call is converted from bool, to 11719 // discover this typo: 11720 // 11721 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11722 // 11723 // FIXME: This is an incredibly special case; is there some more general 11724 // way to detect this class of misplaced-parentheses bug? 11725 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11726 // Check last argument of function call to see if it is an 11727 // implicit cast from a type matching the type the result 11728 // is being cast to. 11729 CallExpr *CEx = cast<CallExpr>(E); 11730 if (unsigned NumArgs = CEx->getNumArgs()) { 11731 Expr *LastA = CEx->getArg(NumArgs - 1); 11732 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11733 if (isa<ImplicitCastExpr>(LastA) && 11734 InnerE->getType()->isBooleanType()) { 11735 // Warn on this floating-point to bool conversion 11736 DiagnoseImpCast(S, E, T, CC, 11737 diag::warn_impcast_floating_point_to_bool); 11738 } 11739 } 11740 } 11741 return; 11742 } 11743 11744 // Valid casts involving fixed point types should be accounted for here. 11745 if (Source->isFixedPointType()) { 11746 if (Target->isUnsaturatedFixedPointType()) { 11747 Expr::EvalResult Result; 11748 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11749 S.isConstantEvaluated())) { 11750 APFixedPoint Value = Result.Val.getFixedPoint(); 11751 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11752 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11753 if (Value > MaxVal || Value < MinVal) { 11754 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11755 S.PDiag(diag::warn_impcast_fixed_point_range) 11756 << Value.toString() << T 11757 << E->getSourceRange() 11758 << clang::SourceRange(CC)); 11759 return; 11760 } 11761 } 11762 } else if (Target->isIntegerType()) { 11763 Expr::EvalResult Result; 11764 if (!S.isConstantEvaluated() && 11765 E->EvaluateAsFixedPoint(Result, S.Context, 11766 Expr::SE_AllowSideEffects)) { 11767 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11768 11769 bool Overflowed; 11770 llvm::APSInt IntResult = FXResult.convertToInt( 11771 S.Context.getIntWidth(T), 11772 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11773 11774 if (Overflowed) { 11775 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11776 S.PDiag(diag::warn_impcast_fixed_point_range) 11777 << FXResult.toString() << T 11778 << E->getSourceRange() 11779 << clang::SourceRange(CC)); 11780 return; 11781 } 11782 } 11783 } 11784 } else if (Target->isUnsaturatedFixedPointType()) { 11785 if (Source->isIntegerType()) { 11786 Expr::EvalResult Result; 11787 if (!S.isConstantEvaluated() && 11788 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11789 llvm::APSInt Value = Result.Val.getInt(); 11790 11791 bool Overflowed; 11792 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11793 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11794 11795 if (Overflowed) { 11796 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11797 S.PDiag(diag::warn_impcast_fixed_point_range) 11798 << Value.toString(/*Radix=*/10) << T 11799 << E->getSourceRange() 11800 << clang::SourceRange(CC)); 11801 return; 11802 } 11803 } 11804 } 11805 } 11806 11807 // If we are casting an integer type to a floating point type without 11808 // initialization-list syntax, we might lose accuracy if the floating 11809 // point type has a narrower significand than the integer type. 11810 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11811 TargetBT->isFloatingType() && !IsListInit) { 11812 // Determine the number of precision bits in the source integer type. 11813 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11814 unsigned int SourcePrecision = SourceRange.Width; 11815 11816 // Determine the number of precision bits in the 11817 // target floating point type. 11818 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11819 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11820 11821 if (SourcePrecision > 0 && TargetPrecision > 0 && 11822 SourcePrecision > TargetPrecision) { 11823 11824 if (Optional<llvm::APSInt> SourceInt = 11825 E->getIntegerConstantExpr(S.Context)) { 11826 // If the source integer is a constant, convert it to the target 11827 // floating point type. Issue a warning if the value changes 11828 // during the whole conversion. 11829 llvm::APFloat TargetFloatValue( 11830 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11831 llvm::APFloat::opStatus ConversionStatus = 11832 TargetFloatValue.convertFromAPInt( 11833 *SourceInt, SourceBT->isSignedInteger(), 11834 llvm::APFloat::rmNearestTiesToEven); 11835 11836 if (ConversionStatus != llvm::APFloat::opOK) { 11837 std::string PrettySourceValue = SourceInt->toString(10); 11838 SmallString<32> PrettyTargetValue; 11839 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11840 11841 S.DiagRuntimeBehavior( 11842 E->getExprLoc(), E, 11843 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11844 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11845 << E->getSourceRange() << clang::SourceRange(CC)); 11846 } 11847 } else { 11848 // Otherwise, the implicit conversion may lose precision. 11849 DiagnoseImpCast(S, E, T, CC, 11850 diag::warn_impcast_integer_float_precision); 11851 } 11852 } 11853 } 11854 11855 DiagnoseNullConversion(S, E, T, CC); 11856 11857 S.DiscardMisalignedMemberAddress(Target, E); 11858 11859 if (Target->isBooleanType()) 11860 DiagnoseIntInBoolContext(S, E); 11861 11862 if (!Source->isIntegerType() || !Target->isIntegerType()) 11863 return; 11864 11865 // TODO: remove this early return once the false positives for constant->bool 11866 // in templates, macros, etc, are reduced or removed. 11867 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11868 return; 11869 11870 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 11871 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11872 return adornObjCBoolConversionDiagWithTernaryFixit( 11873 S, E, 11874 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11875 << E->getType()); 11876 } 11877 11878 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11879 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11880 11881 if (SourceRange.Width > TargetRange.Width) { 11882 // If the source is a constant, use a default-on diagnostic. 11883 // TODO: this should happen for bitfield stores, too. 11884 Expr::EvalResult Result; 11885 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11886 S.isConstantEvaluated())) { 11887 llvm::APSInt Value(32); 11888 Value = Result.Val.getInt(); 11889 11890 if (S.SourceMgr.isInSystemMacro(CC)) 11891 return; 11892 11893 std::string PrettySourceValue = Value.toString(10); 11894 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11895 11896 S.DiagRuntimeBehavior( 11897 E->getExprLoc(), E, 11898 S.PDiag(diag::warn_impcast_integer_precision_constant) 11899 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11900 << E->getSourceRange() << clang::SourceRange(CC)); 11901 return; 11902 } 11903 11904 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11905 if (S.SourceMgr.isInSystemMacro(CC)) 11906 return; 11907 11908 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11909 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11910 /* pruneControlFlow */ true); 11911 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11912 } 11913 11914 if (TargetRange.Width > SourceRange.Width) { 11915 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11916 if (UO->getOpcode() == UO_Minus) 11917 if (Source->isUnsignedIntegerType()) { 11918 if (Target->isUnsignedIntegerType()) 11919 return DiagnoseImpCast(S, E, T, CC, 11920 diag::warn_impcast_high_order_zero_bits); 11921 if (Target->isSignedIntegerType()) 11922 return DiagnoseImpCast(S, E, T, CC, 11923 diag::warn_impcast_nonnegative_result); 11924 } 11925 } 11926 11927 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11928 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11929 // Warn when doing a signed to signed conversion, warn if the positive 11930 // source value is exactly the width of the target type, which will 11931 // cause a negative value to be stored. 11932 11933 Expr::EvalResult Result; 11934 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11935 !S.SourceMgr.isInSystemMacro(CC)) { 11936 llvm::APSInt Value = Result.Val.getInt(); 11937 if (isSameWidthConstantConversion(S, E, T, CC)) { 11938 std::string PrettySourceValue = Value.toString(10); 11939 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11940 11941 S.DiagRuntimeBehavior( 11942 E->getExprLoc(), E, 11943 S.PDiag(diag::warn_impcast_integer_precision_constant) 11944 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11945 << E->getSourceRange() << clang::SourceRange(CC)); 11946 return; 11947 } 11948 } 11949 11950 // Fall through for non-constants to give a sign conversion warning. 11951 } 11952 11953 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11954 (!TargetRange.NonNegative && SourceRange.NonNegative && 11955 SourceRange.Width == TargetRange.Width)) { 11956 if (S.SourceMgr.isInSystemMacro(CC)) 11957 return; 11958 11959 unsigned DiagID = diag::warn_impcast_integer_sign; 11960 11961 // Traditionally, gcc has warned about this under -Wsign-compare. 11962 // We also want to warn about it in -Wconversion. 11963 // So if -Wconversion is off, use a completely identical diagnostic 11964 // in the sign-compare group. 11965 // The conditional-checking code will 11966 if (ICContext) { 11967 DiagID = diag::warn_impcast_integer_sign_conditional; 11968 *ICContext = true; 11969 } 11970 11971 return DiagnoseImpCast(S, E, T, CC, DiagID); 11972 } 11973 11974 // Diagnose conversions between different enumeration types. 11975 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11976 // type, to give us better diagnostics. 11977 QualType SourceType = E->getType(); 11978 if (!S.getLangOpts().CPlusPlus) { 11979 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11980 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11981 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11982 SourceType = S.Context.getTypeDeclType(Enum); 11983 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11984 } 11985 } 11986 11987 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11988 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11989 if (SourceEnum->getDecl()->hasNameForLinkage() && 11990 TargetEnum->getDecl()->hasNameForLinkage() && 11991 SourceEnum != TargetEnum) { 11992 if (S.SourceMgr.isInSystemMacro(CC)) 11993 return; 11994 11995 return DiagnoseImpCast(S, E, SourceType, T, CC, 11996 diag::warn_impcast_different_enum_types); 11997 } 11998 } 11999 12000 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12001 SourceLocation CC, QualType T); 12002 12003 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 12004 SourceLocation CC, bool &ICContext) { 12005 E = E->IgnoreParenImpCasts(); 12006 12007 if (auto *CO = dyn_cast<AbstractConditionalOperator>(E)) 12008 return CheckConditionalOperator(S, CO, CC, T); 12009 12010 AnalyzeImplicitConversions(S, E, CC); 12011 if (E->getType() != T) 12012 return CheckImplicitConversion(S, E, T, CC, &ICContext); 12013 } 12014 12015 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, 12016 SourceLocation CC, QualType T) { 12017 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 12018 12019 Expr *TrueExpr = E->getTrueExpr(); 12020 if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E)) 12021 TrueExpr = BCO->getCommon(); 12022 12023 bool Suspicious = false; 12024 CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious); 12025 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 12026 12027 if (T->isBooleanType()) 12028 DiagnoseIntInBoolContext(S, E); 12029 12030 // If -Wconversion would have warned about either of the candidates 12031 // for a signedness conversion to the context type... 12032 if (!Suspicious) return; 12033 12034 // ...but it's currently ignored... 12035 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 12036 return; 12037 12038 // ...then check whether it would have warned about either of the 12039 // candidates for a signedness conversion to the condition type. 12040 if (E->getType() == T) return; 12041 12042 Suspicious = false; 12043 CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(), 12044 E->getType(), CC, &Suspicious); 12045 if (!Suspicious) 12046 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 12047 E->getType(), CC, &Suspicious); 12048 } 12049 12050 /// Check conversion of given expression to boolean. 12051 /// Input argument E is a logical expression. 12052 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 12053 if (S.getLangOpts().Bool) 12054 return; 12055 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 12056 return; 12057 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 12058 } 12059 12060 namespace { 12061 struct AnalyzeImplicitConversionsWorkItem { 12062 Expr *E; 12063 SourceLocation CC; 12064 bool IsListInit; 12065 }; 12066 } 12067 12068 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 12069 /// that should be visited are added to WorkList. 12070 static void AnalyzeImplicitConversions( 12071 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 12072 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 12073 Expr *OrigE = Item.E; 12074 SourceLocation CC = Item.CC; 12075 12076 QualType T = OrigE->getType(); 12077 Expr *E = OrigE->IgnoreParenImpCasts(); 12078 12079 // Propagate whether we are in a C++ list initialization expression. 12080 // If so, we do not issue warnings for implicit int-float conversion 12081 // precision loss, because C++11 narrowing already handles it. 12082 bool IsListInit = Item.IsListInit || 12083 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 12084 12085 if (E->isTypeDependent() || E->isValueDependent()) 12086 return; 12087 12088 Expr *SourceExpr = E; 12089 // Examine, but don't traverse into the source expression of an 12090 // OpaqueValueExpr, since it may have multiple parents and we don't want to 12091 // emit duplicate diagnostics. Its fine to examine the form or attempt to 12092 // evaluate it in the context of checking the specific conversion to T though. 12093 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 12094 if (auto *Src = OVE->getSourceExpr()) 12095 SourceExpr = Src; 12096 12097 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 12098 if (UO->getOpcode() == UO_Not && 12099 UO->getSubExpr()->isKnownToHaveBooleanValue()) 12100 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 12101 << OrigE->getSourceRange() << T->isBooleanType() 12102 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 12103 12104 // For conditional operators, we analyze the arguments as if they 12105 // were being fed directly into the output. 12106 if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) { 12107 CheckConditionalOperator(S, CO, CC, T); 12108 return; 12109 } 12110 12111 // Check implicit argument conversions for function calls. 12112 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 12113 CheckImplicitArgumentConversions(S, Call, CC); 12114 12115 // Go ahead and check any implicit conversions we might have skipped. 12116 // The non-canonical typecheck is just an optimization; 12117 // CheckImplicitConversion will filter out dead implicit conversions. 12118 if (SourceExpr->getType() != T) 12119 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 12120 12121 // Now continue drilling into this expression. 12122 12123 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 12124 // The bound subexpressions in a PseudoObjectExpr are not reachable 12125 // as transitive children. 12126 // FIXME: Use a more uniform representation for this. 12127 for (auto *SE : POE->semantics()) 12128 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 12129 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 12130 } 12131 12132 // Skip past explicit casts. 12133 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 12134 E = CE->getSubExpr()->IgnoreParenImpCasts(); 12135 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 12136 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 12137 WorkList.push_back({E, CC, IsListInit}); 12138 return; 12139 } 12140 12141 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12142 // Do a somewhat different check with comparison operators. 12143 if (BO->isComparisonOp()) 12144 return AnalyzeComparison(S, BO); 12145 12146 // And with simple assignments. 12147 if (BO->getOpcode() == BO_Assign) 12148 return AnalyzeAssignment(S, BO); 12149 // And with compound assignments. 12150 if (BO->isAssignmentOp()) 12151 return AnalyzeCompoundAssignment(S, BO); 12152 } 12153 12154 // These break the otherwise-useful invariant below. Fortunately, 12155 // we don't really need to recurse into them, because any internal 12156 // expressions should have been analyzed already when they were 12157 // built into statements. 12158 if (isa<StmtExpr>(E)) return; 12159 12160 // Don't descend into unevaluated contexts. 12161 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 12162 12163 // Now just recurse over the expression's children. 12164 CC = E->getExprLoc(); 12165 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 12166 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 12167 for (Stmt *SubStmt : E->children()) { 12168 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 12169 if (!ChildExpr) 12170 continue; 12171 12172 if (IsLogicalAndOperator && 12173 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 12174 // Ignore checking string literals that are in logical and operators. 12175 // This is a common pattern for asserts. 12176 continue; 12177 WorkList.push_back({ChildExpr, CC, IsListInit}); 12178 } 12179 12180 if (BO && BO->isLogicalOp()) { 12181 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 12182 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12183 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12184 12185 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12186 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12187 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12188 } 12189 12190 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12191 if (U->getOpcode() == UO_LNot) { 12192 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12193 } else if (U->getOpcode() != UO_AddrOf) { 12194 if (U->getSubExpr()->getType()->isAtomicType()) 12195 S.Diag(U->getSubExpr()->getBeginLoc(), 12196 diag::warn_atomic_implicit_seq_cst); 12197 } 12198 } 12199 } 12200 12201 /// AnalyzeImplicitConversions - Find and report any interesting 12202 /// implicit conversions in the given expression. There are a couple 12203 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12204 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12205 bool IsListInit/*= false*/) { 12206 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12207 WorkList.push_back({OrigE, CC, IsListInit}); 12208 while (!WorkList.empty()) 12209 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12210 } 12211 12212 /// Diagnose integer type and any valid implicit conversion to it. 12213 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12214 // Taking into account implicit conversions, 12215 // allow any integer. 12216 if (!E->getType()->isIntegerType()) { 12217 S.Diag(E->getBeginLoc(), 12218 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12219 return true; 12220 } 12221 // Potentially emit standard warnings for implicit conversions if enabled 12222 // using -Wconversion. 12223 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12224 return false; 12225 } 12226 12227 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12228 // Returns true when emitting a warning about taking the address of a reference. 12229 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12230 const PartialDiagnostic &PD) { 12231 E = E->IgnoreParenImpCasts(); 12232 12233 const FunctionDecl *FD = nullptr; 12234 12235 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12236 if (!DRE->getDecl()->getType()->isReferenceType()) 12237 return false; 12238 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12239 if (!M->getMemberDecl()->getType()->isReferenceType()) 12240 return false; 12241 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12242 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12243 return false; 12244 FD = Call->getDirectCallee(); 12245 } else { 12246 return false; 12247 } 12248 12249 SemaRef.Diag(E->getExprLoc(), PD); 12250 12251 // If possible, point to location of function. 12252 if (FD) { 12253 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12254 } 12255 12256 return true; 12257 } 12258 12259 // Returns true if the SourceLocation is expanded from any macro body. 12260 // Returns false if the SourceLocation is invalid, is from not in a macro 12261 // expansion, or is from expanded from a top-level macro argument. 12262 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12263 if (Loc.isInvalid()) 12264 return false; 12265 12266 while (Loc.isMacroID()) { 12267 if (SM.isMacroBodyExpansion(Loc)) 12268 return true; 12269 Loc = SM.getImmediateMacroCallerLoc(Loc); 12270 } 12271 12272 return false; 12273 } 12274 12275 /// Diagnose pointers that are always non-null. 12276 /// \param E the expression containing the pointer 12277 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12278 /// compared to a null pointer 12279 /// \param IsEqual True when the comparison is equal to a null pointer 12280 /// \param Range Extra SourceRange to highlight in the diagnostic 12281 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12282 Expr::NullPointerConstantKind NullKind, 12283 bool IsEqual, SourceRange Range) { 12284 if (!E) 12285 return; 12286 12287 // Don't warn inside macros. 12288 if (E->getExprLoc().isMacroID()) { 12289 const SourceManager &SM = getSourceManager(); 12290 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12291 IsInAnyMacroBody(SM, Range.getBegin())) 12292 return; 12293 } 12294 E = E->IgnoreImpCasts(); 12295 12296 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12297 12298 if (isa<CXXThisExpr>(E)) { 12299 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12300 : diag::warn_this_bool_conversion; 12301 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12302 return; 12303 } 12304 12305 bool IsAddressOf = false; 12306 12307 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12308 if (UO->getOpcode() != UO_AddrOf) 12309 return; 12310 IsAddressOf = true; 12311 E = UO->getSubExpr(); 12312 } 12313 12314 if (IsAddressOf) { 12315 unsigned DiagID = IsCompare 12316 ? diag::warn_address_of_reference_null_compare 12317 : diag::warn_address_of_reference_bool_conversion; 12318 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12319 << IsEqual; 12320 if (CheckForReference(*this, E, PD)) { 12321 return; 12322 } 12323 } 12324 12325 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12326 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12327 std::string Str; 12328 llvm::raw_string_ostream S(Str); 12329 E->printPretty(S, nullptr, getPrintingPolicy()); 12330 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12331 : diag::warn_cast_nonnull_to_bool; 12332 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12333 << E->getSourceRange() << Range << IsEqual; 12334 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12335 }; 12336 12337 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12338 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12339 if (auto *Callee = Call->getDirectCallee()) { 12340 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12341 ComplainAboutNonnullParamOrCall(A); 12342 return; 12343 } 12344 } 12345 } 12346 12347 // Expect to find a single Decl. Skip anything more complicated. 12348 ValueDecl *D = nullptr; 12349 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12350 D = R->getDecl(); 12351 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12352 D = M->getMemberDecl(); 12353 } 12354 12355 // Weak Decls can be null. 12356 if (!D || D->isWeak()) 12357 return; 12358 12359 // Check for parameter decl with nonnull attribute 12360 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12361 if (getCurFunction() && 12362 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12363 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12364 ComplainAboutNonnullParamOrCall(A); 12365 return; 12366 } 12367 12368 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12369 // Skip function template not specialized yet. 12370 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12371 return; 12372 auto ParamIter = llvm::find(FD->parameters(), PV); 12373 assert(ParamIter != FD->param_end()); 12374 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12375 12376 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12377 if (!NonNull->args_size()) { 12378 ComplainAboutNonnullParamOrCall(NonNull); 12379 return; 12380 } 12381 12382 for (const ParamIdx &ArgNo : NonNull->args()) { 12383 if (ArgNo.getASTIndex() == ParamNo) { 12384 ComplainAboutNonnullParamOrCall(NonNull); 12385 return; 12386 } 12387 } 12388 } 12389 } 12390 } 12391 } 12392 12393 QualType T = D->getType(); 12394 const bool IsArray = T->isArrayType(); 12395 const bool IsFunction = T->isFunctionType(); 12396 12397 // Address of function is used to silence the function warning. 12398 if (IsAddressOf && IsFunction) { 12399 return; 12400 } 12401 12402 // Found nothing. 12403 if (!IsAddressOf && !IsFunction && !IsArray) 12404 return; 12405 12406 // Pretty print the expression for the diagnostic. 12407 std::string Str; 12408 llvm::raw_string_ostream S(Str); 12409 E->printPretty(S, nullptr, getPrintingPolicy()); 12410 12411 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12412 : diag::warn_impcast_pointer_to_bool; 12413 enum { 12414 AddressOf, 12415 FunctionPointer, 12416 ArrayPointer 12417 } DiagType; 12418 if (IsAddressOf) 12419 DiagType = AddressOf; 12420 else if (IsFunction) 12421 DiagType = FunctionPointer; 12422 else if (IsArray) 12423 DiagType = ArrayPointer; 12424 else 12425 llvm_unreachable("Could not determine diagnostic."); 12426 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12427 << Range << IsEqual; 12428 12429 if (!IsFunction) 12430 return; 12431 12432 // Suggest '&' to silence the function warning. 12433 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12434 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12435 12436 // Check to see if '()' fixit should be emitted. 12437 QualType ReturnType; 12438 UnresolvedSet<4> NonTemplateOverloads; 12439 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12440 if (ReturnType.isNull()) 12441 return; 12442 12443 if (IsCompare) { 12444 // There are two cases here. If there is null constant, the only suggest 12445 // for a pointer return type. If the null is 0, then suggest if the return 12446 // type is a pointer or an integer type. 12447 if (!ReturnType->isPointerType()) { 12448 if (NullKind == Expr::NPCK_ZeroExpression || 12449 NullKind == Expr::NPCK_ZeroLiteral) { 12450 if (!ReturnType->isIntegerType()) 12451 return; 12452 } else { 12453 return; 12454 } 12455 } 12456 } else { // !IsCompare 12457 // For function to bool, only suggest if the function pointer has bool 12458 // return type. 12459 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12460 return; 12461 } 12462 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12463 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12464 } 12465 12466 /// Diagnoses "dangerous" implicit conversions within the given 12467 /// expression (which is a full expression). Implements -Wconversion 12468 /// and -Wsign-compare. 12469 /// 12470 /// \param CC the "context" location of the implicit conversion, i.e. 12471 /// the most location of the syntactic entity requiring the implicit 12472 /// conversion 12473 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12474 // Don't diagnose in unevaluated contexts. 12475 if (isUnevaluatedContext()) 12476 return; 12477 12478 // Don't diagnose for value- or type-dependent expressions. 12479 if (E->isTypeDependent() || E->isValueDependent()) 12480 return; 12481 12482 // Check for array bounds violations in cases where the check isn't triggered 12483 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12484 // ArraySubscriptExpr is on the RHS of a variable initialization. 12485 CheckArrayAccess(E); 12486 12487 // This is not the right CC for (e.g.) a variable initialization. 12488 AnalyzeImplicitConversions(*this, E, CC); 12489 } 12490 12491 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12492 /// Input argument E is a logical expression. 12493 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12494 ::CheckBoolLikeConversion(*this, E, CC); 12495 } 12496 12497 /// Diagnose when expression is an integer constant expression and its evaluation 12498 /// results in integer overflow 12499 void Sema::CheckForIntOverflow (Expr *E) { 12500 // Use a work list to deal with nested struct initializers. 12501 SmallVector<Expr *, 2> Exprs(1, E); 12502 12503 do { 12504 Expr *OriginalE = Exprs.pop_back_val(); 12505 Expr *E = OriginalE->IgnoreParenCasts(); 12506 12507 if (isa<BinaryOperator>(E)) { 12508 E->EvaluateForOverflow(Context); 12509 continue; 12510 } 12511 12512 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12513 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12514 else if (isa<ObjCBoxedExpr>(OriginalE)) 12515 E->EvaluateForOverflow(Context); 12516 else if (auto Call = dyn_cast<CallExpr>(E)) 12517 Exprs.append(Call->arg_begin(), Call->arg_end()); 12518 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12519 Exprs.append(Message->arg_begin(), Message->arg_end()); 12520 } while (!Exprs.empty()); 12521 } 12522 12523 namespace { 12524 12525 /// Visitor for expressions which looks for unsequenced operations on the 12526 /// same object. 12527 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12528 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12529 12530 /// A tree of sequenced regions within an expression. Two regions are 12531 /// unsequenced if one is an ancestor or a descendent of the other. When we 12532 /// finish processing an expression with sequencing, such as a comma 12533 /// expression, we fold its tree nodes into its parent, since they are 12534 /// unsequenced with respect to nodes we will visit later. 12535 class SequenceTree { 12536 struct Value { 12537 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12538 unsigned Parent : 31; 12539 unsigned Merged : 1; 12540 }; 12541 SmallVector<Value, 8> Values; 12542 12543 public: 12544 /// A region within an expression which may be sequenced with respect 12545 /// to some other region. 12546 class Seq { 12547 friend class SequenceTree; 12548 12549 unsigned Index; 12550 12551 explicit Seq(unsigned N) : Index(N) {} 12552 12553 public: 12554 Seq() : Index(0) {} 12555 }; 12556 12557 SequenceTree() { Values.push_back(Value(0)); } 12558 Seq root() const { return Seq(0); } 12559 12560 /// Create a new sequence of operations, which is an unsequenced 12561 /// subset of \p Parent. This sequence of operations is sequenced with 12562 /// respect to other children of \p Parent. 12563 Seq allocate(Seq Parent) { 12564 Values.push_back(Value(Parent.Index)); 12565 return Seq(Values.size() - 1); 12566 } 12567 12568 /// Merge a sequence of operations into its parent. 12569 void merge(Seq S) { 12570 Values[S.Index].Merged = true; 12571 } 12572 12573 /// Determine whether two operations are unsequenced. This operation 12574 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12575 /// should have been merged into its parent as appropriate. 12576 bool isUnsequenced(Seq Cur, Seq Old) { 12577 unsigned C = representative(Cur.Index); 12578 unsigned Target = representative(Old.Index); 12579 while (C >= Target) { 12580 if (C == Target) 12581 return true; 12582 C = Values[C].Parent; 12583 } 12584 return false; 12585 } 12586 12587 private: 12588 /// Pick a representative for a sequence. 12589 unsigned representative(unsigned K) { 12590 if (Values[K].Merged) 12591 // Perform path compression as we go. 12592 return Values[K].Parent = representative(Values[K].Parent); 12593 return K; 12594 } 12595 }; 12596 12597 /// An object for which we can track unsequenced uses. 12598 using Object = const NamedDecl *; 12599 12600 /// Different flavors of object usage which we track. We only track the 12601 /// least-sequenced usage of each kind. 12602 enum UsageKind { 12603 /// A read of an object. Multiple unsequenced reads are OK. 12604 UK_Use, 12605 12606 /// A modification of an object which is sequenced before the value 12607 /// computation of the expression, such as ++n in C++. 12608 UK_ModAsValue, 12609 12610 /// A modification of an object which is not sequenced before the value 12611 /// computation of the expression, such as n++. 12612 UK_ModAsSideEffect, 12613 12614 UK_Count = UK_ModAsSideEffect + 1 12615 }; 12616 12617 /// Bundle together a sequencing region and the expression corresponding 12618 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12619 struct Usage { 12620 const Expr *UsageExpr; 12621 SequenceTree::Seq Seq; 12622 12623 Usage() : UsageExpr(nullptr), Seq() {} 12624 }; 12625 12626 struct UsageInfo { 12627 Usage Uses[UK_Count]; 12628 12629 /// Have we issued a diagnostic for this object already? 12630 bool Diagnosed; 12631 12632 UsageInfo() : Uses(), Diagnosed(false) {} 12633 }; 12634 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12635 12636 Sema &SemaRef; 12637 12638 /// Sequenced regions within the expression. 12639 SequenceTree Tree; 12640 12641 /// Declaration modifications and references which we have seen. 12642 UsageInfoMap UsageMap; 12643 12644 /// The region we are currently within. 12645 SequenceTree::Seq Region; 12646 12647 /// Filled in with declarations which were modified as a side-effect 12648 /// (that is, post-increment operations). 12649 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12650 12651 /// Expressions to check later. We defer checking these to reduce 12652 /// stack usage. 12653 SmallVectorImpl<const Expr *> &WorkList; 12654 12655 /// RAII object wrapping the visitation of a sequenced subexpression of an 12656 /// expression. At the end of this process, the side-effects of the evaluation 12657 /// become sequenced with respect to the value computation of the result, so 12658 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12659 /// UK_ModAsValue. 12660 struct SequencedSubexpression { 12661 SequencedSubexpression(SequenceChecker &Self) 12662 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12663 Self.ModAsSideEffect = &ModAsSideEffect; 12664 } 12665 12666 ~SequencedSubexpression() { 12667 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12668 // Add a new usage with usage kind UK_ModAsValue, and then restore 12669 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12670 // the previous one was empty). 12671 UsageInfo &UI = Self.UsageMap[M.first]; 12672 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12673 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12674 SideEffectUsage = M.second; 12675 } 12676 Self.ModAsSideEffect = OldModAsSideEffect; 12677 } 12678 12679 SequenceChecker &Self; 12680 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12681 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12682 }; 12683 12684 /// RAII object wrapping the visitation of a subexpression which we might 12685 /// choose to evaluate as a constant. If any subexpression is evaluated and 12686 /// found to be non-constant, this allows us to suppress the evaluation of 12687 /// the outer expression. 12688 class EvaluationTracker { 12689 public: 12690 EvaluationTracker(SequenceChecker &Self) 12691 : Self(Self), Prev(Self.EvalTracker) { 12692 Self.EvalTracker = this; 12693 } 12694 12695 ~EvaluationTracker() { 12696 Self.EvalTracker = Prev; 12697 if (Prev) 12698 Prev->EvalOK &= EvalOK; 12699 } 12700 12701 bool evaluate(const Expr *E, bool &Result) { 12702 if (!EvalOK || E->isValueDependent()) 12703 return false; 12704 EvalOK = E->EvaluateAsBooleanCondition( 12705 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12706 return EvalOK; 12707 } 12708 12709 private: 12710 SequenceChecker &Self; 12711 EvaluationTracker *Prev; 12712 bool EvalOK = true; 12713 } *EvalTracker = nullptr; 12714 12715 /// Find the object which is produced by the specified expression, 12716 /// if any. 12717 Object getObject(const Expr *E, bool Mod) const { 12718 E = E->IgnoreParenCasts(); 12719 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12720 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12721 return getObject(UO->getSubExpr(), Mod); 12722 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12723 if (BO->getOpcode() == BO_Comma) 12724 return getObject(BO->getRHS(), Mod); 12725 if (Mod && BO->isAssignmentOp()) 12726 return getObject(BO->getLHS(), Mod); 12727 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12728 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12729 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12730 return ME->getMemberDecl(); 12731 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12732 // FIXME: If this is a reference, map through to its value. 12733 return DRE->getDecl(); 12734 return nullptr; 12735 } 12736 12737 /// Note that an object \p O was modified or used by an expression 12738 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12739 /// the object \p O as obtained via the \p UsageMap. 12740 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12741 // Get the old usage for the given object and usage kind. 12742 Usage &U = UI.Uses[UK]; 12743 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12744 // If we have a modification as side effect and are in a sequenced 12745 // subexpression, save the old Usage so that we can restore it later 12746 // in SequencedSubexpression::~SequencedSubexpression. 12747 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12748 ModAsSideEffect->push_back(std::make_pair(O, U)); 12749 // Then record the new usage with the current sequencing region. 12750 U.UsageExpr = UsageExpr; 12751 U.Seq = Region; 12752 } 12753 } 12754 12755 /// Check whether a modification or use of an object \p O in an expression 12756 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12757 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12758 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12759 /// usage and false we are checking for a mod-use unsequenced usage. 12760 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12761 UsageKind OtherKind, bool IsModMod) { 12762 if (UI.Diagnosed) 12763 return; 12764 12765 const Usage &U = UI.Uses[OtherKind]; 12766 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12767 return; 12768 12769 const Expr *Mod = U.UsageExpr; 12770 const Expr *ModOrUse = UsageExpr; 12771 if (OtherKind == UK_Use) 12772 std::swap(Mod, ModOrUse); 12773 12774 SemaRef.DiagRuntimeBehavior( 12775 Mod->getExprLoc(), {Mod, ModOrUse}, 12776 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12777 : diag::warn_unsequenced_mod_use) 12778 << O << SourceRange(ModOrUse->getExprLoc())); 12779 UI.Diagnosed = true; 12780 } 12781 12782 // A note on note{Pre, Post}{Use, Mod}: 12783 // 12784 // (It helps to follow the algorithm with an expression such as 12785 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12786 // operations before C++17 and both are well-defined in C++17). 12787 // 12788 // When visiting a node which uses/modify an object we first call notePreUse 12789 // or notePreMod before visiting its sub-expression(s). At this point the 12790 // children of the current node have not yet been visited and so the eventual 12791 // uses/modifications resulting from the children of the current node have not 12792 // been recorded yet. 12793 // 12794 // We then visit the children of the current node. After that notePostUse or 12795 // notePostMod is called. These will 1) detect an unsequenced modification 12796 // as side effect (as in "k++ + k") and 2) add a new usage with the 12797 // appropriate usage kind. 12798 // 12799 // We also have to be careful that some operation sequences modification as 12800 // side effect as well (for example: || or ,). To account for this we wrap 12801 // the visitation of such a sub-expression (for example: the LHS of || or ,) 12802 // with SequencedSubexpression. SequencedSubexpression is an RAII object 12803 // which record usages which are modifications as side effect, and then 12804 // downgrade them (or more accurately restore the previous usage which was a 12805 // modification as side effect) when exiting the scope of the sequenced 12806 // subexpression. 12807 12808 void notePreUse(Object O, const Expr *UseExpr) { 12809 UsageInfo &UI = UsageMap[O]; 12810 // Uses conflict with other modifications. 12811 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 12812 } 12813 12814 void notePostUse(Object O, const Expr *UseExpr) { 12815 UsageInfo &UI = UsageMap[O]; 12816 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 12817 /*IsModMod=*/false); 12818 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 12819 } 12820 12821 void notePreMod(Object O, const Expr *ModExpr) { 12822 UsageInfo &UI = UsageMap[O]; 12823 // Modifications conflict with other modifications and with uses. 12824 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 12825 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 12826 } 12827 12828 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 12829 UsageInfo &UI = UsageMap[O]; 12830 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 12831 /*IsModMod=*/true); 12832 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 12833 } 12834 12835 public: 12836 SequenceChecker(Sema &S, const Expr *E, 12837 SmallVectorImpl<const Expr *> &WorkList) 12838 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12839 Visit(E); 12840 // Silence a -Wunused-private-field since WorkList is now unused. 12841 // TODO: Evaluate if it can be used, and if not remove it. 12842 (void)this->WorkList; 12843 } 12844 12845 void VisitStmt(const Stmt *S) { 12846 // Skip all statements which aren't expressions for now. 12847 } 12848 12849 void VisitExpr(const Expr *E) { 12850 // By default, just recurse to evaluated subexpressions. 12851 Base::VisitStmt(E); 12852 } 12853 12854 void VisitCastExpr(const CastExpr *E) { 12855 Object O = Object(); 12856 if (E->getCastKind() == CK_LValueToRValue) 12857 O = getObject(E->getSubExpr(), false); 12858 12859 if (O) 12860 notePreUse(O, E); 12861 VisitExpr(E); 12862 if (O) 12863 notePostUse(O, E); 12864 } 12865 12866 void VisitSequencedExpressions(const Expr *SequencedBefore, 12867 const Expr *SequencedAfter) { 12868 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12869 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12870 SequenceTree::Seq OldRegion = Region; 12871 12872 { 12873 SequencedSubexpression SeqBefore(*this); 12874 Region = BeforeRegion; 12875 Visit(SequencedBefore); 12876 } 12877 12878 Region = AfterRegion; 12879 Visit(SequencedAfter); 12880 12881 Region = OldRegion; 12882 12883 Tree.merge(BeforeRegion); 12884 Tree.merge(AfterRegion); 12885 } 12886 12887 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 12888 // C++17 [expr.sub]p1: 12889 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12890 // expression E1 is sequenced before the expression E2. 12891 if (SemaRef.getLangOpts().CPlusPlus17) 12892 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12893 else { 12894 Visit(ASE->getLHS()); 12895 Visit(ASE->getRHS()); 12896 } 12897 } 12898 12899 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12900 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12901 void VisitBinPtrMem(const BinaryOperator *BO) { 12902 // C++17 [expr.mptr.oper]p4: 12903 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 12904 // the expression E1 is sequenced before the expression E2. 12905 if (SemaRef.getLangOpts().CPlusPlus17) 12906 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12907 else { 12908 Visit(BO->getLHS()); 12909 Visit(BO->getRHS()); 12910 } 12911 } 12912 12913 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12914 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12915 void VisitBinShlShr(const BinaryOperator *BO) { 12916 // C++17 [expr.shift]p4: 12917 // The expression E1 is sequenced before the expression E2. 12918 if (SemaRef.getLangOpts().CPlusPlus17) 12919 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12920 else { 12921 Visit(BO->getLHS()); 12922 Visit(BO->getRHS()); 12923 } 12924 } 12925 12926 void VisitBinComma(const BinaryOperator *BO) { 12927 // C++11 [expr.comma]p1: 12928 // Every value computation and side effect associated with the left 12929 // expression is sequenced before every value computation and side 12930 // effect associated with the right expression. 12931 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12932 } 12933 12934 void VisitBinAssign(const BinaryOperator *BO) { 12935 SequenceTree::Seq RHSRegion; 12936 SequenceTree::Seq LHSRegion; 12937 if (SemaRef.getLangOpts().CPlusPlus17) { 12938 RHSRegion = Tree.allocate(Region); 12939 LHSRegion = Tree.allocate(Region); 12940 } else { 12941 RHSRegion = Region; 12942 LHSRegion = Region; 12943 } 12944 SequenceTree::Seq OldRegion = Region; 12945 12946 // C++11 [expr.ass]p1: 12947 // [...] the assignment is sequenced after the value computation 12948 // of the right and left operands, [...] 12949 // 12950 // so check it before inspecting the operands and update the 12951 // map afterwards. 12952 Object O = getObject(BO->getLHS(), /*Mod=*/true); 12953 if (O) 12954 notePreMod(O, BO); 12955 12956 if (SemaRef.getLangOpts().CPlusPlus17) { 12957 // C++17 [expr.ass]p1: 12958 // [...] The right operand is sequenced before the left operand. [...] 12959 { 12960 SequencedSubexpression SeqBefore(*this); 12961 Region = RHSRegion; 12962 Visit(BO->getRHS()); 12963 } 12964 12965 Region = LHSRegion; 12966 Visit(BO->getLHS()); 12967 12968 if (O && isa<CompoundAssignOperator>(BO)) 12969 notePostUse(O, BO); 12970 12971 } else { 12972 // C++11 does not specify any sequencing between the LHS and RHS. 12973 Region = LHSRegion; 12974 Visit(BO->getLHS()); 12975 12976 if (O && isa<CompoundAssignOperator>(BO)) 12977 notePostUse(O, BO); 12978 12979 Region = RHSRegion; 12980 Visit(BO->getRHS()); 12981 } 12982 12983 // C++11 [expr.ass]p1: 12984 // the assignment is sequenced [...] before the value computation of the 12985 // assignment expression. 12986 // C11 6.5.16/3 has no such rule. 12987 Region = OldRegion; 12988 if (O) 12989 notePostMod(O, BO, 12990 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12991 : UK_ModAsSideEffect); 12992 if (SemaRef.getLangOpts().CPlusPlus17) { 12993 Tree.merge(RHSRegion); 12994 Tree.merge(LHSRegion); 12995 } 12996 } 12997 12998 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 12999 VisitBinAssign(CAO); 13000 } 13001 13002 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13003 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 13004 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 13005 Object O = getObject(UO->getSubExpr(), true); 13006 if (!O) 13007 return VisitExpr(UO); 13008 13009 notePreMod(O, UO); 13010 Visit(UO->getSubExpr()); 13011 // C++11 [expr.pre.incr]p1: 13012 // the expression ++x is equivalent to x+=1 13013 notePostMod(O, UO, 13014 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 13015 : UK_ModAsSideEffect); 13016 } 13017 13018 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13019 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 13020 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 13021 Object O = getObject(UO->getSubExpr(), true); 13022 if (!O) 13023 return VisitExpr(UO); 13024 13025 notePreMod(O, UO); 13026 Visit(UO->getSubExpr()); 13027 notePostMod(O, UO, UK_ModAsSideEffect); 13028 } 13029 13030 void VisitBinLOr(const BinaryOperator *BO) { 13031 // C++11 [expr.log.or]p2: 13032 // If the second expression is evaluated, every value computation and 13033 // side effect associated with the first expression is sequenced before 13034 // every value computation and side effect associated with the 13035 // second expression. 13036 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13037 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13038 SequenceTree::Seq OldRegion = Region; 13039 13040 EvaluationTracker Eval(*this); 13041 { 13042 SequencedSubexpression Sequenced(*this); 13043 Region = LHSRegion; 13044 Visit(BO->getLHS()); 13045 } 13046 13047 // C++11 [expr.log.or]p1: 13048 // [...] the second operand is not evaluated if the first operand 13049 // evaluates to true. 13050 bool EvalResult = false; 13051 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13052 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 13053 if (ShouldVisitRHS) { 13054 Region = RHSRegion; 13055 Visit(BO->getRHS()); 13056 } 13057 13058 Region = OldRegion; 13059 Tree.merge(LHSRegion); 13060 Tree.merge(RHSRegion); 13061 } 13062 13063 void VisitBinLAnd(const BinaryOperator *BO) { 13064 // C++11 [expr.log.and]p2: 13065 // If the second expression is evaluated, every value computation and 13066 // side effect associated with the first expression is sequenced before 13067 // every value computation and side effect associated with the 13068 // second expression. 13069 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 13070 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 13071 SequenceTree::Seq OldRegion = Region; 13072 13073 EvaluationTracker Eval(*this); 13074 { 13075 SequencedSubexpression Sequenced(*this); 13076 Region = LHSRegion; 13077 Visit(BO->getLHS()); 13078 } 13079 13080 // C++11 [expr.log.and]p1: 13081 // [...] the second operand is not evaluated if the first operand is false. 13082 bool EvalResult = false; 13083 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 13084 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 13085 if (ShouldVisitRHS) { 13086 Region = RHSRegion; 13087 Visit(BO->getRHS()); 13088 } 13089 13090 Region = OldRegion; 13091 Tree.merge(LHSRegion); 13092 Tree.merge(RHSRegion); 13093 } 13094 13095 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 13096 // C++11 [expr.cond]p1: 13097 // [...] Every value computation and side effect associated with the first 13098 // expression is sequenced before every value computation and side effect 13099 // associated with the second or third expression. 13100 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 13101 13102 // No sequencing is specified between the true and false expression. 13103 // However since exactly one of both is going to be evaluated we can 13104 // consider them to be sequenced. This is needed to avoid warning on 13105 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 13106 // both the true and false expressions because we can't evaluate x. 13107 // This will still allow us to detect an expression like (pre C++17) 13108 // "(x ? y += 1 : y += 2) = y". 13109 // 13110 // We don't wrap the visitation of the true and false expression with 13111 // SequencedSubexpression because we don't want to downgrade modifications 13112 // as side effect in the true and false expressions after the visition 13113 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 13114 // not warn between the two "y++", but we should warn between the "y++" 13115 // and the "y". 13116 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 13117 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 13118 SequenceTree::Seq OldRegion = Region; 13119 13120 EvaluationTracker Eval(*this); 13121 { 13122 SequencedSubexpression Sequenced(*this); 13123 Region = ConditionRegion; 13124 Visit(CO->getCond()); 13125 } 13126 13127 // C++11 [expr.cond]p1: 13128 // [...] The first expression is contextually converted to bool (Clause 4). 13129 // It is evaluated and if it is true, the result of the conditional 13130 // expression is the value of the second expression, otherwise that of the 13131 // third expression. Only one of the second and third expressions is 13132 // evaluated. [...] 13133 bool EvalResult = false; 13134 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 13135 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 13136 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 13137 if (ShouldVisitTrueExpr) { 13138 Region = TrueRegion; 13139 Visit(CO->getTrueExpr()); 13140 } 13141 if (ShouldVisitFalseExpr) { 13142 Region = FalseRegion; 13143 Visit(CO->getFalseExpr()); 13144 } 13145 13146 Region = OldRegion; 13147 Tree.merge(ConditionRegion); 13148 Tree.merge(TrueRegion); 13149 Tree.merge(FalseRegion); 13150 } 13151 13152 void VisitCallExpr(const CallExpr *CE) { 13153 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 13154 13155 if (CE->isUnevaluatedBuiltinCall(Context)) 13156 return; 13157 13158 // C++11 [intro.execution]p15: 13159 // When calling a function [...], every value computation and side effect 13160 // associated with any argument expression, or with the postfix expression 13161 // designating the called function, is sequenced before execution of every 13162 // expression or statement in the body of the function [and thus before 13163 // the value computation of its result]. 13164 SequencedSubexpression Sequenced(*this); 13165 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 13166 // C++17 [expr.call]p5 13167 // The postfix-expression is sequenced before each expression in the 13168 // expression-list and any default argument. [...] 13169 SequenceTree::Seq CalleeRegion; 13170 SequenceTree::Seq OtherRegion; 13171 if (SemaRef.getLangOpts().CPlusPlus17) { 13172 CalleeRegion = Tree.allocate(Region); 13173 OtherRegion = Tree.allocate(Region); 13174 } else { 13175 CalleeRegion = Region; 13176 OtherRegion = Region; 13177 } 13178 SequenceTree::Seq OldRegion = Region; 13179 13180 // Visit the callee expression first. 13181 Region = CalleeRegion; 13182 if (SemaRef.getLangOpts().CPlusPlus17) { 13183 SequencedSubexpression Sequenced(*this); 13184 Visit(CE->getCallee()); 13185 } else { 13186 Visit(CE->getCallee()); 13187 } 13188 13189 // Then visit the argument expressions. 13190 Region = OtherRegion; 13191 for (const Expr *Argument : CE->arguments()) 13192 Visit(Argument); 13193 13194 Region = OldRegion; 13195 if (SemaRef.getLangOpts().CPlusPlus17) { 13196 Tree.merge(CalleeRegion); 13197 Tree.merge(OtherRegion); 13198 } 13199 }); 13200 } 13201 13202 void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) { 13203 // C++17 [over.match.oper]p2: 13204 // [...] the operator notation is first transformed to the equivalent 13205 // function-call notation as summarized in Table 12 (where @ denotes one 13206 // of the operators covered in the specified subclause). However, the 13207 // operands are sequenced in the order prescribed for the built-in 13208 // operator (Clause 8). 13209 // 13210 // From the above only overloaded binary operators and overloaded call 13211 // operators have sequencing rules in C++17 that we need to handle 13212 // separately. 13213 if (!SemaRef.getLangOpts().CPlusPlus17 || 13214 (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call)) 13215 return VisitCallExpr(CXXOCE); 13216 13217 enum { 13218 NoSequencing, 13219 LHSBeforeRHS, 13220 RHSBeforeLHS, 13221 LHSBeforeRest 13222 } SequencingKind; 13223 switch (CXXOCE->getOperator()) { 13224 case OO_Equal: 13225 case OO_PlusEqual: 13226 case OO_MinusEqual: 13227 case OO_StarEqual: 13228 case OO_SlashEqual: 13229 case OO_PercentEqual: 13230 case OO_CaretEqual: 13231 case OO_AmpEqual: 13232 case OO_PipeEqual: 13233 case OO_LessLessEqual: 13234 case OO_GreaterGreaterEqual: 13235 SequencingKind = RHSBeforeLHS; 13236 break; 13237 13238 case OO_LessLess: 13239 case OO_GreaterGreater: 13240 case OO_AmpAmp: 13241 case OO_PipePipe: 13242 case OO_Comma: 13243 case OO_ArrowStar: 13244 case OO_Subscript: 13245 SequencingKind = LHSBeforeRHS; 13246 break; 13247 13248 case OO_Call: 13249 SequencingKind = LHSBeforeRest; 13250 break; 13251 13252 default: 13253 SequencingKind = NoSequencing; 13254 break; 13255 } 13256 13257 if (SequencingKind == NoSequencing) 13258 return VisitCallExpr(CXXOCE); 13259 13260 // This is a call, so all subexpressions are sequenced before the result. 13261 SequencedSubexpression Sequenced(*this); 13262 13263 SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] { 13264 assert(SemaRef.getLangOpts().CPlusPlus17 && 13265 "Should only get there with C++17 and above!"); 13266 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) && 13267 "Should only get there with an overloaded binary operator" 13268 " or an overloaded call operator!"); 13269 13270 if (SequencingKind == LHSBeforeRest) { 13271 assert(CXXOCE->getOperator() == OO_Call && 13272 "We should only have an overloaded call operator here!"); 13273 13274 // This is very similar to VisitCallExpr, except that we only have the 13275 // C++17 case. The postfix-expression is the first argument of the 13276 // CXXOperatorCallExpr. The expressions in the expression-list, if any, 13277 // are in the following arguments. 13278 // 13279 // Note that we intentionally do not visit the callee expression since 13280 // it is just a decayed reference to a function. 13281 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region); 13282 SequenceTree::Seq ArgsRegion = Tree.allocate(Region); 13283 SequenceTree::Seq OldRegion = Region; 13284 13285 assert(CXXOCE->getNumArgs() >= 1 && 13286 "An overloaded call operator must have at least one argument" 13287 " for the postfix-expression!"); 13288 const Expr *PostfixExpr = CXXOCE->getArgs()[0]; 13289 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1, 13290 CXXOCE->getNumArgs() - 1); 13291 13292 // Visit the postfix-expression first. 13293 { 13294 Region = PostfixExprRegion; 13295 SequencedSubexpression Sequenced(*this); 13296 Visit(PostfixExpr); 13297 } 13298 13299 // Then visit the argument expressions. 13300 Region = ArgsRegion; 13301 for (const Expr *Arg : Args) 13302 Visit(Arg); 13303 13304 Region = OldRegion; 13305 Tree.merge(PostfixExprRegion); 13306 Tree.merge(ArgsRegion); 13307 } else { 13308 assert(CXXOCE->getNumArgs() == 2 && 13309 "Should only have two arguments here!"); 13310 assert((SequencingKind == LHSBeforeRHS || 13311 SequencingKind == RHSBeforeLHS) && 13312 "Unexpected sequencing kind!"); 13313 13314 // We do not visit the callee expression since it is just a decayed 13315 // reference to a function. 13316 const Expr *E1 = CXXOCE->getArg(0); 13317 const Expr *E2 = CXXOCE->getArg(1); 13318 if (SequencingKind == RHSBeforeLHS) 13319 std::swap(E1, E2); 13320 13321 return VisitSequencedExpressions(E1, E2); 13322 } 13323 }); 13324 } 13325 13326 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13327 // This is a call, so all subexpressions are sequenced before the result. 13328 SequencedSubexpression Sequenced(*this); 13329 13330 if (!CCE->isListInitialization()) 13331 return VisitExpr(CCE); 13332 13333 // In C++11, list initializations are sequenced. 13334 SmallVector<SequenceTree::Seq, 32> Elts; 13335 SequenceTree::Seq Parent = Region; 13336 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13337 E = CCE->arg_end(); 13338 I != E; ++I) { 13339 Region = Tree.allocate(Parent); 13340 Elts.push_back(Region); 13341 Visit(*I); 13342 } 13343 13344 // Forget that the initializers are sequenced. 13345 Region = Parent; 13346 for (unsigned I = 0; I < Elts.size(); ++I) 13347 Tree.merge(Elts[I]); 13348 } 13349 13350 void VisitInitListExpr(const InitListExpr *ILE) { 13351 if (!SemaRef.getLangOpts().CPlusPlus11) 13352 return VisitExpr(ILE); 13353 13354 // In C++11, list initializations are sequenced. 13355 SmallVector<SequenceTree::Seq, 32> Elts; 13356 SequenceTree::Seq Parent = Region; 13357 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13358 const Expr *E = ILE->getInit(I); 13359 if (!E) 13360 continue; 13361 Region = Tree.allocate(Parent); 13362 Elts.push_back(Region); 13363 Visit(E); 13364 } 13365 13366 // Forget that the initializers are sequenced. 13367 Region = Parent; 13368 for (unsigned I = 0; I < Elts.size(); ++I) 13369 Tree.merge(Elts[I]); 13370 } 13371 }; 13372 13373 } // namespace 13374 13375 void Sema::CheckUnsequencedOperations(const Expr *E) { 13376 SmallVector<const Expr *, 8> WorkList; 13377 WorkList.push_back(E); 13378 while (!WorkList.empty()) { 13379 const Expr *Item = WorkList.pop_back_val(); 13380 SequenceChecker(*this, Item, WorkList); 13381 } 13382 } 13383 13384 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13385 bool IsConstexpr) { 13386 llvm::SaveAndRestore<bool> ConstantContext( 13387 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13388 CheckImplicitConversions(E, CheckLoc); 13389 if (!E->isInstantiationDependent()) 13390 CheckUnsequencedOperations(E); 13391 if (!IsConstexpr && !E->isValueDependent()) 13392 CheckForIntOverflow(E); 13393 DiagnoseMisalignedMembers(); 13394 } 13395 13396 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13397 FieldDecl *BitField, 13398 Expr *Init) { 13399 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13400 } 13401 13402 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13403 SourceLocation Loc) { 13404 if (!PType->isVariablyModifiedType()) 13405 return; 13406 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13407 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13408 return; 13409 } 13410 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13411 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13412 return; 13413 } 13414 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13415 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13416 return; 13417 } 13418 13419 const ArrayType *AT = S.Context.getAsArrayType(PType); 13420 if (!AT) 13421 return; 13422 13423 if (AT->getSizeModifier() != ArrayType::Star) { 13424 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13425 return; 13426 } 13427 13428 S.Diag(Loc, diag::err_array_star_in_function_definition); 13429 } 13430 13431 /// CheckParmsForFunctionDef - Check that the parameters of the given 13432 /// function are appropriate for the definition of a function. This 13433 /// takes care of any checks that cannot be performed on the 13434 /// declaration itself, e.g., that the types of each of the function 13435 /// parameters are complete. 13436 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13437 bool CheckParameterNames) { 13438 bool HasInvalidParm = false; 13439 for (ParmVarDecl *Param : Parameters) { 13440 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13441 // function declarator that is part of a function definition of 13442 // that function shall not have incomplete type. 13443 // 13444 // This is also C++ [dcl.fct]p6. 13445 if (!Param->isInvalidDecl() && 13446 RequireCompleteType(Param->getLocation(), Param->getType(), 13447 diag::err_typecheck_decl_incomplete_type)) { 13448 Param->setInvalidDecl(); 13449 HasInvalidParm = true; 13450 } 13451 13452 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13453 // declaration of each parameter shall include an identifier. 13454 if (CheckParameterNames && Param->getIdentifier() == nullptr && 13455 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 13456 // Diagnose this as an extension in C17 and earlier. 13457 if (!getLangOpts().C2x) 13458 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 13459 } 13460 13461 // C99 6.7.5.3p12: 13462 // If the function declarator is not part of a definition of that 13463 // function, parameters may have incomplete type and may use the [*] 13464 // notation in their sequences of declarator specifiers to specify 13465 // variable length array types. 13466 QualType PType = Param->getOriginalType(); 13467 // FIXME: This diagnostic should point the '[*]' if source-location 13468 // information is added for it. 13469 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13470 13471 // If the parameter is a c++ class type and it has to be destructed in the 13472 // callee function, declare the destructor so that it can be called by the 13473 // callee function. Do not perform any direct access check on the dtor here. 13474 if (!Param->isInvalidDecl()) { 13475 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13476 if (!ClassDecl->isInvalidDecl() && 13477 !ClassDecl->hasIrrelevantDestructor() && 13478 !ClassDecl->isDependentContext() && 13479 ClassDecl->isParamDestroyedInCallee()) { 13480 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13481 MarkFunctionReferenced(Param->getLocation(), Destructor); 13482 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13483 } 13484 } 13485 } 13486 13487 // Parameters with the pass_object_size attribute only need to be marked 13488 // constant at function definitions. Because we lack information about 13489 // whether we're on a declaration or definition when we're instantiating the 13490 // attribute, we need to check for constness here. 13491 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13492 if (!Param->getType().isConstQualified()) 13493 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13494 << Attr->getSpelling() << 1; 13495 13496 // Check for parameter names shadowing fields from the class. 13497 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13498 // The owning context for the parameter should be the function, but we 13499 // want to see if this function's declaration context is a record. 13500 DeclContext *DC = Param->getDeclContext(); 13501 if (DC && DC->isFunctionOrMethod()) { 13502 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13503 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13504 RD, /*DeclIsField*/ false); 13505 } 13506 } 13507 } 13508 13509 return HasInvalidParm; 13510 } 13511 13512 Optional<std::pair<CharUnits, CharUnits>> 13513 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 13514 13515 /// Compute the alignment and offset of the base class object given the 13516 /// derived-to-base cast expression and the alignment and offset of the derived 13517 /// class object. 13518 static std::pair<CharUnits, CharUnits> 13519 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 13520 CharUnits BaseAlignment, CharUnits Offset, 13521 ASTContext &Ctx) { 13522 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 13523 ++PathI) { 13524 const CXXBaseSpecifier *Base = *PathI; 13525 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 13526 if (Base->isVirtual()) { 13527 // The complete object may have a lower alignment than the non-virtual 13528 // alignment of the base, in which case the base may be misaligned. Choose 13529 // the smaller of the non-virtual alignment and BaseAlignment, which is a 13530 // conservative lower bound of the complete object alignment. 13531 CharUnits NonVirtualAlignment = 13532 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 13533 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 13534 Offset = CharUnits::Zero(); 13535 } else { 13536 const ASTRecordLayout &RL = 13537 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 13538 Offset += RL.getBaseClassOffset(BaseDecl); 13539 } 13540 DerivedType = Base->getType(); 13541 } 13542 13543 return std::make_pair(BaseAlignment, Offset); 13544 } 13545 13546 /// Compute the alignment and offset of a binary additive operator. 13547 static Optional<std::pair<CharUnits, CharUnits>> 13548 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 13549 bool IsSub, ASTContext &Ctx) { 13550 QualType PointeeType = PtrE->getType()->getPointeeType(); 13551 13552 if (!PointeeType->isConstantSizeType()) 13553 return llvm::None; 13554 13555 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 13556 13557 if (!P) 13558 return llvm::None; 13559 13560 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 13561 if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) { 13562 CharUnits Offset = EltSize * IdxRes->getExtValue(); 13563 if (IsSub) 13564 Offset = -Offset; 13565 return std::make_pair(P->first, P->second + Offset); 13566 } 13567 13568 // If the integer expression isn't a constant expression, compute the lower 13569 // bound of the alignment using the alignment and offset of the pointer 13570 // expression and the element size. 13571 return std::make_pair( 13572 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 13573 CharUnits::Zero()); 13574 } 13575 13576 /// This helper function takes an lvalue expression and returns the alignment of 13577 /// a VarDecl and a constant offset from the VarDecl. 13578 Optional<std::pair<CharUnits, CharUnits>> 13579 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 13580 E = E->IgnoreParens(); 13581 switch (E->getStmtClass()) { 13582 default: 13583 break; 13584 case Stmt::CStyleCastExprClass: 13585 case Stmt::CXXStaticCastExprClass: 13586 case Stmt::ImplicitCastExprClass: { 13587 auto *CE = cast<CastExpr>(E); 13588 const Expr *From = CE->getSubExpr(); 13589 switch (CE->getCastKind()) { 13590 default: 13591 break; 13592 case CK_NoOp: 13593 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13594 case CK_UncheckedDerivedToBase: 13595 case CK_DerivedToBase: { 13596 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13597 if (!P) 13598 break; 13599 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 13600 P->second, Ctx); 13601 } 13602 } 13603 break; 13604 } 13605 case Stmt::ArraySubscriptExprClass: { 13606 auto *ASE = cast<ArraySubscriptExpr>(E); 13607 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 13608 false, Ctx); 13609 } 13610 case Stmt::DeclRefExprClass: { 13611 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 13612 // FIXME: If VD is captured by copy or is an escaping __block variable, 13613 // use the alignment of VD's type. 13614 if (!VD->getType()->isReferenceType()) 13615 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 13616 if (VD->hasInit()) 13617 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 13618 } 13619 break; 13620 } 13621 case Stmt::MemberExprClass: { 13622 auto *ME = cast<MemberExpr>(E); 13623 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 13624 if (!FD || FD->getType()->isReferenceType()) 13625 break; 13626 Optional<std::pair<CharUnits, CharUnits>> P; 13627 if (ME->isArrow()) 13628 P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx); 13629 else 13630 P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 13631 if (!P) 13632 break; 13633 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 13634 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 13635 return std::make_pair(P->first, 13636 P->second + CharUnits::fromQuantity(Offset)); 13637 } 13638 case Stmt::UnaryOperatorClass: { 13639 auto *UO = cast<UnaryOperator>(E); 13640 switch (UO->getOpcode()) { 13641 default: 13642 break; 13643 case UO_Deref: 13644 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 13645 } 13646 break; 13647 } 13648 case Stmt::BinaryOperatorClass: { 13649 auto *BO = cast<BinaryOperator>(E); 13650 auto Opcode = BO->getOpcode(); 13651 switch (Opcode) { 13652 default: 13653 break; 13654 case BO_Comma: 13655 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 13656 } 13657 break; 13658 } 13659 } 13660 return llvm::None; 13661 } 13662 13663 /// This helper function takes a pointer expression and returns the alignment of 13664 /// a VarDecl and a constant offset from the VarDecl. 13665 Optional<std::pair<CharUnits, CharUnits>> 13666 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 13667 E = E->IgnoreParens(); 13668 switch (E->getStmtClass()) { 13669 default: 13670 break; 13671 case Stmt::CStyleCastExprClass: 13672 case Stmt::CXXStaticCastExprClass: 13673 case Stmt::ImplicitCastExprClass: { 13674 auto *CE = cast<CastExpr>(E); 13675 const Expr *From = CE->getSubExpr(); 13676 switch (CE->getCastKind()) { 13677 default: 13678 break; 13679 case CK_NoOp: 13680 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13681 case CK_ArrayToPointerDecay: 13682 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13683 case CK_UncheckedDerivedToBase: 13684 case CK_DerivedToBase: { 13685 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13686 if (!P) 13687 break; 13688 return getDerivedToBaseAlignmentAndOffset( 13689 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 13690 } 13691 } 13692 break; 13693 } 13694 case Stmt::CXXThisExprClass: { 13695 auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl(); 13696 CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment(); 13697 return std::make_pair(Alignment, CharUnits::Zero()); 13698 } 13699 case Stmt::UnaryOperatorClass: { 13700 auto *UO = cast<UnaryOperator>(E); 13701 if (UO->getOpcode() == UO_AddrOf) 13702 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 13703 break; 13704 } 13705 case Stmt::BinaryOperatorClass: { 13706 auto *BO = cast<BinaryOperator>(E); 13707 auto Opcode = BO->getOpcode(); 13708 switch (Opcode) { 13709 default: 13710 break; 13711 case BO_Add: 13712 case BO_Sub: { 13713 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 13714 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 13715 std::swap(LHS, RHS); 13716 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 13717 Ctx); 13718 } 13719 case BO_Comma: 13720 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 13721 } 13722 break; 13723 } 13724 } 13725 return llvm::None; 13726 } 13727 13728 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 13729 // See if we can compute the alignment of a VarDecl and an offset from it. 13730 Optional<std::pair<CharUnits, CharUnits>> P = 13731 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 13732 13733 if (P) 13734 return P->first.alignmentAtOffset(P->second); 13735 13736 // If that failed, return the type's alignment. 13737 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 13738 } 13739 13740 /// CheckCastAlign - Implements -Wcast-align, which warns when a 13741 /// pointer cast increases the alignment requirements. 13742 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 13743 // This is actually a lot of work to potentially be doing on every 13744 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 13745 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 13746 return; 13747 13748 // Ignore dependent types. 13749 if (T->isDependentType() || Op->getType()->isDependentType()) 13750 return; 13751 13752 // Require that the destination be a pointer type. 13753 const PointerType *DestPtr = T->getAs<PointerType>(); 13754 if (!DestPtr) return; 13755 13756 // If the destination has alignment 1, we're done. 13757 QualType DestPointee = DestPtr->getPointeeType(); 13758 if (DestPointee->isIncompleteType()) return; 13759 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 13760 if (DestAlign.isOne()) return; 13761 13762 // Require that the source be a pointer type. 13763 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 13764 if (!SrcPtr) return; 13765 QualType SrcPointee = SrcPtr->getPointeeType(); 13766 13767 // Explicitly allow casts from cv void*. We already implicitly 13768 // allowed casts to cv void*, since they have alignment 1. 13769 // Also allow casts involving incomplete types, which implicitly 13770 // includes 'void'. 13771 if (SrcPointee->isIncompleteType()) return; 13772 13773 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 13774 13775 if (SrcAlign >= DestAlign) return; 13776 13777 Diag(TRange.getBegin(), diag::warn_cast_align) 13778 << Op->getType() << T 13779 << static_cast<unsigned>(SrcAlign.getQuantity()) 13780 << static_cast<unsigned>(DestAlign.getQuantity()) 13781 << TRange << Op->getSourceRange(); 13782 } 13783 13784 /// Check whether this array fits the idiom of a size-one tail padded 13785 /// array member of a struct. 13786 /// 13787 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 13788 /// commonly used to emulate flexible arrays in C89 code. 13789 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 13790 const NamedDecl *ND) { 13791 if (Size != 1 || !ND) return false; 13792 13793 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 13794 if (!FD) return false; 13795 13796 // Don't consider sizes resulting from macro expansions or template argument 13797 // substitution to form C89 tail-padded arrays. 13798 13799 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 13800 while (TInfo) { 13801 TypeLoc TL = TInfo->getTypeLoc(); 13802 // Look through typedefs. 13803 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 13804 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 13805 TInfo = TDL->getTypeSourceInfo(); 13806 continue; 13807 } 13808 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 13809 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 13810 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 13811 return false; 13812 } 13813 break; 13814 } 13815 13816 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 13817 if (!RD) return false; 13818 if (RD->isUnion()) return false; 13819 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13820 if (!CRD->isStandardLayout()) return false; 13821 } 13822 13823 // See if this is the last field decl in the record. 13824 const Decl *D = FD; 13825 while ((D = D->getNextDeclInContext())) 13826 if (isa<FieldDecl>(D)) 13827 return false; 13828 return true; 13829 } 13830 13831 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 13832 const ArraySubscriptExpr *ASE, 13833 bool AllowOnePastEnd, bool IndexNegated) { 13834 // Already diagnosed by the constant evaluator. 13835 if (isConstantEvaluated()) 13836 return; 13837 13838 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 13839 if (IndexExpr->isValueDependent()) 13840 return; 13841 13842 const Type *EffectiveType = 13843 BaseExpr->getType()->getPointeeOrArrayElementType(); 13844 BaseExpr = BaseExpr->IgnoreParenCasts(); 13845 const ConstantArrayType *ArrayTy = 13846 Context.getAsConstantArrayType(BaseExpr->getType()); 13847 13848 if (!ArrayTy) 13849 return; 13850 13851 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 13852 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 13853 return; 13854 13855 Expr::EvalResult Result; 13856 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 13857 return; 13858 13859 llvm::APSInt index = Result.Val.getInt(); 13860 if (IndexNegated) 13861 index = -index; 13862 13863 const NamedDecl *ND = nullptr; 13864 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13865 ND = DRE->getDecl(); 13866 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13867 ND = ME->getMemberDecl(); 13868 13869 if (index.isUnsigned() || !index.isNegative()) { 13870 // It is possible that the type of the base expression after 13871 // IgnoreParenCasts is incomplete, even though the type of the base 13872 // expression before IgnoreParenCasts is complete (see PR39746 for an 13873 // example). In this case we have no information about whether the array 13874 // access exceeds the array bounds. However we can still diagnose an array 13875 // access which precedes the array bounds. 13876 if (BaseType->isIncompleteType()) 13877 return; 13878 13879 llvm::APInt size = ArrayTy->getSize(); 13880 if (!size.isStrictlyPositive()) 13881 return; 13882 13883 if (BaseType != EffectiveType) { 13884 // Make sure we're comparing apples to apples when comparing index to size 13885 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 13886 uint64_t array_typesize = Context.getTypeSize(BaseType); 13887 // Handle ptrarith_typesize being zero, such as when casting to void* 13888 if (!ptrarith_typesize) ptrarith_typesize = 1; 13889 if (ptrarith_typesize != array_typesize) { 13890 // There's a cast to a different size type involved 13891 uint64_t ratio = array_typesize / ptrarith_typesize; 13892 // TODO: Be smarter about handling cases where array_typesize is not a 13893 // multiple of ptrarith_typesize 13894 if (ptrarith_typesize * ratio == array_typesize) 13895 size *= llvm::APInt(size.getBitWidth(), ratio); 13896 } 13897 } 13898 13899 if (size.getBitWidth() > index.getBitWidth()) 13900 index = index.zext(size.getBitWidth()); 13901 else if (size.getBitWidth() < index.getBitWidth()) 13902 size = size.zext(index.getBitWidth()); 13903 13904 // For array subscripting the index must be less than size, but for pointer 13905 // arithmetic also allow the index (offset) to be equal to size since 13906 // computing the next address after the end of the array is legal and 13907 // commonly done e.g. in C++ iterators and range-based for loops. 13908 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13909 return; 13910 13911 // Also don't warn for arrays of size 1 which are members of some 13912 // structure. These are often used to approximate flexible arrays in C89 13913 // code. 13914 if (IsTailPaddedMemberArray(*this, size, ND)) 13915 return; 13916 13917 // Suppress the warning if the subscript expression (as identified by the 13918 // ']' location) and the index expression are both from macro expansions 13919 // within a system header. 13920 if (ASE) { 13921 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 13922 ASE->getRBracketLoc()); 13923 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 13924 SourceLocation IndexLoc = 13925 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 13926 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 13927 return; 13928 } 13929 } 13930 13931 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 13932 if (ASE) 13933 DiagID = diag::warn_array_index_exceeds_bounds; 13934 13935 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13936 PDiag(DiagID) << index.toString(10, true) 13937 << size.toString(10, true) 13938 << (unsigned)size.getLimitedValue(~0U) 13939 << IndexExpr->getSourceRange()); 13940 } else { 13941 unsigned DiagID = diag::warn_array_index_precedes_bounds; 13942 if (!ASE) { 13943 DiagID = diag::warn_ptr_arith_precedes_bounds; 13944 if (index.isNegative()) index = -index; 13945 } 13946 13947 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13948 PDiag(DiagID) << index.toString(10, true) 13949 << IndexExpr->getSourceRange()); 13950 } 13951 13952 if (!ND) { 13953 // Try harder to find a NamedDecl to point at in the note. 13954 while (const ArraySubscriptExpr *ASE = 13955 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 13956 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 13957 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13958 ND = DRE->getDecl(); 13959 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13960 ND = ME->getMemberDecl(); 13961 } 13962 13963 if (ND) 13964 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 13965 PDiag(diag::note_array_declared_here) 13966 << ND->getDeclName()); 13967 } 13968 13969 void Sema::CheckArrayAccess(const Expr *expr) { 13970 int AllowOnePastEnd = 0; 13971 while (expr) { 13972 expr = expr->IgnoreParenImpCasts(); 13973 switch (expr->getStmtClass()) { 13974 case Stmt::ArraySubscriptExprClass: { 13975 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 13976 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 13977 AllowOnePastEnd > 0); 13978 expr = ASE->getBase(); 13979 break; 13980 } 13981 case Stmt::MemberExprClass: { 13982 expr = cast<MemberExpr>(expr)->getBase(); 13983 break; 13984 } 13985 case Stmt::OMPArraySectionExprClass: { 13986 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 13987 if (ASE->getLowerBound()) 13988 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 13989 /*ASE=*/nullptr, AllowOnePastEnd > 0); 13990 return; 13991 } 13992 case Stmt::UnaryOperatorClass: { 13993 // Only unwrap the * and & unary operators 13994 const UnaryOperator *UO = cast<UnaryOperator>(expr); 13995 expr = UO->getSubExpr(); 13996 switch (UO->getOpcode()) { 13997 case UO_AddrOf: 13998 AllowOnePastEnd++; 13999 break; 14000 case UO_Deref: 14001 AllowOnePastEnd--; 14002 break; 14003 default: 14004 return; 14005 } 14006 break; 14007 } 14008 case Stmt::ConditionalOperatorClass: { 14009 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 14010 if (const Expr *lhs = cond->getLHS()) 14011 CheckArrayAccess(lhs); 14012 if (const Expr *rhs = cond->getRHS()) 14013 CheckArrayAccess(rhs); 14014 return; 14015 } 14016 case Stmt::CXXOperatorCallExprClass: { 14017 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 14018 for (const auto *Arg : OCE->arguments()) 14019 CheckArrayAccess(Arg); 14020 return; 14021 } 14022 default: 14023 return; 14024 } 14025 } 14026 } 14027 14028 //===--- CHECK: Objective-C retain cycles ----------------------------------// 14029 14030 namespace { 14031 14032 struct RetainCycleOwner { 14033 VarDecl *Variable = nullptr; 14034 SourceRange Range; 14035 SourceLocation Loc; 14036 bool Indirect = false; 14037 14038 RetainCycleOwner() = default; 14039 14040 void setLocsFrom(Expr *e) { 14041 Loc = e->getExprLoc(); 14042 Range = e->getSourceRange(); 14043 } 14044 }; 14045 14046 } // namespace 14047 14048 /// Consider whether capturing the given variable can possibly lead to 14049 /// a retain cycle. 14050 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 14051 // In ARC, it's captured strongly iff the variable has __strong 14052 // lifetime. In MRR, it's captured strongly if the variable is 14053 // __block and has an appropriate type. 14054 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14055 return false; 14056 14057 owner.Variable = var; 14058 if (ref) 14059 owner.setLocsFrom(ref); 14060 return true; 14061 } 14062 14063 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 14064 while (true) { 14065 e = e->IgnoreParens(); 14066 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 14067 switch (cast->getCastKind()) { 14068 case CK_BitCast: 14069 case CK_LValueBitCast: 14070 case CK_LValueToRValue: 14071 case CK_ARCReclaimReturnedObject: 14072 e = cast->getSubExpr(); 14073 continue; 14074 14075 default: 14076 return false; 14077 } 14078 } 14079 14080 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 14081 ObjCIvarDecl *ivar = ref->getDecl(); 14082 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 14083 return false; 14084 14085 // Try to find a retain cycle in the base. 14086 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 14087 return false; 14088 14089 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 14090 owner.Indirect = true; 14091 return true; 14092 } 14093 14094 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 14095 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 14096 if (!var) return false; 14097 return considerVariable(var, ref, owner); 14098 } 14099 14100 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 14101 if (member->isArrow()) return false; 14102 14103 // Don't count this as an indirect ownership. 14104 e = member->getBase(); 14105 continue; 14106 } 14107 14108 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 14109 // Only pay attention to pseudo-objects on property references. 14110 ObjCPropertyRefExpr *pre 14111 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 14112 ->IgnoreParens()); 14113 if (!pre) return false; 14114 if (pre->isImplicitProperty()) return false; 14115 ObjCPropertyDecl *property = pre->getExplicitProperty(); 14116 if (!property->isRetaining() && 14117 !(property->getPropertyIvarDecl() && 14118 property->getPropertyIvarDecl()->getType() 14119 .getObjCLifetime() == Qualifiers::OCL_Strong)) 14120 return false; 14121 14122 owner.Indirect = true; 14123 if (pre->isSuperReceiver()) { 14124 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 14125 if (!owner.Variable) 14126 return false; 14127 owner.Loc = pre->getLocation(); 14128 owner.Range = pre->getSourceRange(); 14129 return true; 14130 } 14131 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 14132 ->getSourceExpr()); 14133 continue; 14134 } 14135 14136 // Array ivars? 14137 14138 return false; 14139 } 14140 } 14141 14142 namespace { 14143 14144 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 14145 ASTContext &Context; 14146 VarDecl *Variable; 14147 Expr *Capturer = nullptr; 14148 bool VarWillBeReased = false; 14149 14150 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 14151 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 14152 Context(Context), Variable(variable) {} 14153 14154 void VisitDeclRefExpr(DeclRefExpr *ref) { 14155 if (ref->getDecl() == Variable && !Capturer) 14156 Capturer = ref; 14157 } 14158 14159 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 14160 if (Capturer) return; 14161 Visit(ref->getBase()); 14162 if (Capturer && ref->isFreeIvar()) 14163 Capturer = ref; 14164 } 14165 14166 void VisitBlockExpr(BlockExpr *block) { 14167 // Look inside nested blocks 14168 if (block->getBlockDecl()->capturesVariable(Variable)) 14169 Visit(block->getBlockDecl()->getBody()); 14170 } 14171 14172 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 14173 if (Capturer) return; 14174 if (OVE->getSourceExpr()) 14175 Visit(OVE->getSourceExpr()); 14176 } 14177 14178 void VisitBinaryOperator(BinaryOperator *BinOp) { 14179 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 14180 return; 14181 Expr *LHS = BinOp->getLHS(); 14182 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 14183 if (DRE->getDecl() != Variable) 14184 return; 14185 if (Expr *RHS = BinOp->getRHS()) { 14186 RHS = RHS->IgnoreParenCasts(); 14187 Optional<llvm::APSInt> Value; 14188 VarWillBeReased = 14189 (RHS && (Value = RHS->getIntegerConstantExpr(Context)) && 14190 *Value == 0); 14191 } 14192 } 14193 } 14194 }; 14195 14196 } // namespace 14197 14198 /// Check whether the given argument is a block which captures a 14199 /// variable. 14200 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 14201 assert(owner.Variable && owner.Loc.isValid()); 14202 14203 e = e->IgnoreParenCasts(); 14204 14205 // Look through [^{...} copy] and Block_copy(^{...}). 14206 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 14207 Selector Cmd = ME->getSelector(); 14208 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 14209 e = ME->getInstanceReceiver(); 14210 if (!e) 14211 return nullptr; 14212 e = e->IgnoreParenCasts(); 14213 } 14214 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 14215 if (CE->getNumArgs() == 1) { 14216 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 14217 if (Fn) { 14218 const IdentifierInfo *FnI = Fn->getIdentifier(); 14219 if (FnI && FnI->isStr("_Block_copy")) { 14220 e = CE->getArg(0)->IgnoreParenCasts(); 14221 } 14222 } 14223 } 14224 } 14225 14226 BlockExpr *block = dyn_cast<BlockExpr>(e); 14227 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 14228 return nullptr; 14229 14230 FindCaptureVisitor visitor(S.Context, owner.Variable); 14231 visitor.Visit(block->getBlockDecl()->getBody()); 14232 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 14233 } 14234 14235 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 14236 RetainCycleOwner &owner) { 14237 assert(capturer); 14238 assert(owner.Variable && owner.Loc.isValid()); 14239 14240 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 14241 << owner.Variable << capturer->getSourceRange(); 14242 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 14243 << owner.Indirect << owner.Range; 14244 } 14245 14246 /// Check for a keyword selector that starts with the word 'add' or 14247 /// 'set'. 14248 static bool isSetterLikeSelector(Selector sel) { 14249 if (sel.isUnarySelector()) return false; 14250 14251 StringRef str = sel.getNameForSlot(0); 14252 while (!str.empty() && str.front() == '_') str = str.substr(1); 14253 if (str.startswith("set")) 14254 str = str.substr(3); 14255 else if (str.startswith("add")) { 14256 // Specially allow 'addOperationWithBlock:'. 14257 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 14258 return false; 14259 str = str.substr(3); 14260 } 14261 else 14262 return false; 14263 14264 if (str.empty()) return true; 14265 return !isLowercase(str.front()); 14266 } 14267 14268 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 14269 ObjCMessageExpr *Message) { 14270 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 14271 Message->getReceiverInterface(), 14272 NSAPI::ClassId_NSMutableArray); 14273 if (!IsMutableArray) { 14274 return None; 14275 } 14276 14277 Selector Sel = Message->getSelector(); 14278 14279 Optional<NSAPI::NSArrayMethodKind> MKOpt = 14280 S.NSAPIObj->getNSArrayMethodKind(Sel); 14281 if (!MKOpt) { 14282 return None; 14283 } 14284 14285 NSAPI::NSArrayMethodKind MK = *MKOpt; 14286 14287 switch (MK) { 14288 case NSAPI::NSMutableArr_addObject: 14289 case NSAPI::NSMutableArr_insertObjectAtIndex: 14290 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 14291 return 0; 14292 case NSAPI::NSMutableArr_replaceObjectAtIndex: 14293 return 1; 14294 14295 default: 14296 return None; 14297 } 14298 14299 return None; 14300 } 14301 14302 static 14303 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 14304 ObjCMessageExpr *Message) { 14305 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 14306 Message->getReceiverInterface(), 14307 NSAPI::ClassId_NSMutableDictionary); 14308 if (!IsMutableDictionary) { 14309 return None; 14310 } 14311 14312 Selector Sel = Message->getSelector(); 14313 14314 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 14315 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 14316 if (!MKOpt) { 14317 return None; 14318 } 14319 14320 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 14321 14322 switch (MK) { 14323 case NSAPI::NSMutableDict_setObjectForKey: 14324 case NSAPI::NSMutableDict_setValueForKey: 14325 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 14326 return 0; 14327 14328 default: 14329 return None; 14330 } 14331 14332 return None; 14333 } 14334 14335 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14336 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14337 Message->getReceiverInterface(), 14338 NSAPI::ClassId_NSMutableSet); 14339 14340 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14341 Message->getReceiverInterface(), 14342 NSAPI::ClassId_NSMutableOrderedSet); 14343 if (!IsMutableSet && !IsMutableOrderedSet) { 14344 return None; 14345 } 14346 14347 Selector Sel = Message->getSelector(); 14348 14349 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 14350 if (!MKOpt) { 14351 return None; 14352 } 14353 14354 NSAPI::NSSetMethodKind MK = *MKOpt; 14355 14356 switch (MK) { 14357 case NSAPI::NSMutableSet_addObject: 14358 case NSAPI::NSOrderedSet_setObjectAtIndex: 14359 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 14360 case NSAPI::NSOrderedSet_insertObjectAtIndex: 14361 return 0; 14362 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 14363 return 1; 14364 } 14365 14366 return None; 14367 } 14368 14369 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 14370 if (!Message->isInstanceMessage()) { 14371 return; 14372 } 14373 14374 Optional<int> ArgOpt; 14375 14376 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 14377 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 14378 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 14379 return; 14380 } 14381 14382 int ArgIndex = *ArgOpt; 14383 14384 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 14385 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 14386 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 14387 } 14388 14389 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 14390 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14391 if (ArgRE->isObjCSelfExpr()) { 14392 Diag(Message->getSourceRange().getBegin(), 14393 diag::warn_objc_circular_container) 14394 << ArgRE->getDecl() << StringRef("'super'"); 14395 } 14396 } 14397 } else { 14398 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 14399 14400 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 14401 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 14402 } 14403 14404 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 14405 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14406 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 14407 ValueDecl *Decl = ReceiverRE->getDecl(); 14408 Diag(Message->getSourceRange().getBegin(), 14409 diag::warn_objc_circular_container) 14410 << Decl << Decl; 14411 if (!ArgRE->isObjCSelfExpr()) { 14412 Diag(Decl->getLocation(), 14413 diag::note_objc_circular_container_declared_here) 14414 << Decl; 14415 } 14416 } 14417 } 14418 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 14419 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 14420 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 14421 ObjCIvarDecl *Decl = IvarRE->getDecl(); 14422 Diag(Message->getSourceRange().getBegin(), 14423 diag::warn_objc_circular_container) 14424 << Decl << Decl; 14425 Diag(Decl->getLocation(), 14426 diag::note_objc_circular_container_declared_here) 14427 << Decl; 14428 } 14429 } 14430 } 14431 } 14432 } 14433 14434 /// Check a message send to see if it's likely to cause a retain cycle. 14435 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 14436 // Only check instance methods whose selector looks like a setter. 14437 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 14438 return; 14439 14440 // Try to find a variable that the receiver is strongly owned by. 14441 RetainCycleOwner owner; 14442 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 14443 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 14444 return; 14445 } else { 14446 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 14447 owner.Variable = getCurMethodDecl()->getSelfDecl(); 14448 owner.Loc = msg->getSuperLoc(); 14449 owner.Range = msg->getSuperLoc(); 14450 } 14451 14452 // Check whether the receiver is captured by any of the arguments. 14453 const ObjCMethodDecl *MD = msg->getMethodDecl(); 14454 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 14455 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 14456 // noescape blocks should not be retained by the method. 14457 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 14458 continue; 14459 return diagnoseRetainCycle(*this, capturer, owner); 14460 } 14461 } 14462 } 14463 14464 /// Check a property assign to see if it's likely to cause a retain cycle. 14465 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 14466 RetainCycleOwner owner; 14467 if (!findRetainCycleOwner(*this, receiver, owner)) 14468 return; 14469 14470 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 14471 diagnoseRetainCycle(*this, capturer, owner); 14472 } 14473 14474 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 14475 RetainCycleOwner Owner; 14476 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 14477 return; 14478 14479 // Because we don't have an expression for the variable, we have to set the 14480 // location explicitly here. 14481 Owner.Loc = Var->getLocation(); 14482 Owner.Range = Var->getSourceRange(); 14483 14484 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 14485 diagnoseRetainCycle(*this, Capturer, Owner); 14486 } 14487 14488 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 14489 Expr *RHS, bool isProperty) { 14490 // Check if RHS is an Objective-C object literal, which also can get 14491 // immediately zapped in a weak reference. Note that we explicitly 14492 // allow ObjCStringLiterals, since those are designed to never really die. 14493 RHS = RHS->IgnoreParenImpCasts(); 14494 14495 // This enum needs to match with the 'select' in 14496 // warn_objc_arc_literal_assign (off-by-1). 14497 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 14498 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 14499 return false; 14500 14501 S.Diag(Loc, diag::warn_arc_literal_assign) 14502 << (unsigned) Kind 14503 << (isProperty ? 0 : 1) 14504 << RHS->getSourceRange(); 14505 14506 return true; 14507 } 14508 14509 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 14510 Qualifiers::ObjCLifetime LT, 14511 Expr *RHS, bool isProperty) { 14512 // Strip off any implicit cast added to get to the one ARC-specific. 14513 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14514 if (cast->getCastKind() == CK_ARCConsumeObject) { 14515 S.Diag(Loc, diag::warn_arc_retained_assign) 14516 << (LT == Qualifiers::OCL_ExplicitNone) 14517 << (isProperty ? 0 : 1) 14518 << RHS->getSourceRange(); 14519 return true; 14520 } 14521 RHS = cast->getSubExpr(); 14522 } 14523 14524 if (LT == Qualifiers::OCL_Weak && 14525 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 14526 return true; 14527 14528 return false; 14529 } 14530 14531 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 14532 QualType LHS, Expr *RHS) { 14533 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 14534 14535 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 14536 return false; 14537 14538 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 14539 return true; 14540 14541 return false; 14542 } 14543 14544 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 14545 Expr *LHS, Expr *RHS) { 14546 QualType LHSType; 14547 // PropertyRef on LHS type need be directly obtained from 14548 // its declaration as it has a PseudoType. 14549 ObjCPropertyRefExpr *PRE 14550 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 14551 if (PRE && !PRE->isImplicitProperty()) { 14552 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14553 if (PD) 14554 LHSType = PD->getType(); 14555 } 14556 14557 if (LHSType.isNull()) 14558 LHSType = LHS->getType(); 14559 14560 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 14561 14562 if (LT == Qualifiers::OCL_Weak) { 14563 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 14564 getCurFunction()->markSafeWeakUse(LHS); 14565 } 14566 14567 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 14568 return; 14569 14570 // FIXME. Check for other life times. 14571 if (LT != Qualifiers::OCL_None) 14572 return; 14573 14574 if (PRE) { 14575 if (PRE->isImplicitProperty()) 14576 return; 14577 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14578 if (!PD) 14579 return; 14580 14581 unsigned Attributes = PD->getPropertyAttributes(); 14582 if (Attributes & ObjCPropertyAttribute::kind_assign) { 14583 // when 'assign' attribute was not explicitly specified 14584 // by user, ignore it and rely on property type itself 14585 // for lifetime info. 14586 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 14587 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 14588 LHSType->isObjCRetainableType()) 14589 return; 14590 14591 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14592 if (cast->getCastKind() == CK_ARCConsumeObject) { 14593 Diag(Loc, diag::warn_arc_retained_property_assign) 14594 << RHS->getSourceRange(); 14595 return; 14596 } 14597 RHS = cast->getSubExpr(); 14598 } 14599 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 14600 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 14601 return; 14602 } 14603 } 14604 } 14605 14606 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 14607 14608 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 14609 SourceLocation StmtLoc, 14610 const NullStmt *Body) { 14611 // Do not warn if the body is a macro that expands to nothing, e.g: 14612 // 14613 // #define CALL(x) 14614 // if (condition) 14615 // CALL(0); 14616 if (Body->hasLeadingEmptyMacro()) 14617 return false; 14618 14619 // Get line numbers of statement and body. 14620 bool StmtLineInvalid; 14621 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 14622 &StmtLineInvalid); 14623 if (StmtLineInvalid) 14624 return false; 14625 14626 bool BodyLineInvalid; 14627 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 14628 &BodyLineInvalid); 14629 if (BodyLineInvalid) 14630 return false; 14631 14632 // Warn if null statement and body are on the same line. 14633 if (StmtLine != BodyLine) 14634 return false; 14635 14636 return true; 14637 } 14638 14639 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 14640 const Stmt *Body, 14641 unsigned DiagID) { 14642 // Since this is a syntactic check, don't emit diagnostic for template 14643 // instantiations, this just adds noise. 14644 if (CurrentInstantiationScope) 14645 return; 14646 14647 // The body should be a null statement. 14648 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14649 if (!NBody) 14650 return; 14651 14652 // Do the usual checks. 14653 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14654 return; 14655 14656 Diag(NBody->getSemiLoc(), DiagID); 14657 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14658 } 14659 14660 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 14661 const Stmt *PossibleBody) { 14662 assert(!CurrentInstantiationScope); // Ensured by caller 14663 14664 SourceLocation StmtLoc; 14665 const Stmt *Body; 14666 unsigned DiagID; 14667 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 14668 StmtLoc = FS->getRParenLoc(); 14669 Body = FS->getBody(); 14670 DiagID = diag::warn_empty_for_body; 14671 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 14672 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 14673 Body = WS->getBody(); 14674 DiagID = diag::warn_empty_while_body; 14675 } else 14676 return; // Neither `for' nor `while'. 14677 14678 // The body should be a null statement. 14679 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14680 if (!NBody) 14681 return; 14682 14683 // Skip expensive checks if diagnostic is disabled. 14684 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 14685 return; 14686 14687 // Do the usual checks. 14688 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14689 return; 14690 14691 // `for(...);' and `while(...);' are popular idioms, so in order to keep 14692 // noise level low, emit diagnostics only if for/while is followed by a 14693 // CompoundStmt, e.g.: 14694 // for (int i = 0; i < n; i++); 14695 // { 14696 // a(i); 14697 // } 14698 // or if for/while is followed by a statement with more indentation 14699 // than for/while itself: 14700 // for (int i = 0; i < n; i++); 14701 // a(i); 14702 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 14703 if (!ProbableTypo) { 14704 bool BodyColInvalid; 14705 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 14706 PossibleBody->getBeginLoc(), &BodyColInvalid); 14707 if (BodyColInvalid) 14708 return; 14709 14710 bool StmtColInvalid; 14711 unsigned StmtCol = 14712 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 14713 if (StmtColInvalid) 14714 return; 14715 14716 if (BodyCol > StmtCol) 14717 ProbableTypo = true; 14718 } 14719 14720 if (ProbableTypo) { 14721 Diag(NBody->getSemiLoc(), DiagID); 14722 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14723 } 14724 } 14725 14726 //===--- CHECK: Warn on self move with std::move. -------------------------===// 14727 14728 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 14729 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 14730 SourceLocation OpLoc) { 14731 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 14732 return; 14733 14734 if (inTemplateInstantiation()) 14735 return; 14736 14737 // Strip parens and casts away. 14738 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14739 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14740 14741 // Check for a call expression 14742 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 14743 if (!CE || CE->getNumArgs() != 1) 14744 return; 14745 14746 // Check for a call to std::move 14747 if (!CE->isCallToStdMove()) 14748 return; 14749 14750 // Get argument from std::move 14751 RHSExpr = CE->getArg(0); 14752 14753 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14754 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14755 14756 // Two DeclRefExpr's, check that the decls are the same. 14757 if (LHSDeclRef && RHSDeclRef) { 14758 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14759 return; 14760 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14761 RHSDeclRef->getDecl()->getCanonicalDecl()) 14762 return; 14763 14764 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14765 << LHSExpr->getSourceRange() 14766 << RHSExpr->getSourceRange(); 14767 return; 14768 } 14769 14770 // Member variables require a different approach to check for self moves. 14771 // MemberExpr's are the same if every nested MemberExpr refers to the same 14772 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 14773 // the base Expr's are CXXThisExpr's. 14774 const Expr *LHSBase = LHSExpr; 14775 const Expr *RHSBase = RHSExpr; 14776 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 14777 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 14778 if (!LHSME || !RHSME) 14779 return; 14780 14781 while (LHSME && RHSME) { 14782 if (LHSME->getMemberDecl()->getCanonicalDecl() != 14783 RHSME->getMemberDecl()->getCanonicalDecl()) 14784 return; 14785 14786 LHSBase = LHSME->getBase(); 14787 RHSBase = RHSME->getBase(); 14788 LHSME = dyn_cast<MemberExpr>(LHSBase); 14789 RHSME = dyn_cast<MemberExpr>(RHSBase); 14790 } 14791 14792 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 14793 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 14794 if (LHSDeclRef && RHSDeclRef) { 14795 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14796 return; 14797 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14798 RHSDeclRef->getDecl()->getCanonicalDecl()) 14799 return; 14800 14801 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14802 << LHSExpr->getSourceRange() 14803 << RHSExpr->getSourceRange(); 14804 return; 14805 } 14806 14807 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 14808 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14809 << LHSExpr->getSourceRange() 14810 << RHSExpr->getSourceRange(); 14811 } 14812 14813 //===--- Layout compatibility ----------------------------------------------// 14814 14815 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 14816 14817 /// Check if two enumeration types are layout-compatible. 14818 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 14819 // C++11 [dcl.enum] p8: 14820 // Two enumeration types are layout-compatible if they have the same 14821 // underlying type. 14822 return ED1->isComplete() && ED2->isComplete() && 14823 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 14824 } 14825 14826 /// Check if two fields are layout-compatible. 14827 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 14828 FieldDecl *Field2) { 14829 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 14830 return false; 14831 14832 if (Field1->isBitField() != Field2->isBitField()) 14833 return false; 14834 14835 if (Field1->isBitField()) { 14836 // Make sure that the bit-fields are the same length. 14837 unsigned Bits1 = Field1->getBitWidthValue(C); 14838 unsigned Bits2 = Field2->getBitWidthValue(C); 14839 14840 if (Bits1 != Bits2) 14841 return false; 14842 } 14843 14844 return true; 14845 } 14846 14847 /// Check if two standard-layout structs are layout-compatible. 14848 /// (C++11 [class.mem] p17) 14849 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 14850 RecordDecl *RD2) { 14851 // If both records are C++ classes, check that base classes match. 14852 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 14853 // If one of records is a CXXRecordDecl we are in C++ mode, 14854 // thus the other one is a CXXRecordDecl, too. 14855 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 14856 // Check number of base classes. 14857 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 14858 return false; 14859 14860 // Check the base classes. 14861 for (CXXRecordDecl::base_class_const_iterator 14862 Base1 = D1CXX->bases_begin(), 14863 BaseEnd1 = D1CXX->bases_end(), 14864 Base2 = D2CXX->bases_begin(); 14865 Base1 != BaseEnd1; 14866 ++Base1, ++Base2) { 14867 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 14868 return false; 14869 } 14870 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 14871 // If only RD2 is a C++ class, it should have zero base classes. 14872 if (D2CXX->getNumBases() > 0) 14873 return false; 14874 } 14875 14876 // Check the fields. 14877 RecordDecl::field_iterator Field2 = RD2->field_begin(), 14878 Field2End = RD2->field_end(), 14879 Field1 = RD1->field_begin(), 14880 Field1End = RD1->field_end(); 14881 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 14882 if (!isLayoutCompatible(C, *Field1, *Field2)) 14883 return false; 14884 } 14885 if (Field1 != Field1End || Field2 != Field2End) 14886 return false; 14887 14888 return true; 14889 } 14890 14891 /// Check if two standard-layout unions are layout-compatible. 14892 /// (C++11 [class.mem] p18) 14893 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 14894 RecordDecl *RD2) { 14895 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 14896 for (auto *Field2 : RD2->fields()) 14897 UnmatchedFields.insert(Field2); 14898 14899 for (auto *Field1 : RD1->fields()) { 14900 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 14901 I = UnmatchedFields.begin(), 14902 E = UnmatchedFields.end(); 14903 14904 for ( ; I != E; ++I) { 14905 if (isLayoutCompatible(C, Field1, *I)) { 14906 bool Result = UnmatchedFields.erase(*I); 14907 (void) Result; 14908 assert(Result); 14909 break; 14910 } 14911 } 14912 if (I == E) 14913 return false; 14914 } 14915 14916 return UnmatchedFields.empty(); 14917 } 14918 14919 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 14920 RecordDecl *RD2) { 14921 if (RD1->isUnion() != RD2->isUnion()) 14922 return false; 14923 14924 if (RD1->isUnion()) 14925 return isLayoutCompatibleUnion(C, RD1, RD2); 14926 else 14927 return isLayoutCompatibleStruct(C, RD1, RD2); 14928 } 14929 14930 /// Check if two types are layout-compatible in C++11 sense. 14931 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 14932 if (T1.isNull() || T2.isNull()) 14933 return false; 14934 14935 // C++11 [basic.types] p11: 14936 // If two types T1 and T2 are the same type, then T1 and T2 are 14937 // layout-compatible types. 14938 if (C.hasSameType(T1, T2)) 14939 return true; 14940 14941 T1 = T1.getCanonicalType().getUnqualifiedType(); 14942 T2 = T2.getCanonicalType().getUnqualifiedType(); 14943 14944 const Type::TypeClass TC1 = T1->getTypeClass(); 14945 const Type::TypeClass TC2 = T2->getTypeClass(); 14946 14947 if (TC1 != TC2) 14948 return false; 14949 14950 if (TC1 == Type::Enum) { 14951 return isLayoutCompatible(C, 14952 cast<EnumType>(T1)->getDecl(), 14953 cast<EnumType>(T2)->getDecl()); 14954 } else if (TC1 == Type::Record) { 14955 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 14956 return false; 14957 14958 return isLayoutCompatible(C, 14959 cast<RecordType>(T1)->getDecl(), 14960 cast<RecordType>(T2)->getDecl()); 14961 } 14962 14963 return false; 14964 } 14965 14966 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 14967 14968 /// Given a type tag expression find the type tag itself. 14969 /// 14970 /// \param TypeExpr Type tag expression, as it appears in user's code. 14971 /// 14972 /// \param VD Declaration of an identifier that appears in a type tag. 14973 /// 14974 /// \param MagicValue Type tag magic value. 14975 /// 14976 /// \param isConstantEvaluated wether the evalaution should be performed in 14977 14978 /// constant context. 14979 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 14980 const ValueDecl **VD, uint64_t *MagicValue, 14981 bool isConstantEvaluated) { 14982 while(true) { 14983 if (!TypeExpr) 14984 return false; 14985 14986 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 14987 14988 switch (TypeExpr->getStmtClass()) { 14989 case Stmt::UnaryOperatorClass: { 14990 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 14991 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 14992 TypeExpr = UO->getSubExpr(); 14993 continue; 14994 } 14995 return false; 14996 } 14997 14998 case Stmt::DeclRefExprClass: { 14999 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 15000 *VD = DRE->getDecl(); 15001 return true; 15002 } 15003 15004 case Stmt::IntegerLiteralClass: { 15005 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 15006 llvm::APInt MagicValueAPInt = IL->getValue(); 15007 if (MagicValueAPInt.getActiveBits() <= 64) { 15008 *MagicValue = MagicValueAPInt.getZExtValue(); 15009 return true; 15010 } else 15011 return false; 15012 } 15013 15014 case Stmt::BinaryConditionalOperatorClass: 15015 case Stmt::ConditionalOperatorClass: { 15016 const AbstractConditionalOperator *ACO = 15017 cast<AbstractConditionalOperator>(TypeExpr); 15018 bool Result; 15019 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 15020 isConstantEvaluated)) { 15021 if (Result) 15022 TypeExpr = ACO->getTrueExpr(); 15023 else 15024 TypeExpr = ACO->getFalseExpr(); 15025 continue; 15026 } 15027 return false; 15028 } 15029 15030 case Stmt::BinaryOperatorClass: { 15031 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 15032 if (BO->getOpcode() == BO_Comma) { 15033 TypeExpr = BO->getRHS(); 15034 continue; 15035 } 15036 return false; 15037 } 15038 15039 default: 15040 return false; 15041 } 15042 } 15043 } 15044 15045 /// Retrieve the C type corresponding to type tag TypeExpr. 15046 /// 15047 /// \param TypeExpr Expression that specifies a type tag. 15048 /// 15049 /// \param MagicValues Registered magic values. 15050 /// 15051 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 15052 /// kind. 15053 /// 15054 /// \param TypeInfo Information about the corresponding C type. 15055 /// 15056 /// \param isConstantEvaluated wether the evalaution should be performed in 15057 /// constant context. 15058 /// 15059 /// \returns true if the corresponding C type was found. 15060 static bool GetMatchingCType( 15061 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 15062 const ASTContext &Ctx, 15063 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 15064 *MagicValues, 15065 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 15066 bool isConstantEvaluated) { 15067 FoundWrongKind = false; 15068 15069 // Variable declaration that has type_tag_for_datatype attribute. 15070 const ValueDecl *VD = nullptr; 15071 15072 uint64_t MagicValue; 15073 15074 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 15075 return false; 15076 15077 if (VD) { 15078 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 15079 if (I->getArgumentKind() != ArgumentKind) { 15080 FoundWrongKind = true; 15081 return false; 15082 } 15083 TypeInfo.Type = I->getMatchingCType(); 15084 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 15085 TypeInfo.MustBeNull = I->getMustBeNull(); 15086 return true; 15087 } 15088 return false; 15089 } 15090 15091 if (!MagicValues) 15092 return false; 15093 15094 llvm::DenseMap<Sema::TypeTagMagicValue, 15095 Sema::TypeTagData>::const_iterator I = 15096 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 15097 if (I == MagicValues->end()) 15098 return false; 15099 15100 TypeInfo = I->second; 15101 return true; 15102 } 15103 15104 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 15105 uint64_t MagicValue, QualType Type, 15106 bool LayoutCompatible, 15107 bool MustBeNull) { 15108 if (!TypeTagForDatatypeMagicValues) 15109 TypeTagForDatatypeMagicValues.reset( 15110 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 15111 15112 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 15113 (*TypeTagForDatatypeMagicValues)[Magic] = 15114 TypeTagData(Type, LayoutCompatible, MustBeNull); 15115 } 15116 15117 static bool IsSameCharType(QualType T1, QualType T2) { 15118 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 15119 if (!BT1) 15120 return false; 15121 15122 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 15123 if (!BT2) 15124 return false; 15125 15126 BuiltinType::Kind T1Kind = BT1->getKind(); 15127 BuiltinType::Kind T2Kind = BT2->getKind(); 15128 15129 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 15130 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 15131 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 15132 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 15133 } 15134 15135 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 15136 const ArrayRef<const Expr *> ExprArgs, 15137 SourceLocation CallSiteLoc) { 15138 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 15139 bool IsPointerAttr = Attr->getIsPointer(); 15140 15141 // Retrieve the argument representing the 'type_tag'. 15142 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 15143 if (TypeTagIdxAST >= ExprArgs.size()) { 15144 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15145 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 15146 return; 15147 } 15148 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 15149 bool FoundWrongKind; 15150 TypeTagData TypeInfo; 15151 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 15152 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 15153 TypeInfo, isConstantEvaluated())) { 15154 if (FoundWrongKind) 15155 Diag(TypeTagExpr->getExprLoc(), 15156 diag::warn_type_tag_for_datatype_wrong_kind) 15157 << TypeTagExpr->getSourceRange(); 15158 return; 15159 } 15160 15161 // Retrieve the argument representing the 'arg_idx'. 15162 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 15163 if (ArgumentIdxAST >= ExprArgs.size()) { 15164 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 15165 << 1 << Attr->getArgumentIdx().getSourceIndex(); 15166 return; 15167 } 15168 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 15169 if (IsPointerAttr) { 15170 // Skip implicit cast of pointer to `void *' (as a function argument). 15171 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 15172 if (ICE->getType()->isVoidPointerType() && 15173 ICE->getCastKind() == CK_BitCast) 15174 ArgumentExpr = ICE->getSubExpr(); 15175 } 15176 QualType ArgumentType = ArgumentExpr->getType(); 15177 15178 // Passing a `void*' pointer shouldn't trigger a warning. 15179 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 15180 return; 15181 15182 if (TypeInfo.MustBeNull) { 15183 // Type tag with matching void type requires a null pointer. 15184 if (!ArgumentExpr->isNullPointerConstant(Context, 15185 Expr::NPC_ValueDependentIsNotNull)) { 15186 Diag(ArgumentExpr->getExprLoc(), 15187 diag::warn_type_safety_null_pointer_required) 15188 << ArgumentKind->getName() 15189 << ArgumentExpr->getSourceRange() 15190 << TypeTagExpr->getSourceRange(); 15191 } 15192 return; 15193 } 15194 15195 QualType RequiredType = TypeInfo.Type; 15196 if (IsPointerAttr) 15197 RequiredType = Context.getPointerType(RequiredType); 15198 15199 bool mismatch = false; 15200 if (!TypeInfo.LayoutCompatible) { 15201 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 15202 15203 // C++11 [basic.fundamental] p1: 15204 // Plain char, signed char, and unsigned char are three distinct types. 15205 // 15206 // But we treat plain `char' as equivalent to `signed char' or `unsigned 15207 // char' depending on the current char signedness mode. 15208 if (mismatch) 15209 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 15210 RequiredType->getPointeeType())) || 15211 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 15212 mismatch = false; 15213 } else 15214 if (IsPointerAttr) 15215 mismatch = !isLayoutCompatible(Context, 15216 ArgumentType->getPointeeType(), 15217 RequiredType->getPointeeType()); 15218 else 15219 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 15220 15221 if (mismatch) 15222 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 15223 << ArgumentType << ArgumentKind 15224 << TypeInfo.LayoutCompatible << RequiredType 15225 << ArgumentExpr->getSourceRange() 15226 << TypeTagExpr->getSourceRange(); 15227 } 15228 15229 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 15230 CharUnits Alignment) { 15231 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 15232 } 15233 15234 void Sema::DiagnoseMisalignedMembers() { 15235 for (MisalignedMember &m : MisalignedMembers) { 15236 const NamedDecl *ND = m.RD; 15237 if (ND->getName().empty()) { 15238 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 15239 ND = TD; 15240 } 15241 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 15242 << m.MD << ND << m.E->getSourceRange(); 15243 } 15244 MisalignedMembers.clear(); 15245 } 15246 15247 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 15248 E = E->IgnoreParens(); 15249 if (!T->isPointerType() && !T->isIntegerType()) 15250 return; 15251 if (isa<UnaryOperator>(E) && 15252 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 15253 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 15254 if (isa<MemberExpr>(Op)) { 15255 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 15256 if (MA != MisalignedMembers.end() && 15257 (T->isIntegerType() || 15258 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 15259 Context.getTypeAlignInChars( 15260 T->getPointeeType()) <= MA->Alignment)))) 15261 MisalignedMembers.erase(MA); 15262 } 15263 } 15264 } 15265 15266 void Sema::RefersToMemberWithReducedAlignment( 15267 Expr *E, 15268 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 15269 Action) { 15270 const auto *ME = dyn_cast<MemberExpr>(E); 15271 if (!ME) 15272 return; 15273 15274 // No need to check expressions with an __unaligned-qualified type. 15275 if (E->getType().getQualifiers().hasUnaligned()) 15276 return; 15277 15278 // For a chain of MemberExpr like "a.b.c.d" this list 15279 // will keep FieldDecl's like [d, c, b]. 15280 SmallVector<FieldDecl *, 4> ReverseMemberChain; 15281 const MemberExpr *TopME = nullptr; 15282 bool AnyIsPacked = false; 15283 do { 15284 QualType BaseType = ME->getBase()->getType(); 15285 if (BaseType->isDependentType()) 15286 return; 15287 if (ME->isArrow()) 15288 BaseType = BaseType->getPointeeType(); 15289 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 15290 if (RD->isInvalidDecl()) 15291 return; 15292 15293 ValueDecl *MD = ME->getMemberDecl(); 15294 auto *FD = dyn_cast<FieldDecl>(MD); 15295 // We do not care about non-data members. 15296 if (!FD || FD->isInvalidDecl()) 15297 return; 15298 15299 AnyIsPacked = 15300 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 15301 ReverseMemberChain.push_back(FD); 15302 15303 TopME = ME; 15304 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 15305 } while (ME); 15306 assert(TopME && "We did not compute a topmost MemberExpr!"); 15307 15308 // Not the scope of this diagnostic. 15309 if (!AnyIsPacked) 15310 return; 15311 15312 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 15313 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 15314 // TODO: The innermost base of the member expression may be too complicated. 15315 // For now, just disregard these cases. This is left for future 15316 // improvement. 15317 if (!DRE && !isa<CXXThisExpr>(TopBase)) 15318 return; 15319 15320 // Alignment expected by the whole expression. 15321 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 15322 15323 // No need to do anything else with this case. 15324 if (ExpectedAlignment.isOne()) 15325 return; 15326 15327 // Synthesize offset of the whole access. 15328 CharUnits Offset; 15329 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15330 I++) { 15331 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15332 } 15333 15334 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15335 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15336 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15337 15338 // The base expression of the innermost MemberExpr may give 15339 // stronger guarantees than the class containing the member. 15340 if (DRE && !TopME->isArrow()) { 15341 const ValueDecl *VD = DRE->getDecl(); 15342 if (!VD->getType()->isReferenceType()) 15343 CompleteObjectAlignment = 15344 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15345 } 15346 15347 // Check if the synthesized offset fulfills the alignment. 15348 if (Offset % ExpectedAlignment != 0 || 15349 // It may fulfill the offset it but the effective alignment may still be 15350 // lower than the expected expression alignment. 15351 CompleteObjectAlignment < ExpectedAlignment) { 15352 // If this happens, we want to determine a sensible culprit of this. 15353 // Intuitively, watching the chain of member expressions from right to 15354 // left, we start with the required alignment (as required by the field 15355 // type) but some packed attribute in that chain has reduced the alignment. 15356 // It may happen that another packed structure increases it again. But if 15357 // we are here such increase has not been enough. So pointing the first 15358 // FieldDecl that either is packed or else its RecordDecl is, 15359 // seems reasonable. 15360 FieldDecl *FD = nullptr; 15361 CharUnits Alignment; 15362 for (FieldDecl *FDI : ReverseMemberChain) { 15363 if (FDI->hasAttr<PackedAttr>() || 15364 FDI->getParent()->hasAttr<PackedAttr>()) { 15365 FD = FDI; 15366 Alignment = std::min( 15367 Context.getTypeAlignInChars(FD->getType()), 15368 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 15369 break; 15370 } 15371 } 15372 assert(FD && "We did not find a packed FieldDecl!"); 15373 Action(E, FD->getParent(), FD, Alignment); 15374 } 15375 } 15376 15377 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 15378 using namespace std::placeholders; 15379 15380 RefersToMemberWithReducedAlignment( 15381 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 15382 _2, _3, _4)); 15383 } 15384 15385 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 15386 ExprResult CallResult) { 15387 if (checkArgCount(*this, TheCall, 1)) 15388 return ExprError(); 15389 15390 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 15391 if (MatrixArg.isInvalid()) 15392 return MatrixArg; 15393 Expr *Matrix = MatrixArg.get(); 15394 15395 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 15396 if (!MType) { 15397 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg); 15398 return ExprError(); 15399 } 15400 15401 // Create returned matrix type by swapping rows and columns of the argument 15402 // matrix type. 15403 QualType ResultType = Context.getConstantMatrixType( 15404 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 15405 15406 // Change the return type to the type of the returned matrix. 15407 TheCall->setType(ResultType); 15408 15409 // Update call argument to use the possibly converted matrix argument. 15410 TheCall->setArg(0, Matrix); 15411 return CallResult; 15412 } 15413 15414 // Get and verify the matrix dimensions. 15415 static llvm::Optional<unsigned> 15416 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) { 15417 SourceLocation ErrorPos; 15418 Optional<llvm::APSInt> Value = 15419 Expr->getIntegerConstantExpr(S.Context, &ErrorPos); 15420 if (!Value) { 15421 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg) 15422 << Name; 15423 return {}; 15424 } 15425 uint64_t Dim = Value->getZExtValue(); 15426 if (!ConstantMatrixType::isDimensionValid(Dim)) { 15427 S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension) 15428 << Name << ConstantMatrixType::getMaxElementsPerDimension(); 15429 return {}; 15430 } 15431 return Dim; 15432 } 15433 15434 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, 15435 ExprResult CallResult) { 15436 if (!getLangOpts().MatrixTypes) { 15437 Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled); 15438 return ExprError(); 15439 } 15440 15441 if (checkArgCount(*this, TheCall, 4)) 15442 return ExprError(); 15443 15444 unsigned PtrArgIdx = 0; 15445 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15446 Expr *RowsExpr = TheCall->getArg(1); 15447 Expr *ColumnsExpr = TheCall->getArg(2); 15448 Expr *StrideExpr = TheCall->getArg(3); 15449 15450 bool ArgError = false; 15451 15452 // Check pointer argument. 15453 { 15454 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15455 if (PtrConv.isInvalid()) 15456 return PtrConv; 15457 PtrExpr = PtrConv.get(); 15458 TheCall->setArg(0, PtrExpr); 15459 if (PtrExpr->isTypeDependent()) { 15460 TheCall->setType(Context.DependentTy); 15461 return TheCall; 15462 } 15463 } 15464 15465 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15466 QualType ElementTy; 15467 if (!PtrTy) { 15468 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15469 << PtrArgIdx + 1; 15470 ArgError = true; 15471 } else { 15472 ElementTy = PtrTy->getPointeeType().getUnqualifiedType(); 15473 15474 if (!ConstantMatrixType::isValidElementType(ElementTy)) { 15475 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15476 << PtrArgIdx + 1; 15477 ArgError = true; 15478 } 15479 } 15480 15481 // Apply default Lvalue conversions and convert the expression to size_t. 15482 auto ApplyArgumentConversions = [this](Expr *E) { 15483 ExprResult Conv = DefaultLvalueConversion(E); 15484 if (Conv.isInvalid()) 15485 return Conv; 15486 15487 return tryConvertExprToType(Conv.get(), Context.getSizeType()); 15488 }; 15489 15490 // Apply conversion to row and column expressions. 15491 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr); 15492 if (!RowsConv.isInvalid()) { 15493 RowsExpr = RowsConv.get(); 15494 TheCall->setArg(1, RowsExpr); 15495 } else 15496 RowsExpr = nullptr; 15497 15498 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr); 15499 if (!ColumnsConv.isInvalid()) { 15500 ColumnsExpr = ColumnsConv.get(); 15501 TheCall->setArg(2, ColumnsExpr); 15502 } else 15503 ColumnsExpr = nullptr; 15504 15505 // If any any part of the result matrix type is still pending, just use 15506 // Context.DependentTy, until all parts are resolved. 15507 if ((RowsExpr && RowsExpr->isTypeDependent()) || 15508 (ColumnsExpr && ColumnsExpr->isTypeDependent())) { 15509 TheCall->setType(Context.DependentTy); 15510 return CallResult; 15511 } 15512 15513 // Check row and column dimenions. 15514 llvm::Optional<unsigned> MaybeRows; 15515 if (RowsExpr) 15516 MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this); 15517 15518 llvm::Optional<unsigned> MaybeColumns; 15519 if (ColumnsExpr) 15520 MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this); 15521 15522 // Check stride argument. 15523 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr); 15524 if (StrideConv.isInvalid()) 15525 return ExprError(); 15526 StrideExpr = StrideConv.get(); 15527 TheCall->setArg(3, StrideExpr); 15528 15529 if (MaybeRows) { 15530 if (Optional<llvm::APSInt> Value = 15531 StrideExpr->getIntegerConstantExpr(Context)) { 15532 uint64_t Stride = Value->getZExtValue(); 15533 if (Stride < *MaybeRows) { 15534 Diag(StrideExpr->getBeginLoc(), 15535 diag::err_builtin_matrix_stride_too_small); 15536 ArgError = true; 15537 } 15538 } 15539 } 15540 15541 if (ArgError || !MaybeRows || !MaybeColumns) 15542 return ExprError(); 15543 15544 TheCall->setType( 15545 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns)); 15546 return CallResult; 15547 } 15548 15549 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, 15550 ExprResult CallResult) { 15551 if (checkArgCount(*this, TheCall, 3)) 15552 return ExprError(); 15553 15554 unsigned PtrArgIdx = 1; 15555 Expr *MatrixExpr = TheCall->getArg(0); 15556 Expr *PtrExpr = TheCall->getArg(PtrArgIdx); 15557 Expr *StrideExpr = TheCall->getArg(2); 15558 15559 bool ArgError = false; 15560 15561 { 15562 ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr); 15563 if (MatrixConv.isInvalid()) 15564 return MatrixConv; 15565 MatrixExpr = MatrixConv.get(); 15566 TheCall->setArg(0, MatrixExpr); 15567 } 15568 if (MatrixExpr->isTypeDependent()) { 15569 TheCall->setType(Context.DependentTy); 15570 return TheCall; 15571 } 15572 15573 auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>(); 15574 if (!MatrixTy) { 15575 Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 15576 ArgError = true; 15577 } 15578 15579 { 15580 ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr); 15581 if (PtrConv.isInvalid()) 15582 return PtrConv; 15583 PtrExpr = PtrConv.get(); 15584 TheCall->setArg(1, PtrExpr); 15585 if (PtrExpr->isTypeDependent()) { 15586 TheCall->setType(Context.DependentTy); 15587 return TheCall; 15588 } 15589 } 15590 15591 // Check pointer argument. 15592 auto *PtrTy = PtrExpr->getType()->getAs<PointerType>(); 15593 if (!PtrTy) { 15594 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg) 15595 << PtrArgIdx + 1; 15596 ArgError = true; 15597 } else { 15598 QualType ElementTy = PtrTy->getPointeeType(); 15599 if (ElementTy.isConstQualified()) { 15600 Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const); 15601 ArgError = true; 15602 } 15603 ElementTy = ElementTy.getUnqualifiedType().getCanonicalType(); 15604 if (MatrixTy && 15605 !Context.hasSameType(ElementTy, MatrixTy->getElementType())) { 15606 Diag(PtrExpr->getBeginLoc(), 15607 diag::err_builtin_matrix_pointer_arg_mismatch) 15608 << ElementTy << MatrixTy->getElementType(); 15609 ArgError = true; 15610 } 15611 } 15612 15613 // Apply default Lvalue conversions and convert the stride expression to 15614 // size_t. 15615 { 15616 ExprResult StrideConv = DefaultLvalueConversion(StrideExpr); 15617 if (StrideConv.isInvalid()) 15618 return StrideConv; 15619 15620 StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType()); 15621 if (StrideConv.isInvalid()) 15622 return StrideConv; 15623 StrideExpr = StrideConv.get(); 15624 TheCall->setArg(2, StrideExpr); 15625 } 15626 15627 // Check stride argument. 15628 if (MatrixTy) { 15629 if (Optional<llvm::APSInt> Value = 15630 StrideExpr->getIntegerConstantExpr(Context)) { 15631 uint64_t Stride = Value->getZExtValue(); 15632 if (Stride < MatrixTy->getNumRows()) { 15633 Diag(StrideExpr->getBeginLoc(), 15634 diag::err_builtin_matrix_stride_too_small); 15635 ArgError = true; 15636 } 15637 } 15638 } 15639 15640 if (ArgError) 15641 return ExprError(); 15642 15643 return CallResult; 15644 } 15645