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 <cassert> 92 #include <cstddef> 93 #include <cstdint> 94 #include <functional> 95 #include <limits> 96 #include <string> 97 #include <tuple> 98 #include <utility> 99 100 using namespace clang; 101 using namespace sema; 102 103 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL, 104 unsigned ByteNo) const { 105 return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts, 106 Context.getTargetInfo()); 107 } 108 109 /// Checks that a call expression's argument count is the desired number. 110 /// This is useful when doing custom type-checking. Returns true on error. 111 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) { 112 unsigned argCount = call->getNumArgs(); 113 if (argCount == desiredArgCount) return false; 114 115 if (argCount < desiredArgCount) 116 return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args) 117 << 0 /*function call*/ << desiredArgCount << argCount 118 << call->getSourceRange(); 119 120 // Highlight all the excess arguments. 121 SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(), 122 call->getArg(argCount - 1)->getEndLoc()); 123 124 return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args) 125 << 0 /*function call*/ << desiredArgCount << argCount 126 << call->getArg(1)->getSourceRange(); 127 } 128 129 /// Check that the first argument to __builtin_annotation is an integer 130 /// and the second argument is a non-wide string literal. 131 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) { 132 if (checkArgCount(S, TheCall, 2)) 133 return true; 134 135 // First argument should be an integer. 136 Expr *ValArg = TheCall->getArg(0); 137 QualType Ty = ValArg->getType(); 138 if (!Ty->isIntegerType()) { 139 S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg) 140 << ValArg->getSourceRange(); 141 return true; 142 } 143 144 // Second argument should be a constant string. 145 Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts(); 146 StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg); 147 if (!Literal || !Literal->isAscii()) { 148 S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg) 149 << StrArg->getSourceRange(); 150 return true; 151 } 152 153 TheCall->setType(Ty); 154 return false; 155 } 156 157 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) { 158 // We need at least one argument. 159 if (TheCall->getNumArgs() < 1) { 160 S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 161 << 0 << 1 << TheCall->getNumArgs() 162 << TheCall->getCallee()->getSourceRange(); 163 return true; 164 } 165 166 // All arguments should be wide string literals. 167 for (Expr *Arg : TheCall->arguments()) { 168 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts()); 169 if (!Literal || !Literal->isWide()) { 170 S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str) 171 << Arg->getSourceRange(); 172 return true; 173 } 174 } 175 176 return false; 177 } 178 179 /// Check that the argument to __builtin_addressof is a glvalue, and set the 180 /// result type to the corresponding pointer type. 181 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) { 182 if (checkArgCount(S, TheCall, 1)) 183 return true; 184 185 ExprResult Arg(TheCall->getArg(0)); 186 QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc()); 187 if (ResultType.isNull()) 188 return true; 189 190 TheCall->setArg(0, Arg.get()); 191 TheCall->setType(ResultType); 192 return false; 193 } 194 195 /// Check the number of arguments and set the result type to 196 /// the argument type. 197 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) { 198 if (checkArgCount(S, TheCall, 1)) 199 return true; 200 201 TheCall->setType(TheCall->getArg(0)->getType()); 202 return false; 203 } 204 205 /// Check that the value argument for __builtin_is_aligned(value, alignment) and 206 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer 207 /// type (but not a function pointer) and that the alignment is a power-of-two. 208 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) { 209 if (checkArgCount(S, TheCall, 2)) 210 return true; 211 212 clang::Expr *Source = TheCall->getArg(0); 213 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned; 214 215 auto IsValidIntegerType = [](QualType Ty) { 216 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType(); 217 }; 218 QualType SrcTy = Source->getType(); 219 // We should also be able to use it with arrays (but not functions!). 220 if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) { 221 SrcTy = S.Context.getDecayedType(SrcTy); 222 } 223 if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) || 224 SrcTy->isFunctionPointerType()) { 225 // FIXME: this is not quite the right error message since we don't allow 226 // floating point types, or member pointers. 227 S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand) 228 << SrcTy; 229 return true; 230 } 231 232 clang::Expr *AlignOp = TheCall->getArg(1); 233 if (!IsValidIntegerType(AlignOp->getType())) { 234 S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int) 235 << AlignOp->getType(); 236 return true; 237 } 238 Expr::EvalResult AlignResult; 239 unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1; 240 // We can't check validity of alignment if it is type dependent. 241 if (!AlignOp->isInstantiationDependent() && 242 AlignOp->EvaluateAsInt(AlignResult, S.Context, 243 Expr::SE_AllowSideEffects)) { 244 llvm::APSInt AlignValue = AlignResult.Val.getInt(); 245 llvm::APSInt MaxValue( 246 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits)); 247 if (AlignValue < 1) { 248 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1; 249 return true; 250 } 251 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) { 252 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big) 253 << MaxValue.toString(10); 254 return true; 255 } 256 if (!AlignValue.isPowerOf2()) { 257 S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two); 258 return true; 259 } 260 if (AlignValue == 1) { 261 S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless) 262 << IsBooleanAlignBuiltin; 263 } 264 } 265 266 ExprResult SrcArg = S.PerformCopyInitialization( 267 InitializedEntity::InitializeParameter(S.Context, SrcTy, false), 268 SourceLocation(), Source); 269 if (SrcArg.isInvalid()) 270 return true; 271 TheCall->setArg(0, SrcArg.get()); 272 ExprResult AlignArg = 273 S.PerformCopyInitialization(InitializedEntity::InitializeParameter( 274 S.Context, AlignOp->getType(), false), 275 SourceLocation(), AlignOp); 276 if (AlignArg.isInvalid()) 277 return true; 278 TheCall->setArg(1, AlignArg.get()); 279 // For align_up/align_down, the return type is the same as the (potentially 280 // decayed) argument type including qualifiers. For is_aligned(), the result 281 // is always bool. 282 TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy); 283 return false; 284 } 285 286 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall, 287 unsigned BuiltinID) { 288 if (checkArgCount(S, TheCall, 3)) 289 return true; 290 291 // First two arguments should be integers. 292 for (unsigned I = 0; I < 2; ++I) { 293 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I)); 294 if (Arg.isInvalid()) return true; 295 TheCall->setArg(I, Arg.get()); 296 297 QualType Ty = Arg.get()->getType(); 298 if (!Ty->isIntegerType()) { 299 S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int) 300 << Ty << Arg.get()->getSourceRange(); 301 return true; 302 } 303 } 304 305 // Third argument should be a pointer to a non-const integer. 306 // IRGen correctly handles volatile, restrict, and address spaces, and 307 // the other qualifiers aren't possible. 308 { 309 ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2)); 310 if (Arg.isInvalid()) return true; 311 TheCall->setArg(2, Arg.get()); 312 313 QualType Ty = Arg.get()->getType(); 314 const auto *PtrTy = Ty->getAs<PointerType>(); 315 if (!PtrTy || 316 !PtrTy->getPointeeType()->isIntegerType() || 317 PtrTy->getPointeeType().isConstQualified()) { 318 S.Diag(Arg.get()->getBeginLoc(), 319 diag::err_overflow_builtin_must_be_ptr_int) 320 << Ty << Arg.get()->getSourceRange(); 321 return true; 322 } 323 } 324 325 // Disallow signed ExtIntType args larger than 128 bits to mul function until 326 // we improve backend support. 327 if (BuiltinID == Builtin::BI__builtin_mul_overflow) { 328 for (unsigned I = 0; I < 3; ++I) { 329 const auto Arg = TheCall->getArg(I); 330 // Third argument will be a pointer. 331 auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType(); 332 if (Ty->isExtIntType() && Ty->isSignedIntegerType() && 333 S.getASTContext().getIntWidth(Ty) > 128) 334 return S.Diag(Arg->getBeginLoc(), 335 diag::err_overflow_builtin_ext_int_max_size) 336 << 128; 337 } 338 } 339 340 return false; 341 } 342 343 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) { 344 if (checkArgCount(S, BuiltinCall, 2)) 345 return true; 346 347 SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc(); 348 Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts(); 349 Expr *Call = BuiltinCall->getArg(0); 350 Expr *Chain = BuiltinCall->getArg(1); 351 352 if (Call->getStmtClass() != Stmt::CallExprClass) { 353 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call) 354 << Call->getSourceRange(); 355 return true; 356 } 357 358 auto CE = cast<CallExpr>(Call); 359 if (CE->getCallee()->getType()->isBlockPointerType()) { 360 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call) 361 << Call->getSourceRange(); 362 return true; 363 } 364 365 const Decl *TargetDecl = CE->getCalleeDecl(); 366 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 367 if (FD->getBuiltinID()) { 368 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call) 369 << Call->getSourceRange(); 370 return true; 371 } 372 373 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) { 374 S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call) 375 << Call->getSourceRange(); 376 return true; 377 } 378 379 ExprResult ChainResult = S.UsualUnaryConversions(Chain); 380 if (ChainResult.isInvalid()) 381 return true; 382 if (!ChainResult.get()->getType()->isPointerType()) { 383 S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer) 384 << Chain->getSourceRange(); 385 return true; 386 } 387 388 QualType ReturnTy = CE->getCallReturnType(S.Context); 389 QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() }; 390 QualType BuiltinTy = S.Context.getFunctionType( 391 ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo()); 392 QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy); 393 394 Builtin = 395 S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get(); 396 397 BuiltinCall->setType(CE->getType()); 398 BuiltinCall->setValueKind(CE->getValueKind()); 399 BuiltinCall->setObjectKind(CE->getObjectKind()); 400 BuiltinCall->setCallee(Builtin); 401 BuiltinCall->setArg(1, ChainResult.get()); 402 403 return false; 404 } 405 406 namespace { 407 408 class EstimateSizeFormatHandler 409 : public analyze_format_string::FormatStringHandler { 410 size_t Size; 411 412 public: 413 EstimateSizeFormatHandler(StringRef Format) 414 : Size(std::min(Format.find(0), Format.size()) + 415 1 /* null byte always written by sprintf */) {} 416 417 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 418 const char *, unsigned SpecifierLen) override { 419 420 const size_t FieldWidth = computeFieldWidth(FS); 421 const size_t Precision = computePrecision(FS); 422 423 // The actual format. 424 switch (FS.getConversionSpecifier().getKind()) { 425 // Just a char. 426 case analyze_format_string::ConversionSpecifier::cArg: 427 case analyze_format_string::ConversionSpecifier::CArg: 428 Size += std::max(FieldWidth, (size_t)1); 429 break; 430 // Just an integer. 431 case analyze_format_string::ConversionSpecifier::dArg: 432 case analyze_format_string::ConversionSpecifier::DArg: 433 case analyze_format_string::ConversionSpecifier::iArg: 434 case analyze_format_string::ConversionSpecifier::oArg: 435 case analyze_format_string::ConversionSpecifier::OArg: 436 case analyze_format_string::ConversionSpecifier::uArg: 437 case analyze_format_string::ConversionSpecifier::UArg: 438 case analyze_format_string::ConversionSpecifier::xArg: 439 case analyze_format_string::ConversionSpecifier::XArg: 440 Size += std::max(FieldWidth, Precision); 441 break; 442 443 // %g style conversion switches between %f or %e style dynamically. 444 // %f always takes less space, so default to it. 445 case analyze_format_string::ConversionSpecifier::gArg: 446 case analyze_format_string::ConversionSpecifier::GArg: 447 448 // Floating point number in the form '[+]ddd.ddd'. 449 case analyze_format_string::ConversionSpecifier::fArg: 450 case analyze_format_string::ConversionSpecifier::FArg: 451 Size += std::max(FieldWidth, 1 /* integer part */ + 452 (Precision ? 1 + Precision 453 : 0) /* period + decimal */); 454 break; 455 456 // Floating point number in the form '[-]d.ddde[+-]dd'. 457 case analyze_format_string::ConversionSpecifier::eArg: 458 case analyze_format_string::ConversionSpecifier::EArg: 459 Size += 460 std::max(FieldWidth, 461 1 /* integer part */ + 462 (Precision ? 1 + Precision : 0) /* period + decimal */ + 463 1 /* e or E letter */ + 2 /* exponent */); 464 break; 465 466 // Floating point number in the form '[-]0xh.hhhhp±dd'. 467 case analyze_format_string::ConversionSpecifier::aArg: 468 case analyze_format_string::ConversionSpecifier::AArg: 469 Size += 470 std::max(FieldWidth, 471 2 /* 0x */ + 1 /* integer part */ + 472 (Precision ? 1 + Precision : 0) /* period + decimal */ + 473 1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */); 474 break; 475 476 // Just a string. 477 case analyze_format_string::ConversionSpecifier::sArg: 478 case analyze_format_string::ConversionSpecifier::SArg: 479 Size += FieldWidth; 480 break; 481 482 // Just a pointer in the form '0xddd'. 483 case analyze_format_string::ConversionSpecifier::pArg: 484 Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision); 485 break; 486 487 // A plain percent. 488 case analyze_format_string::ConversionSpecifier::PercentArg: 489 Size += 1; 490 break; 491 492 default: 493 break; 494 } 495 496 Size += FS.hasPlusPrefix() || FS.hasSpacePrefix(); 497 498 if (FS.hasAlternativeForm()) { 499 switch (FS.getConversionSpecifier().getKind()) { 500 default: 501 break; 502 // Force a leading '0'. 503 case analyze_format_string::ConversionSpecifier::oArg: 504 Size += 1; 505 break; 506 // Force a leading '0x'. 507 case analyze_format_string::ConversionSpecifier::xArg: 508 case analyze_format_string::ConversionSpecifier::XArg: 509 Size += 2; 510 break; 511 // Force a period '.' before decimal, even if precision is 0. 512 case analyze_format_string::ConversionSpecifier::aArg: 513 case analyze_format_string::ConversionSpecifier::AArg: 514 case analyze_format_string::ConversionSpecifier::eArg: 515 case analyze_format_string::ConversionSpecifier::EArg: 516 case analyze_format_string::ConversionSpecifier::fArg: 517 case analyze_format_string::ConversionSpecifier::FArg: 518 case analyze_format_string::ConversionSpecifier::gArg: 519 case analyze_format_string::ConversionSpecifier::GArg: 520 Size += (Precision ? 0 : 1); 521 break; 522 } 523 } 524 assert(SpecifierLen <= Size && "no underflow"); 525 Size -= SpecifierLen; 526 return true; 527 } 528 529 size_t getSizeLowerBound() const { return Size; } 530 531 private: 532 static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) { 533 const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth(); 534 size_t FieldWidth = 0; 535 if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant) 536 FieldWidth = FW.getConstantAmount(); 537 return FieldWidth; 538 } 539 540 static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) { 541 const analyze_format_string::OptionalAmount &FW = FS.getPrecision(); 542 size_t Precision = 0; 543 544 // See man 3 printf for default precision value based on the specifier. 545 switch (FW.getHowSpecified()) { 546 case analyze_format_string::OptionalAmount::NotSpecified: 547 switch (FS.getConversionSpecifier().getKind()) { 548 default: 549 break; 550 case analyze_format_string::ConversionSpecifier::dArg: // %d 551 case analyze_format_string::ConversionSpecifier::DArg: // %D 552 case analyze_format_string::ConversionSpecifier::iArg: // %i 553 Precision = 1; 554 break; 555 case analyze_format_string::ConversionSpecifier::oArg: // %d 556 case analyze_format_string::ConversionSpecifier::OArg: // %D 557 case analyze_format_string::ConversionSpecifier::uArg: // %d 558 case analyze_format_string::ConversionSpecifier::UArg: // %D 559 case analyze_format_string::ConversionSpecifier::xArg: // %d 560 case analyze_format_string::ConversionSpecifier::XArg: // %D 561 Precision = 1; 562 break; 563 case analyze_format_string::ConversionSpecifier::fArg: // %f 564 case analyze_format_string::ConversionSpecifier::FArg: // %F 565 case analyze_format_string::ConversionSpecifier::eArg: // %e 566 case analyze_format_string::ConversionSpecifier::EArg: // %E 567 case analyze_format_string::ConversionSpecifier::gArg: // %g 568 case analyze_format_string::ConversionSpecifier::GArg: // %G 569 Precision = 6; 570 break; 571 case analyze_format_string::ConversionSpecifier::pArg: // %d 572 Precision = 1; 573 break; 574 } 575 break; 576 case analyze_format_string::OptionalAmount::Constant: 577 Precision = FW.getConstantAmount(); 578 break; 579 default: 580 break; 581 } 582 return Precision; 583 } 584 }; 585 586 } // namespace 587 588 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a 589 /// __builtin_*_chk function, then use the object size argument specified in the 590 /// source. Otherwise, infer the object size using __builtin_object_size. 591 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, 592 CallExpr *TheCall) { 593 // FIXME: There are some more useful checks we could be doing here: 594 // - Evaluate strlen of strcpy arguments, use as object size. 595 596 if (TheCall->isValueDependent() || TheCall->isTypeDependent() || 597 isConstantEvaluated()) 598 return; 599 600 unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true); 601 if (!BuiltinID) 602 return; 603 604 const TargetInfo &TI = getASTContext().getTargetInfo(); 605 unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType()); 606 607 unsigned DiagID = 0; 608 bool IsChkVariant = false; 609 Optional<llvm::APSInt> UsedSize; 610 unsigned SizeIndex, ObjectIndex; 611 switch (BuiltinID) { 612 default: 613 return; 614 case Builtin::BIsprintf: 615 case Builtin::BI__builtin___sprintf_chk: { 616 size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3; 617 auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts(); 618 619 if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) { 620 621 if (!Format->isAscii() && !Format->isUTF8()) 622 return; 623 624 StringRef FormatStrRef = Format->getString(); 625 EstimateSizeFormatHandler H(FormatStrRef); 626 const char *FormatBytes = FormatStrRef.data(); 627 const ConstantArrayType *T = 628 Context.getAsConstantArrayType(Format->getType()); 629 assert(T && "String literal not of constant array type!"); 630 size_t TypeSize = T->getSize().getZExtValue(); 631 632 // In case there's a null byte somewhere. 633 size_t StrLen = 634 std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0)); 635 if (!analyze_format_string::ParsePrintfString( 636 H, FormatBytes, FormatBytes + StrLen, getLangOpts(), 637 Context.getTargetInfo(), false)) { 638 DiagID = diag::warn_fortify_source_format_overflow; 639 UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound()) 640 .extOrTrunc(SizeTypeWidth); 641 if (BuiltinID == Builtin::BI__builtin___sprintf_chk) { 642 IsChkVariant = true; 643 ObjectIndex = 2; 644 } else { 645 IsChkVariant = false; 646 ObjectIndex = 0; 647 } 648 break; 649 } 650 } 651 return; 652 } 653 case Builtin::BI__builtin___memcpy_chk: 654 case Builtin::BI__builtin___memmove_chk: 655 case Builtin::BI__builtin___memset_chk: 656 case Builtin::BI__builtin___strlcat_chk: 657 case Builtin::BI__builtin___strlcpy_chk: 658 case Builtin::BI__builtin___strncat_chk: 659 case Builtin::BI__builtin___strncpy_chk: 660 case Builtin::BI__builtin___stpncpy_chk: 661 case Builtin::BI__builtin___memccpy_chk: 662 case Builtin::BI__builtin___mempcpy_chk: { 663 DiagID = diag::warn_builtin_chk_overflow; 664 IsChkVariant = true; 665 SizeIndex = TheCall->getNumArgs() - 2; 666 ObjectIndex = TheCall->getNumArgs() - 1; 667 break; 668 } 669 670 case Builtin::BI__builtin___snprintf_chk: 671 case Builtin::BI__builtin___vsnprintf_chk: { 672 DiagID = diag::warn_builtin_chk_overflow; 673 IsChkVariant = true; 674 SizeIndex = 1; 675 ObjectIndex = 3; 676 break; 677 } 678 679 case Builtin::BIstrncat: 680 case Builtin::BI__builtin_strncat: 681 case Builtin::BIstrncpy: 682 case Builtin::BI__builtin_strncpy: 683 case Builtin::BIstpncpy: 684 case Builtin::BI__builtin_stpncpy: { 685 // Whether these functions overflow depends on the runtime strlen of the 686 // string, not just the buffer size, so emitting the "always overflow" 687 // diagnostic isn't quite right. We should still diagnose passing a buffer 688 // size larger than the destination buffer though; this is a runtime abort 689 // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise. 690 DiagID = diag::warn_fortify_source_size_mismatch; 691 SizeIndex = TheCall->getNumArgs() - 1; 692 ObjectIndex = 0; 693 break; 694 } 695 696 case Builtin::BImemcpy: 697 case Builtin::BI__builtin_memcpy: 698 case Builtin::BImemmove: 699 case Builtin::BI__builtin_memmove: 700 case Builtin::BImemset: 701 case Builtin::BI__builtin_memset: 702 case Builtin::BImempcpy: 703 case Builtin::BI__builtin_mempcpy: { 704 DiagID = diag::warn_fortify_source_overflow; 705 SizeIndex = TheCall->getNumArgs() - 1; 706 ObjectIndex = 0; 707 break; 708 } 709 case Builtin::BIsnprintf: 710 case Builtin::BI__builtin_snprintf: 711 case Builtin::BIvsnprintf: 712 case Builtin::BI__builtin_vsnprintf: { 713 DiagID = diag::warn_fortify_source_size_mismatch; 714 SizeIndex = 1; 715 ObjectIndex = 0; 716 break; 717 } 718 } 719 720 llvm::APSInt ObjectSize; 721 // For __builtin___*_chk, the object size is explicitly provided by the caller 722 // (usually using __builtin_object_size). Use that value to check this call. 723 if (IsChkVariant) { 724 Expr::EvalResult Result; 725 Expr *SizeArg = TheCall->getArg(ObjectIndex); 726 if (!SizeArg->EvaluateAsInt(Result, getASTContext())) 727 return; 728 ObjectSize = Result.Val.getInt(); 729 730 // Otherwise, try to evaluate an imaginary call to __builtin_object_size. 731 } else { 732 // If the parameter has a pass_object_size attribute, then we should use its 733 // (potentially) more strict checking mode. Otherwise, conservatively assume 734 // type 0. 735 int BOSType = 0; 736 if (const auto *POS = 737 FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>()) 738 BOSType = POS->getType(); 739 740 Expr *ObjArg = TheCall->getArg(ObjectIndex); 741 uint64_t Result; 742 if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType)) 743 return; 744 // Get the object size in the target's size_t width. 745 ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth); 746 } 747 748 // Evaluate the number of bytes of the object that this call will use. 749 if (!UsedSize) { 750 Expr::EvalResult Result; 751 Expr *UsedSizeArg = TheCall->getArg(SizeIndex); 752 if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext())) 753 return; 754 UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth); 755 } 756 757 if (UsedSize.getValue().ule(ObjectSize)) 758 return; 759 760 StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID); 761 // Skim off the details of whichever builtin was called to produce a better 762 // diagnostic, as it's unlikley that the user wrote the __builtin explicitly. 763 if (IsChkVariant) { 764 FunctionName = FunctionName.drop_front(std::strlen("__builtin___")); 765 FunctionName = FunctionName.drop_back(std::strlen("_chk")); 766 } else if (FunctionName.startswith("__builtin_")) { 767 FunctionName = FunctionName.drop_front(std::strlen("__builtin_")); 768 } 769 770 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 771 PDiag(DiagID) 772 << FunctionName << ObjectSize.toString(/*Radix=*/10) 773 << UsedSize.getValue().toString(/*Radix=*/10)); 774 } 775 776 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, 777 Scope::ScopeFlags NeededScopeFlags, 778 unsigned DiagID) { 779 // Scopes aren't available during instantiation. Fortunately, builtin 780 // functions cannot be template args so they cannot be formed through template 781 // instantiation. Therefore checking once during the parse is sufficient. 782 if (SemaRef.inTemplateInstantiation()) 783 return false; 784 785 Scope *S = SemaRef.getCurScope(); 786 while (S && !S->isSEHExceptScope()) 787 S = S->getParent(); 788 if (!S || !(S->getFlags() & NeededScopeFlags)) { 789 auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 790 SemaRef.Diag(TheCall->getExprLoc(), DiagID) 791 << DRE->getDecl()->getIdentifier(); 792 return true; 793 } 794 795 return false; 796 } 797 798 static inline bool isBlockPointer(Expr *Arg) { 799 return Arg->getType()->isBlockPointerType(); 800 } 801 802 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local 803 /// void*, which is a requirement of device side enqueue. 804 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) { 805 const BlockPointerType *BPT = 806 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 807 ArrayRef<QualType> Params = 808 BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes(); 809 unsigned ArgCounter = 0; 810 bool IllegalParams = false; 811 // Iterate through the block parameters until either one is found that is not 812 // a local void*, or the block is valid. 813 for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end(); 814 I != E; ++I, ++ArgCounter) { 815 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() || 816 (*I)->getPointeeType().getQualifiers().getAddressSpace() != 817 LangAS::opencl_local) { 818 // Get the location of the error. If a block literal has been passed 819 // (BlockExpr) then we can point straight to the offending argument, 820 // else we just point to the variable reference. 821 SourceLocation ErrorLoc; 822 if (isa<BlockExpr>(BlockArg)) { 823 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl(); 824 ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc(); 825 } else if (isa<DeclRefExpr>(BlockArg)) { 826 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc(); 827 } 828 S.Diag(ErrorLoc, 829 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args); 830 IllegalParams = true; 831 } 832 } 833 834 return IllegalParams; 835 } 836 837 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) { 838 if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) { 839 S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension) 840 << 1 << Call->getDirectCallee() << "cl_khr_subgroups"; 841 return true; 842 } 843 return false; 844 } 845 846 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) { 847 if (checkArgCount(S, TheCall, 2)) 848 return true; 849 850 if (checkOpenCLSubgroupExt(S, TheCall)) 851 return true; 852 853 // First argument is an ndrange_t type. 854 Expr *NDRangeArg = TheCall->getArg(0); 855 if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 856 S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 857 << TheCall->getDirectCallee() << "'ndrange_t'"; 858 return true; 859 } 860 861 Expr *BlockArg = TheCall->getArg(1); 862 if (!isBlockPointer(BlockArg)) { 863 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 864 << TheCall->getDirectCallee() << "block"; 865 return true; 866 } 867 return checkOpenCLBlockArgs(S, BlockArg); 868 } 869 870 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the 871 /// get_kernel_work_group_size 872 /// and get_kernel_preferred_work_group_size_multiple builtin functions. 873 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) { 874 if (checkArgCount(S, TheCall, 1)) 875 return true; 876 877 Expr *BlockArg = TheCall->getArg(0); 878 if (!isBlockPointer(BlockArg)) { 879 S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type) 880 << TheCall->getDirectCallee() << "block"; 881 return true; 882 } 883 return checkOpenCLBlockArgs(S, BlockArg); 884 } 885 886 /// Diagnose integer type and any valid implicit conversion to it. 887 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, 888 const QualType &IntType); 889 890 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, 891 unsigned Start, unsigned End) { 892 bool IllegalParams = false; 893 for (unsigned I = Start; I <= End; ++I) 894 IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I), 895 S.Context.getSizeType()); 896 return IllegalParams; 897 } 898 899 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 900 /// 'local void*' parameter of passed block. 901 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, 902 Expr *BlockArg, 903 unsigned NumNonVarArgs) { 904 const BlockPointerType *BPT = 905 cast<BlockPointerType>(BlockArg->getType().getCanonicalType()); 906 unsigned NumBlockParams = 907 BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams(); 908 unsigned TotalNumArgs = TheCall->getNumArgs(); 909 910 // For each argument passed to the block, a corresponding uint needs to 911 // be passed to describe the size of the local memory. 912 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) { 913 S.Diag(TheCall->getBeginLoc(), 914 diag::err_opencl_enqueue_kernel_local_size_args); 915 return true; 916 } 917 918 // Check that the sizes of the local memory are specified by integers. 919 return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs, 920 TotalNumArgs - 1); 921 } 922 923 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different 924 /// overload formats specified in Table 6.13.17.1. 925 /// int enqueue_kernel(queue_t queue, 926 /// kernel_enqueue_flags_t flags, 927 /// const ndrange_t ndrange, 928 /// void (^block)(void)) 929 /// int enqueue_kernel(queue_t queue, 930 /// kernel_enqueue_flags_t flags, 931 /// const ndrange_t ndrange, 932 /// uint num_events_in_wait_list, 933 /// clk_event_t *event_wait_list, 934 /// clk_event_t *event_ret, 935 /// void (^block)(void)) 936 /// int enqueue_kernel(queue_t queue, 937 /// kernel_enqueue_flags_t flags, 938 /// const ndrange_t ndrange, 939 /// void (^block)(local void*, ...), 940 /// uint size0, ...) 941 /// int enqueue_kernel(queue_t queue, 942 /// kernel_enqueue_flags_t flags, 943 /// const ndrange_t ndrange, 944 /// uint num_events_in_wait_list, 945 /// clk_event_t *event_wait_list, 946 /// clk_event_t *event_ret, 947 /// void (^block)(local void*, ...), 948 /// uint size0, ...) 949 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) { 950 unsigned NumArgs = TheCall->getNumArgs(); 951 952 if (NumArgs < 4) { 953 S.Diag(TheCall->getBeginLoc(), 954 diag::err_typecheck_call_too_few_args_at_least) 955 << 0 << 4 << NumArgs; 956 return true; 957 } 958 959 Expr *Arg0 = TheCall->getArg(0); 960 Expr *Arg1 = TheCall->getArg(1); 961 Expr *Arg2 = TheCall->getArg(2); 962 Expr *Arg3 = TheCall->getArg(3); 963 964 // First argument always needs to be a queue_t type. 965 if (!Arg0->getType()->isQueueT()) { 966 S.Diag(TheCall->getArg(0)->getBeginLoc(), 967 diag::err_opencl_builtin_expected_type) 968 << TheCall->getDirectCallee() << S.Context.OCLQueueTy; 969 return true; 970 } 971 972 // Second argument always needs to be a kernel_enqueue_flags_t enum value. 973 if (!Arg1->getType()->isIntegerType()) { 974 S.Diag(TheCall->getArg(1)->getBeginLoc(), 975 diag::err_opencl_builtin_expected_type) 976 << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)"; 977 return true; 978 } 979 980 // Third argument is always an ndrange_t type. 981 if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") { 982 S.Diag(TheCall->getArg(2)->getBeginLoc(), 983 diag::err_opencl_builtin_expected_type) 984 << TheCall->getDirectCallee() << "'ndrange_t'"; 985 return true; 986 } 987 988 // With four arguments, there is only one form that the function could be 989 // called in: no events and no variable arguments. 990 if (NumArgs == 4) { 991 // check that the last argument is the right block type. 992 if (!isBlockPointer(Arg3)) { 993 S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type) 994 << TheCall->getDirectCallee() << "block"; 995 return true; 996 } 997 // we have a block type, check the prototype 998 const BlockPointerType *BPT = 999 cast<BlockPointerType>(Arg3->getType().getCanonicalType()); 1000 if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) { 1001 S.Diag(Arg3->getBeginLoc(), 1002 diag::err_opencl_enqueue_kernel_blocks_no_args); 1003 return true; 1004 } 1005 return false; 1006 } 1007 // we can have block + varargs. 1008 if (isBlockPointer(Arg3)) 1009 return (checkOpenCLBlockArgs(S, Arg3) || 1010 checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4)); 1011 // last two cases with either exactly 7 args or 7 args and varargs. 1012 if (NumArgs >= 7) { 1013 // check common block argument. 1014 Expr *Arg6 = TheCall->getArg(6); 1015 if (!isBlockPointer(Arg6)) { 1016 S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type) 1017 << TheCall->getDirectCallee() << "block"; 1018 return true; 1019 } 1020 if (checkOpenCLBlockArgs(S, Arg6)) 1021 return true; 1022 1023 // Forth argument has to be any integer type. 1024 if (!Arg3->getType()->isIntegerType()) { 1025 S.Diag(TheCall->getArg(3)->getBeginLoc(), 1026 diag::err_opencl_builtin_expected_type) 1027 << TheCall->getDirectCallee() << "integer"; 1028 return true; 1029 } 1030 // check remaining common arguments. 1031 Expr *Arg4 = TheCall->getArg(4); 1032 Expr *Arg5 = TheCall->getArg(5); 1033 1034 // Fifth argument is always passed as a pointer to clk_event_t. 1035 if (!Arg4->isNullPointerConstant(S.Context, 1036 Expr::NPC_ValueDependentIsNotNull) && 1037 !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) { 1038 S.Diag(TheCall->getArg(4)->getBeginLoc(), 1039 diag::err_opencl_builtin_expected_type) 1040 << TheCall->getDirectCallee() 1041 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1042 return true; 1043 } 1044 1045 // Sixth argument is always passed as a pointer to clk_event_t. 1046 if (!Arg5->isNullPointerConstant(S.Context, 1047 Expr::NPC_ValueDependentIsNotNull) && 1048 !(Arg5->getType()->isPointerType() && 1049 Arg5->getType()->getPointeeType()->isClkEventT())) { 1050 S.Diag(TheCall->getArg(5)->getBeginLoc(), 1051 diag::err_opencl_builtin_expected_type) 1052 << TheCall->getDirectCallee() 1053 << S.Context.getPointerType(S.Context.OCLClkEventTy); 1054 return true; 1055 } 1056 1057 if (NumArgs == 7) 1058 return false; 1059 1060 return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7); 1061 } 1062 1063 // None of the specific case has been detected, give generic error 1064 S.Diag(TheCall->getBeginLoc(), 1065 diag::err_opencl_enqueue_kernel_incorrect_args); 1066 return true; 1067 } 1068 1069 /// Returns OpenCL access qual. 1070 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) { 1071 return D->getAttr<OpenCLAccessAttr>(); 1072 } 1073 1074 /// Returns true if pipe element type is different from the pointer. 1075 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) { 1076 const Expr *Arg0 = Call->getArg(0); 1077 // First argument type should always be pipe. 1078 if (!Arg0->getType()->isPipeType()) { 1079 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1080 << Call->getDirectCallee() << Arg0->getSourceRange(); 1081 return true; 1082 } 1083 OpenCLAccessAttr *AccessQual = 1084 getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl()); 1085 // Validates the access qualifier is compatible with the call. 1086 // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be 1087 // read_only and write_only, and assumed to be read_only if no qualifier is 1088 // specified. 1089 switch (Call->getDirectCallee()->getBuiltinID()) { 1090 case Builtin::BIread_pipe: 1091 case Builtin::BIreserve_read_pipe: 1092 case Builtin::BIcommit_read_pipe: 1093 case Builtin::BIwork_group_reserve_read_pipe: 1094 case Builtin::BIsub_group_reserve_read_pipe: 1095 case Builtin::BIwork_group_commit_read_pipe: 1096 case Builtin::BIsub_group_commit_read_pipe: 1097 if (!(!AccessQual || AccessQual->isReadOnly())) { 1098 S.Diag(Arg0->getBeginLoc(), 1099 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1100 << "read_only" << Arg0->getSourceRange(); 1101 return true; 1102 } 1103 break; 1104 case Builtin::BIwrite_pipe: 1105 case Builtin::BIreserve_write_pipe: 1106 case Builtin::BIcommit_write_pipe: 1107 case Builtin::BIwork_group_reserve_write_pipe: 1108 case Builtin::BIsub_group_reserve_write_pipe: 1109 case Builtin::BIwork_group_commit_write_pipe: 1110 case Builtin::BIsub_group_commit_write_pipe: 1111 if (!(AccessQual && AccessQual->isWriteOnly())) { 1112 S.Diag(Arg0->getBeginLoc(), 1113 diag::err_opencl_builtin_pipe_invalid_access_modifier) 1114 << "write_only" << Arg0->getSourceRange(); 1115 return true; 1116 } 1117 break; 1118 default: 1119 break; 1120 } 1121 return false; 1122 } 1123 1124 /// Returns true if pipe element type is different from the pointer. 1125 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) { 1126 const Expr *Arg0 = Call->getArg(0); 1127 const Expr *ArgIdx = Call->getArg(Idx); 1128 const PipeType *PipeTy = cast<PipeType>(Arg0->getType()); 1129 const QualType EltTy = PipeTy->getElementType(); 1130 const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>(); 1131 // The Idx argument should be a pointer and the type of the pointer and 1132 // the type of pipe element should also be the same. 1133 if (!ArgTy || 1134 !S.Context.hasSameType( 1135 EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) { 1136 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1137 << Call->getDirectCallee() << S.Context.getPointerType(EltTy) 1138 << ArgIdx->getType() << ArgIdx->getSourceRange(); 1139 return true; 1140 } 1141 return false; 1142 } 1143 1144 // Performs semantic analysis for the read/write_pipe call. 1145 // \param S Reference to the semantic analyzer. 1146 // \param Call A pointer to the builtin call. 1147 // \return True if a semantic error has been found, false otherwise. 1148 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) { 1149 // OpenCL v2.0 s6.13.16.2 - The built-in read/write 1150 // functions have two forms. 1151 switch (Call->getNumArgs()) { 1152 case 2: 1153 if (checkOpenCLPipeArg(S, Call)) 1154 return true; 1155 // The call with 2 arguments should be 1156 // read/write_pipe(pipe T, T*). 1157 // Check packet type T. 1158 if (checkOpenCLPipePacketType(S, Call, 1)) 1159 return true; 1160 break; 1161 1162 case 4: { 1163 if (checkOpenCLPipeArg(S, Call)) 1164 return true; 1165 // The call with 4 arguments should be 1166 // read/write_pipe(pipe T, reserve_id_t, uint, T*). 1167 // Check reserve_id_t. 1168 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1169 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1170 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1171 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1172 return true; 1173 } 1174 1175 // Check the index. 1176 const Expr *Arg2 = Call->getArg(2); 1177 if (!Arg2->getType()->isIntegerType() && 1178 !Arg2->getType()->isUnsignedIntegerType()) { 1179 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1180 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1181 << Arg2->getType() << Arg2->getSourceRange(); 1182 return true; 1183 } 1184 1185 // Check packet type T. 1186 if (checkOpenCLPipePacketType(S, Call, 3)) 1187 return true; 1188 } break; 1189 default: 1190 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num) 1191 << Call->getDirectCallee() << Call->getSourceRange(); 1192 return true; 1193 } 1194 1195 return false; 1196 } 1197 1198 // Performs a semantic analysis on the {work_group_/sub_group_ 1199 // /_}reserve_{read/write}_pipe 1200 // \param S Reference to the semantic analyzer. 1201 // \param Call The call to the builtin function to be analyzed. 1202 // \return True if a semantic error was found, false otherwise. 1203 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) { 1204 if (checkArgCount(S, Call, 2)) 1205 return true; 1206 1207 if (checkOpenCLPipeArg(S, Call)) 1208 return true; 1209 1210 // Check the reserve size. 1211 if (!Call->getArg(1)->getType()->isIntegerType() && 1212 !Call->getArg(1)->getType()->isUnsignedIntegerType()) { 1213 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1214 << Call->getDirectCallee() << S.Context.UnsignedIntTy 1215 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1216 return true; 1217 } 1218 1219 // Since return type of reserve_read/write_pipe built-in function is 1220 // reserve_id_t, which is not defined in the builtin def file , we used int 1221 // as return type and need to override the return type of these functions. 1222 Call->setType(S.Context.OCLReserveIDTy); 1223 1224 return false; 1225 } 1226 1227 // Performs a semantic analysis on {work_group_/sub_group_ 1228 // /_}commit_{read/write}_pipe 1229 // \param S Reference to the semantic analyzer. 1230 // \param Call The call to the builtin function to be analyzed. 1231 // \return True if a semantic error was found, false otherwise. 1232 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) { 1233 if (checkArgCount(S, Call, 2)) 1234 return true; 1235 1236 if (checkOpenCLPipeArg(S, Call)) 1237 return true; 1238 1239 // Check reserve_id_t. 1240 if (!Call->getArg(1)->getType()->isReserveIDT()) { 1241 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg) 1242 << Call->getDirectCallee() << S.Context.OCLReserveIDTy 1243 << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange(); 1244 return true; 1245 } 1246 1247 return false; 1248 } 1249 1250 // Performs a semantic analysis on the call to built-in Pipe 1251 // Query Functions. 1252 // \param S Reference to the semantic analyzer. 1253 // \param Call The call to the builtin function to be analyzed. 1254 // \return True if a semantic error was found, false otherwise. 1255 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) { 1256 if (checkArgCount(S, Call, 1)) 1257 return true; 1258 1259 if (!Call->getArg(0)->getType()->isPipeType()) { 1260 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg) 1261 << Call->getDirectCallee() << Call->getArg(0)->getSourceRange(); 1262 return true; 1263 } 1264 1265 return false; 1266 } 1267 1268 // OpenCL v2.0 s6.13.9 - Address space qualifier functions. 1269 // Performs semantic analysis for the to_global/local/private call. 1270 // \param S Reference to the semantic analyzer. 1271 // \param BuiltinID ID of the builtin function. 1272 // \param Call A pointer to the builtin call. 1273 // \return True if a semantic error has been found, false otherwise. 1274 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, 1275 CallExpr *Call) { 1276 if (Call->getNumArgs() != 1) { 1277 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_arg_num) 1278 << Call->getDirectCallee() << Call->getSourceRange(); 1279 return true; 1280 } 1281 1282 auto RT = Call->getArg(0)->getType(); 1283 if (!RT->isPointerType() || RT->getPointeeType() 1284 .getAddressSpace() == LangAS::opencl_constant) { 1285 S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg) 1286 << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange(); 1287 return true; 1288 } 1289 1290 if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) { 1291 S.Diag(Call->getArg(0)->getBeginLoc(), 1292 diag::warn_opencl_generic_address_space_arg) 1293 << Call->getDirectCallee()->getNameInfo().getAsString() 1294 << Call->getArg(0)->getSourceRange(); 1295 } 1296 1297 RT = RT->getPointeeType(); 1298 auto Qual = RT.getQualifiers(); 1299 switch (BuiltinID) { 1300 case Builtin::BIto_global: 1301 Qual.setAddressSpace(LangAS::opencl_global); 1302 break; 1303 case Builtin::BIto_local: 1304 Qual.setAddressSpace(LangAS::opencl_local); 1305 break; 1306 case Builtin::BIto_private: 1307 Qual.setAddressSpace(LangAS::opencl_private); 1308 break; 1309 default: 1310 llvm_unreachable("Invalid builtin function"); 1311 } 1312 Call->setType(S.Context.getPointerType(S.Context.getQualifiedType( 1313 RT.getUnqualifiedType(), Qual))); 1314 1315 return false; 1316 } 1317 1318 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) { 1319 if (checkArgCount(S, TheCall, 1)) 1320 return ExprError(); 1321 1322 // Compute __builtin_launder's parameter type from the argument. 1323 // The parameter type is: 1324 // * The type of the argument if it's not an array or function type, 1325 // Otherwise, 1326 // * The decayed argument type. 1327 QualType ParamTy = [&]() { 1328 QualType ArgTy = TheCall->getArg(0)->getType(); 1329 if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe()) 1330 return S.Context.getPointerType(Ty->getElementType()); 1331 if (ArgTy->isFunctionType()) { 1332 return S.Context.getPointerType(ArgTy); 1333 } 1334 return ArgTy; 1335 }(); 1336 1337 TheCall->setType(ParamTy); 1338 1339 auto DiagSelect = [&]() -> llvm::Optional<unsigned> { 1340 if (!ParamTy->isPointerType()) 1341 return 0; 1342 if (ParamTy->isFunctionPointerType()) 1343 return 1; 1344 if (ParamTy->isVoidPointerType()) 1345 return 2; 1346 return llvm::Optional<unsigned>{}; 1347 }(); 1348 if (DiagSelect.hasValue()) { 1349 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg) 1350 << DiagSelect.getValue() << TheCall->getSourceRange(); 1351 return ExprError(); 1352 } 1353 1354 // We either have an incomplete class type, or we have a class template 1355 // whose instantiation has not been forced. Example: 1356 // 1357 // template <class T> struct Foo { T value; }; 1358 // Foo<int> *p = nullptr; 1359 // auto *d = __builtin_launder(p); 1360 if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(), 1361 diag::err_incomplete_type)) 1362 return ExprError(); 1363 1364 assert(ParamTy->getPointeeType()->isObjectType() && 1365 "Unhandled non-object pointer case"); 1366 1367 InitializedEntity Entity = 1368 InitializedEntity::InitializeParameter(S.Context, ParamTy, false); 1369 ExprResult Arg = 1370 S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0)); 1371 if (Arg.isInvalid()) 1372 return ExprError(); 1373 TheCall->setArg(0, Arg.get()); 1374 1375 return TheCall; 1376 } 1377 1378 // Emit an error and return true if the current architecture is not in the list 1379 // of supported architectures. 1380 static bool 1381 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall, 1382 ArrayRef<llvm::Triple::ArchType> SupportedArchs) { 1383 llvm::Triple::ArchType CurArch = 1384 S.getASTContext().getTargetInfo().getTriple().getArch(); 1385 if (llvm::is_contained(SupportedArchs, CurArch)) 1386 return false; 1387 S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported) 1388 << TheCall->getSourceRange(); 1389 return true; 1390 } 1391 1392 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, 1393 SourceLocation CallSiteLoc); 1394 1395 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 1396 CallExpr *TheCall) { 1397 switch (TI.getTriple().getArch()) { 1398 default: 1399 // Some builtins don't require additional checking, so just consider these 1400 // acceptable. 1401 return false; 1402 case llvm::Triple::arm: 1403 case llvm::Triple::armeb: 1404 case llvm::Triple::thumb: 1405 case llvm::Triple::thumbeb: 1406 return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall); 1407 case llvm::Triple::aarch64: 1408 case llvm::Triple::aarch64_32: 1409 case llvm::Triple::aarch64_be: 1410 return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall); 1411 case llvm::Triple::bpfeb: 1412 case llvm::Triple::bpfel: 1413 return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall); 1414 case llvm::Triple::hexagon: 1415 return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall); 1416 case llvm::Triple::mips: 1417 case llvm::Triple::mipsel: 1418 case llvm::Triple::mips64: 1419 case llvm::Triple::mips64el: 1420 return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall); 1421 case llvm::Triple::systemz: 1422 return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall); 1423 case llvm::Triple::x86: 1424 case llvm::Triple::x86_64: 1425 return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall); 1426 case llvm::Triple::ppc: 1427 case llvm::Triple::ppc64: 1428 case llvm::Triple::ppc64le: 1429 return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall); 1430 case llvm::Triple::amdgcn: 1431 return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall); 1432 } 1433 } 1434 1435 ExprResult 1436 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, 1437 CallExpr *TheCall) { 1438 ExprResult TheCallResult(TheCall); 1439 1440 // Find out if any arguments are required to be integer constant expressions. 1441 unsigned ICEArguments = 0; 1442 ASTContext::GetBuiltinTypeError Error; 1443 Context.GetBuiltinType(BuiltinID, Error, &ICEArguments); 1444 if (Error != ASTContext::GE_None) 1445 ICEArguments = 0; // Don't diagnose previously diagnosed errors. 1446 1447 // If any arguments are required to be ICE's, check and diagnose. 1448 for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) { 1449 // Skip arguments not required to be ICE's. 1450 if ((ICEArguments & (1 << ArgNo)) == 0) continue; 1451 1452 llvm::APSInt Result; 1453 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result)) 1454 return true; 1455 ICEArguments &= ~(1 << ArgNo); 1456 } 1457 1458 switch (BuiltinID) { 1459 case Builtin::BI__builtin___CFStringMakeConstantString: 1460 assert(TheCall->getNumArgs() == 1 && 1461 "Wrong # arguments to builtin CFStringMakeConstantString"); 1462 if (CheckObjCString(TheCall->getArg(0))) 1463 return ExprError(); 1464 break; 1465 case Builtin::BI__builtin_ms_va_start: 1466 case Builtin::BI__builtin_stdarg_start: 1467 case Builtin::BI__builtin_va_start: 1468 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1469 return ExprError(); 1470 break; 1471 case Builtin::BI__va_start: { 1472 switch (Context.getTargetInfo().getTriple().getArch()) { 1473 case llvm::Triple::aarch64: 1474 case llvm::Triple::arm: 1475 case llvm::Triple::thumb: 1476 if (SemaBuiltinVAStartARMMicrosoft(TheCall)) 1477 return ExprError(); 1478 break; 1479 default: 1480 if (SemaBuiltinVAStart(BuiltinID, TheCall)) 1481 return ExprError(); 1482 break; 1483 } 1484 break; 1485 } 1486 1487 // The acquire, release, and no fence variants are ARM and AArch64 only. 1488 case Builtin::BI_interlockedbittestandset_acq: 1489 case Builtin::BI_interlockedbittestandset_rel: 1490 case Builtin::BI_interlockedbittestandset_nf: 1491 case Builtin::BI_interlockedbittestandreset_acq: 1492 case Builtin::BI_interlockedbittestandreset_rel: 1493 case Builtin::BI_interlockedbittestandreset_nf: 1494 if (CheckBuiltinTargetSupport( 1495 *this, BuiltinID, TheCall, 1496 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64})) 1497 return ExprError(); 1498 break; 1499 1500 // The 64-bit bittest variants are x64, ARM, and AArch64 only. 1501 case Builtin::BI_bittest64: 1502 case Builtin::BI_bittestandcomplement64: 1503 case Builtin::BI_bittestandreset64: 1504 case Builtin::BI_bittestandset64: 1505 case Builtin::BI_interlockedbittestandreset64: 1506 case Builtin::BI_interlockedbittestandset64: 1507 if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall, 1508 {llvm::Triple::x86_64, llvm::Triple::arm, 1509 llvm::Triple::thumb, llvm::Triple::aarch64})) 1510 return ExprError(); 1511 break; 1512 1513 case Builtin::BI__builtin_isgreater: 1514 case Builtin::BI__builtin_isgreaterequal: 1515 case Builtin::BI__builtin_isless: 1516 case Builtin::BI__builtin_islessequal: 1517 case Builtin::BI__builtin_islessgreater: 1518 case Builtin::BI__builtin_isunordered: 1519 if (SemaBuiltinUnorderedCompare(TheCall)) 1520 return ExprError(); 1521 break; 1522 case Builtin::BI__builtin_fpclassify: 1523 if (SemaBuiltinFPClassification(TheCall, 6)) 1524 return ExprError(); 1525 break; 1526 case Builtin::BI__builtin_isfinite: 1527 case Builtin::BI__builtin_isinf: 1528 case Builtin::BI__builtin_isinf_sign: 1529 case Builtin::BI__builtin_isnan: 1530 case Builtin::BI__builtin_isnormal: 1531 case Builtin::BI__builtin_signbit: 1532 case Builtin::BI__builtin_signbitf: 1533 case Builtin::BI__builtin_signbitl: 1534 if (SemaBuiltinFPClassification(TheCall, 1)) 1535 return ExprError(); 1536 break; 1537 case Builtin::BI__builtin_shufflevector: 1538 return SemaBuiltinShuffleVector(TheCall); 1539 // TheCall will be freed by the smart pointer here, but that's fine, since 1540 // SemaBuiltinShuffleVector guts it, but then doesn't release it. 1541 case Builtin::BI__builtin_prefetch: 1542 if (SemaBuiltinPrefetch(TheCall)) 1543 return ExprError(); 1544 break; 1545 case Builtin::BI__builtin_alloca_with_align: 1546 if (SemaBuiltinAllocaWithAlign(TheCall)) 1547 return ExprError(); 1548 LLVM_FALLTHROUGH; 1549 case Builtin::BI__builtin_alloca: 1550 Diag(TheCall->getBeginLoc(), diag::warn_alloca) 1551 << TheCall->getDirectCallee(); 1552 break; 1553 case Builtin::BI__assume: 1554 case Builtin::BI__builtin_assume: 1555 if (SemaBuiltinAssume(TheCall)) 1556 return ExprError(); 1557 break; 1558 case Builtin::BI__builtin_assume_aligned: 1559 if (SemaBuiltinAssumeAligned(TheCall)) 1560 return ExprError(); 1561 break; 1562 case Builtin::BI__builtin_dynamic_object_size: 1563 case Builtin::BI__builtin_object_size: 1564 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3)) 1565 return ExprError(); 1566 break; 1567 case Builtin::BI__builtin_longjmp: 1568 if (SemaBuiltinLongjmp(TheCall)) 1569 return ExprError(); 1570 break; 1571 case Builtin::BI__builtin_setjmp: 1572 if (SemaBuiltinSetjmp(TheCall)) 1573 return ExprError(); 1574 break; 1575 case Builtin::BI_setjmp: 1576 case Builtin::BI_setjmpex: 1577 if (checkArgCount(*this, TheCall, 1)) 1578 return true; 1579 break; 1580 case Builtin::BI__builtin_classify_type: 1581 if (checkArgCount(*this, TheCall, 1)) return true; 1582 TheCall->setType(Context.IntTy); 1583 break; 1584 case Builtin::BI__builtin_constant_p: { 1585 if (checkArgCount(*this, TheCall, 1)) return true; 1586 ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0)); 1587 if (Arg.isInvalid()) return true; 1588 TheCall->setArg(0, Arg.get()); 1589 TheCall->setType(Context.IntTy); 1590 break; 1591 } 1592 case Builtin::BI__builtin_launder: 1593 return SemaBuiltinLaunder(*this, TheCall); 1594 case Builtin::BI__sync_fetch_and_add: 1595 case Builtin::BI__sync_fetch_and_add_1: 1596 case Builtin::BI__sync_fetch_and_add_2: 1597 case Builtin::BI__sync_fetch_and_add_4: 1598 case Builtin::BI__sync_fetch_and_add_8: 1599 case Builtin::BI__sync_fetch_and_add_16: 1600 case Builtin::BI__sync_fetch_and_sub: 1601 case Builtin::BI__sync_fetch_and_sub_1: 1602 case Builtin::BI__sync_fetch_and_sub_2: 1603 case Builtin::BI__sync_fetch_and_sub_4: 1604 case Builtin::BI__sync_fetch_and_sub_8: 1605 case Builtin::BI__sync_fetch_and_sub_16: 1606 case Builtin::BI__sync_fetch_and_or: 1607 case Builtin::BI__sync_fetch_and_or_1: 1608 case Builtin::BI__sync_fetch_and_or_2: 1609 case Builtin::BI__sync_fetch_and_or_4: 1610 case Builtin::BI__sync_fetch_and_or_8: 1611 case Builtin::BI__sync_fetch_and_or_16: 1612 case Builtin::BI__sync_fetch_and_and: 1613 case Builtin::BI__sync_fetch_and_and_1: 1614 case Builtin::BI__sync_fetch_and_and_2: 1615 case Builtin::BI__sync_fetch_and_and_4: 1616 case Builtin::BI__sync_fetch_and_and_8: 1617 case Builtin::BI__sync_fetch_and_and_16: 1618 case Builtin::BI__sync_fetch_and_xor: 1619 case Builtin::BI__sync_fetch_and_xor_1: 1620 case Builtin::BI__sync_fetch_and_xor_2: 1621 case Builtin::BI__sync_fetch_and_xor_4: 1622 case Builtin::BI__sync_fetch_and_xor_8: 1623 case Builtin::BI__sync_fetch_and_xor_16: 1624 case Builtin::BI__sync_fetch_and_nand: 1625 case Builtin::BI__sync_fetch_and_nand_1: 1626 case Builtin::BI__sync_fetch_and_nand_2: 1627 case Builtin::BI__sync_fetch_and_nand_4: 1628 case Builtin::BI__sync_fetch_and_nand_8: 1629 case Builtin::BI__sync_fetch_and_nand_16: 1630 case Builtin::BI__sync_add_and_fetch: 1631 case Builtin::BI__sync_add_and_fetch_1: 1632 case Builtin::BI__sync_add_and_fetch_2: 1633 case Builtin::BI__sync_add_and_fetch_4: 1634 case Builtin::BI__sync_add_and_fetch_8: 1635 case Builtin::BI__sync_add_and_fetch_16: 1636 case Builtin::BI__sync_sub_and_fetch: 1637 case Builtin::BI__sync_sub_and_fetch_1: 1638 case Builtin::BI__sync_sub_and_fetch_2: 1639 case Builtin::BI__sync_sub_and_fetch_4: 1640 case Builtin::BI__sync_sub_and_fetch_8: 1641 case Builtin::BI__sync_sub_and_fetch_16: 1642 case Builtin::BI__sync_and_and_fetch: 1643 case Builtin::BI__sync_and_and_fetch_1: 1644 case Builtin::BI__sync_and_and_fetch_2: 1645 case Builtin::BI__sync_and_and_fetch_4: 1646 case Builtin::BI__sync_and_and_fetch_8: 1647 case Builtin::BI__sync_and_and_fetch_16: 1648 case Builtin::BI__sync_or_and_fetch: 1649 case Builtin::BI__sync_or_and_fetch_1: 1650 case Builtin::BI__sync_or_and_fetch_2: 1651 case Builtin::BI__sync_or_and_fetch_4: 1652 case Builtin::BI__sync_or_and_fetch_8: 1653 case Builtin::BI__sync_or_and_fetch_16: 1654 case Builtin::BI__sync_xor_and_fetch: 1655 case Builtin::BI__sync_xor_and_fetch_1: 1656 case Builtin::BI__sync_xor_and_fetch_2: 1657 case Builtin::BI__sync_xor_and_fetch_4: 1658 case Builtin::BI__sync_xor_and_fetch_8: 1659 case Builtin::BI__sync_xor_and_fetch_16: 1660 case Builtin::BI__sync_nand_and_fetch: 1661 case Builtin::BI__sync_nand_and_fetch_1: 1662 case Builtin::BI__sync_nand_and_fetch_2: 1663 case Builtin::BI__sync_nand_and_fetch_4: 1664 case Builtin::BI__sync_nand_and_fetch_8: 1665 case Builtin::BI__sync_nand_and_fetch_16: 1666 case Builtin::BI__sync_val_compare_and_swap: 1667 case Builtin::BI__sync_val_compare_and_swap_1: 1668 case Builtin::BI__sync_val_compare_and_swap_2: 1669 case Builtin::BI__sync_val_compare_and_swap_4: 1670 case Builtin::BI__sync_val_compare_and_swap_8: 1671 case Builtin::BI__sync_val_compare_and_swap_16: 1672 case Builtin::BI__sync_bool_compare_and_swap: 1673 case Builtin::BI__sync_bool_compare_and_swap_1: 1674 case Builtin::BI__sync_bool_compare_and_swap_2: 1675 case Builtin::BI__sync_bool_compare_and_swap_4: 1676 case Builtin::BI__sync_bool_compare_and_swap_8: 1677 case Builtin::BI__sync_bool_compare_and_swap_16: 1678 case Builtin::BI__sync_lock_test_and_set: 1679 case Builtin::BI__sync_lock_test_and_set_1: 1680 case Builtin::BI__sync_lock_test_and_set_2: 1681 case Builtin::BI__sync_lock_test_and_set_4: 1682 case Builtin::BI__sync_lock_test_and_set_8: 1683 case Builtin::BI__sync_lock_test_and_set_16: 1684 case Builtin::BI__sync_lock_release: 1685 case Builtin::BI__sync_lock_release_1: 1686 case Builtin::BI__sync_lock_release_2: 1687 case Builtin::BI__sync_lock_release_4: 1688 case Builtin::BI__sync_lock_release_8: 1689 case Builtin::BI__sync_lock_release_16: 1690 case Builtin::BI__sync_swap: 1691 case Builtin::BI__sync_swap_1: 1692 case Builtin::BI__sync_swap_2: 1693 case Builtin::BI__sync_swap_4: 1694 case Builtin::BI__sync_swap_8: 1695 case Builtin::BI__sync_swap_16: 1696 return SemaBuiltinAtomicOverloaded(TheCallResult); 1697 case Builtin::BI__sync_synchronize: 1698 Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst) 1699 << TheCall->getCallee()->getSourceRange(); 1700 break; 1701 case Builtin::BI__builtin_nontemporal_load: 1702 case Builtin::BI__builtin_nontemporal_store: 1703 return SemaBuiltinNontemporalOverloaded(TheCallResult); 1704 case Builtin::BI__builtin_memcpy_inline: { 1705 clang::Expr *SizeOp = TheCall->getArg(2); 1706 // We warn about copying to or from `nullptr` pointers when `size` is 1707 // greater than 0. When `size` is value dependent we cannot evaluate its 1708 // value so we bail out. 1709 if (SizeOp->isValueDependent()) 1710 break; 1711 if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) { 1712 CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc()); 1713 CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc()); 1714 } 1715 break; 1716 } 1717 #define BUILTIN(ID, TYPE, ATTRS) 1718 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \ 1719 case Builtin::BI##ID: \ 1720 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID); 1721 #include "clang/Basic/Builtins.def" 1722 case Builtin::BI__annotation: 1723 if (SemaBuiltinMSVCAnnotation(*this, TheCall)) 1724 return ExprError(); 1725 break; 1726 case Builtin::BI__builtin_annotation: 1727 if (SemaBuiltinAnnotation(*this, TheCall)) 1728 return ExprError(); 1729 break; 1730 case Builtin::BI__builtin_addressof: 1731 if (SemaBuiltinAddressof(*this, TheCall)) 1732 return ExprError(); 1733 break; 1734 case Builtin::BI__builtin_is_aligned: 1735 case Builtin::BI__builtin_align_up: 1736 case Builtin::BI__builtin_align_down: 1737 if (SemaBuiltinAlignment(*this, TheCall, BuiltinID)) 1738 return ExprError(); 1739 break; 1740 case Builtin::BI__builtin_add_overflow: 1741 case Builtin::BI__builtin_sub_overflow: 1742 case Builtin::BI__builtin_mul_overflow: 1743 if (SemaBuiltinOverflow(*this, TheCall, BuiltinID)) 1744 return ExprError(); 1745 break; 1746 case Builtin::BI__builtin_operator_new: 1747 case Builtin::BI__builtin_operator_delete: { 1748 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete; 1749 ExprResult Res = 1750 SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete); 1751 if (Res.isInvalid()) 1752 CorrectDelayedTyposInExpr(TheCallResult.get()); 1753 return Res; 1754 } 1755 case Builtin::BI__builtin_dump_struct: { 1756 // We first want to ensure we are called with 2 arguments 1757 if (checkArgCount(*this, TheCall, 2)) 1758 return ExprError(); 1759 // Ensure that the first argument is of type 'struct XX *' 1760 const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts(); 1761 const QualType PtrArgType = PtrArg->getType(); 1762 if (!PtrArgType->isPointerType() || 1763 !PtrArgType->getPointeeType()->isRecordType()) { 1764 Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1765 << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType 1766 << "structure pointer"; 1767 return ExprError(); 1768 } 1769 1770 // Ensure that the second argument is of type 'FunctionType' 1771 const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts(); 1772 const QualType FnPtrArgType = FnPtrArg->getType(); 1773 if (!FnPtrArgType->isPointerType()) { 1774 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1775 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1776 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1777 return ExprError(); 1778 } 1779 1780 const auto *FuncType = 1781 FnPtrArgType->getPointeeType()->getAs<FunctionType>(); 1782 1783 if (!FuncType) { 1784 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1785 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2 1786 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1787 return ExprError(); 1788 } 1789 1790 if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) { 1791 if (!FT->getNumParams()) { 1792 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1793 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1794 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1795 return ExprError(); 1796 } 1797 QualType PT = FT->getParamType(0); 1798 if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy || 1799 !PT->isPointerType() || !PT->getPointeeType()->isCharType() || 1800 !PT->getPointeeType().isConstQualified()) { 1801 Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible) 1802 << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 1803 << 2 << FnPtrArgType << "'int (*)(const char *, ...)'"; 1804 return ExprError(); 1805 } 1806 } 1807 1808 TheCall->setType(Context.IntTy); 1809 break; 1810 } 1811 case Builtin::BI__builtin_preserve_access_index: 1812 if (SemaBuiltinPreserveAI(*this, TheCall)) 1813 return ExprError(); 1814 break; 1815 case Builtin::BI__builtin_call_with_static_chain: 1816 if (SemaBuiltinCallWithStaticChain(*this, TheCall)) 1817 return ExprError(); 1818 break; 1819 case Builtin::BI__exception_code: 1820 case Builtin::BI_exception_code: 1821 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope, 1822 diag::err_seh___except_block)) 1823 return ExprError(); 1824 break; 1825 case Builtin::BI__exception_info: 1826 case Builtin::BI_exception_info: 1827 if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope, 1828 diag::err_seh___except_filter)) 1829 return ExprError(); 1830 break; 1831 case Builtin::BI__GetExceptionInfo: 1832 if (checkArgCount(*this, TheCall, 1)) 1833 return ExprError(); 1834 1835 if (CheckCXXThrowOperand( 1836 TheCall->getBeginLoc(), 1837 Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()), 1838 TheCall)) 1839 return ExprError(); 1840 1841 TheCall->setType(Context.VoidPtrTy); 1842 break; 1843 // OpenCL v2.0, s6.13.16 - Pipe functions 1844 case Builtin::BIread_pipe: 1845 case Builtin::BIwrite_pipe: 1846 // Since those two functions are declared with var args, we need a semantic 1847 // check for the argument. 1848 if (SemaBuiltinRWPipe(*this, TheCall)) 1849 return ExprError(); 1850 break; 1851 case Builtin::BIreserve_read_pipe: 1852 case Builtin::BIreserve_write_pipe: 1853 case Builtin::BIwork_group_reserve_read_pipe: 1854 case Builtin::BIwork_group_reserve_write_pipe: 1855 if (SemaBuiltinReserveRWPipe(*this, TheCall)) 1856 return ExprError(); 1857 break; 1858 case Builtin::BIsub_group_reserve_read_pipe: 1859 case Builtin::BIsub_group_reserve_write_pipe: 1860 if (checkOpenCLSubgroupExt(*this, TheCall) || 1861 SemaBuiltinReserveRWPipe(*this, TheCall)) 1862 return ExprError(); 1863 break; 1864 case Builtin::BIcommit_read_pipe: 1865 case Builtin::BIcommit_write_pipe: 1866 case Builtin::BIwork_group_commit_read_pipe: 1867 case Builtin::BIwork_group_commit_write_pipe: 1868 if (SemaBuiltinCommitRWPipe(*this, TheCall)) 1869 return ExprError(); 1870 break; 1871 case Builtin::BIsub_group_commit_read_pipe: 1872 case Builtin::BIsub_group_commit_write_pipe: 1873 if (checkOpenCLSubgroupExt(*this, TheCall) || 1874 SemaBuiltinCommitRWPipe(*this, TheCall)) 1875 return ExprError(); 1876 break; 1877 case Builtin::BIget_pipe_num_packets: 1878 case Builtin::BIget_pipe_max_packets: 1879 if (SemaBuiltinPipePackets(*this, TheCall)) 1880 return ExprError(); 1881 break; 1882 case Builtin::BIto_global: 1883 case Builtin::BIto_local: 1884 case Builtin::BIto_private: 1885 if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall)) 1886 return ExprError(); 1887 break; 1888 // OpenCL v2.0, s6.13.17 - Enqueue kernel functions. 1889 case Builtin::BIenqueue_kernel: 1890 if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall)) 1891 return ExprError(); 1892 break; 1893 case Builtin::BIget_kernel_work_group_size: 1894 case Builtin::BIget_kernel_preferred_work_group_size_multiple: 1895 if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall)) 1896 return ExprError(); 1897 break; 1898 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange: 1899 case Builtin::BIget_kernel_sub_group_count_for_ndrange: 1900 if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall)) 1901 return ExprError(); 1902 break; 1903 case Builtin::BI__builtin_os_log_format: 1904 Cleanup.setExprNeedsCleanups(true); 1905 LLVM_FALLTHROUGH; 1906 case Builtin::BI__builtin_os_log_format_buffer_size: 1907 if (SemaBuiltinOSLogFormat(TheCall)) 1908 return ExprError(); 1909 break; 1910 case Builtin::BI__builtin_frame_address: 1911 case Builtin::BI__builtin_return_address: { 1912 if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF)) 1913 return ExprError(); 1914 1915 // -Wframe-address warning if non-zero passed to builtin 1916 // return/frame address. 1917 Expr::EvalResult Result; 1918 if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) && 1919 Result.Val.getInt() != 0) 1920 Diag(TheCall->getBeginLoc(), diag::warn_frame_address) 1921 << ((BuiltinID == Builtin::BI__builtin_return_address) 1922 ? "__builtin_return_address" 1923 : "__builtin_frame_address") 1924 << TheCall->getSourceRange(); 1925 break; 1926 } 1927 1928 case Builtin::BI__builtin_matrix_transpose: 1929 return SemaBuiltinMatrixTranspose(TheCall, TheCallResult); 1930 } 1931 1932 // Since the target specific builtins for each arch overlap, only check those 1933 // of the arch we are compiling for. 1934 if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) { 1935 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) { 1936 assert(Context.getAuxTargetInfo() && 1937 "Aux Target Builtin, but not an aux target?"); 1938 1939 if (CheckTSBuiltinFunctionCall( 1940 *Context.getAuxTargetInfo(), 1941 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall)) 1942 return ExprError(); 1943 } else { 1944 if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID, 1945 TheCall)) 1946 return ExprError(); 1947 } 1948 } 1949 1950 return TheCallResult; 1951 } 1952 1953 // Get the valid immediate range for the specified NEON type code. 1954 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) { 1955 NeonTypeFlags Type(t); 1956 int IsQuad = ForceQuad ? true : Type.isQuad(); 1957 switch (Type.getEltType()) { 1958 case NeonTypeFlags::Int8: 1959 case NeonTypeFlags::Poly8: 1960 return shift ? 7 : (8 << IsQuad) - 1; 1961 case NeonTypeFlags::Int16: 1962 case NeonTypeFlags::Poly16: 1963 return shift ? 15 : (4 << IsQuad) - 1; 1964 case NeonTypeFlags::Int32: 1965 return shift ? 31 : (2 << IsQuad) - 1; 1966 case NeonTypeFlags::Int64: 1967 case NeonTypeFlags::Poly64: 1968 return shift ? 63 : (1 << IsQuad) - 1; 1969 case NeonTypeFlags::Poly128: 1970 return shift ? 127 : (1 << IsQuad) - 1; 1971 case NeonTypeFlags::Float16: 1972 assert(!shift && "cannot shift float types!"); 1973 return (4 << IsQuad) - 1; 1974 case NeonTypeFlags::Float32: 1975 assert(!shift && "cannot shift float types!"); 1976 return (2 << IsQuad) - 1; 1977 case NeonTypeFlags::Float64: 1978 assert(!shift && "cannot shift float types!"); 1979 return (1 << IsQuad) - 1; 1980 case NeonTypeFlags::BFloat16: 1981 assert(!shift && "cannot shift float types!"); 1982 return (4 << IsQuad) - 1; 1983 } 1984 llvm_unreachable("Invalid NeonTypeFlag!"); 1985 } 1986 1987 /// getNeonEltType - Return the QualType corresponding to the elements of 1988 /// the vector type specified by the NeonTypeFlags. This is used to check 1989 /// the pointer arguments for Neon load/store intrinsics. 1990 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, 1991 bool IsPolyUnsigned, bool IsInt64Long) { 1992 switch (Flags.getEltType()) { 1993 case NeonTypeFlags::Int8: 1994 return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy; 1995 case NeonTypeFlags::Int16: 1996 return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy; 1997 case NeonTypeFlags::Int32: 1998 return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy; 1999 case NeonTypeFlags::Int64: 2000 if (IsInt64Long) 2001 return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy; 2002 else 2003 return Flags.isUnsigned() ? Context.UnsignedLongLongTy 2004 : Context.LongLongTy; 2005 case NeonTypeFlags::Poly8: 2006 return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy; 2007 case NeonTypeFlags::Poly16: 2008 return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy; 2009 case NeonTypeFlags::Poly64: 2010 if (IsInt64Long) 2011 return Context.UnsignedLongTy; 2012 else 2013 return Context.UnsignedLongLongTy; 2014 case NeonTypeFlags::Poly128: 2015 break; 2016 case NeonTypeFlags::Float16: 2017 return Context.HalfTy; 2018 case NeonTypeFlags::Float32: 2019 return Context.FloatTy; 2020 case NeonTypeFlags::Float64: 2021 return Context.DoubleTy; 2022 case NeonTypeFlags::BFloat16: 2023 return Context.BFloat16Ty; 2024 } 2025 llvm_unreachable("Invalid NeonTypeFlag!"); 2026 } 2027 2028 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2029 // Range check SVE intrinsics that take immediate values. 2030 SmallVector<std::tuple<int,int,int>, 3> ImmChecks; 2031 2032 switch (BuiltinID) { 2033 default: 2034 return false; 2035 #define GET_SVE_IMMEDIATE_CHECK 2036 #include "clang/Basic/arm_sve_sema_rangechecks.inc" 2037 #undef GET_SVE_IMMEDIATE_CHECK 2038 } 2039 2040 // Perform all the immediate checks for this builtin call. 2041 bool HasError = false; 2042 for (auto &I : ImmChecks) { 2043 int ArgNum, CheckTy, ElementSizeInBits; 2044 std::tie(ArgNum, CheckTy, ElementSizeInBits) = I; 2045 2046 typedef bool(*OptionSetCheckFnTy)(int64_t Value); 2047 2048 // Function that checks whether the operand (ArgNum) is an immediate 2049 // that is one of the predefined values. 2050 auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm, 2051 int ErrDiag) -> bool { 2052 // We can't check the value of a dependent argument. 2053 Expr *Arg = TheCall->getArg(ArgNum); 2054 if (Arg->isTypeDependent() || Arg->isValueDependent()) 2055 return false; 2056 2057 // Check constant-ness first. 2058 llvm::APSInt Imm; 2059 if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm)) 2060 return true; 2061 2062 if (!CheckImm(Imm.getSExtValue())) 2063 return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange(); 2064 return false; 2065 }; 2066 2067 switch ((SVETypeFlags::ImmCheckType)CheckTy) { 2068 case SVETypeFlags::ImmCheck0_31: 2069 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31)) 2070 HasError = true; 2071 break; 2072 case SVETypeFlags::ImmCheck0_13: 2073 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13)) 2074 HasError = true; 2075 break; 2076 case SVETypeFlags::ImmCheck1_16: 2077 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16)) 2078 HasError = true; 2079 break; 2080 case SVETypeFlags::ImmCheck0_7: 2081 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7)) 2082 HasError = true; 2083 break; 2084 case SVETypeFlags::ImmCheckExtract: 2085 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2086 (2048 / ElementSizeInBits) - 1)) 2087 HasError = true; 2088 break; 2089 case SVETypeFlags::ImmCheckShiftRight: 2090 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits)) 2091 HasError = true; 2092 break; 2093 case SVETypeFlags::ImmCheckShiftRightNarrow: 2094 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 2095 ElementSizeInBits / 2)) 2096 HasError = true; 2097 break; 2098 case SVETypeFlags::ImmCheckShiftLeft: 2099 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2100 ElementSizeInBits - 1)) 2101 HasError = true; 2102 break; 2103 case SVETypeFlags::ImmCheckLaneIndex: 2104 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2105 (128 / (1 * ElementSizeInBits)) - 1)) 2106 HasError = true; 2107 break; 2108 case SVETypeFlags::ImmCheckLaneIndexCompRotate: 2109 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2110 (128 / (2 * ElementSizeInBits)) - 1)) 2111 HasError = true; 2112 break; 2113 case SVETypeFlags::ImmCheckLaneIndexDot: 2114 if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2115 (128 / (4 * ElementSizeInBits)) - 1)) 2116 HasError = true; 2117 break; 2118 case SVETypeFlags::ImmCheckComplexRot90_270: 2119 if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; }, 2120 diag::err_rotation_argument_to_cadd)) 2121 HasError = true; 2122 break; 2123 case SVETypeFlags::ImmCheckComplexRotAll90: 2124 if (CheckImmediateInSet( 2125 [](int64_t V) { 2126 return V == 0 || V == 90 || V == 180 || V == 270; 2127 }, 2128 diag::err_rotation_argument_to_cmla)) 2129 HasError = true; 2130 break; 2131 } 2132 } 2133 2134 return HasError; 2135 } 2136 2137 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI, 2138 unsigned BuiltinID, CallExpr *TheCall) { 2139 llvm::APSInt Result; 2140 uint64_t mask = 0; 2141 unsigned TV = 0; 2142 int PtrArgNum = -1; 2143 bool HasConstPtr = false; 2144 switch (BuiltinID) { 2145 #define GET_NEON_OVERLOAD_CHECK 2146 #include "clang/Basic/arm_neon.inc" 2147 #include "clang/Basic/arm_fp16.inc" 2148 #undef GET_NEON_OVERLOAD_CHECK 2149 } 2150 2151 // For NEON intrinsics which are overloaded on vector element type, validate 2152 // the immediate which specifies which variant to emit. 2153 unsigned ImmArg = TheCall->getNumArgs()-1; 2154 if (mask) { 2155 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result)) 2156 return true; 2157 2158 TV = Result.getLimitedValue(64); 2159 if ((TV > 63) || (mask & (1ULL << TV)) == 0) 2160 return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code) 2161 << TheCall->getArg(ImmArg)->getSourceRange(); 2162 } 2163 2164 if (PtrArgNum >= 0) { 2165 // Check that pointer arguments have the specified type. 2166 Expr *Arg = TheCall->getArg(PtrArgNum); 2167 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) 2168 Arg = ICE->getSubExpr(); 2169 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg); 2170 QualType RHSTy = RHS.get()->getType(); 2171 2172 llvm::Triple::ArchType Arch = TI.getTriple().getArch(); 2173 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 || 2174 Arch == llvm::Triple::aarch64_32 || 2175 Arch == llvm::Triple::aarch64_be; 2176 bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong; 2177 QualType EltTy = 2178 getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long); 2179 if (HasConstPtr) 2180 EltTy = EltTy.withConst(); 2181 QualType LHSTy = Context.getPointerType(EltTy); 2182 AssignConvertType ConvTy; 2183 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS); 2184 if (RHS.isInvalid()) 2185 return true; 2186 if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy, 2187 RHS.get(), AA_Assigning)) 2188 return true; 2189 } 2190 2191 // For NEON intrinsics which take an immediate value as part of the 2192 // instruction, range check them here. 2193 unsigned i = 0, l = 0, u = 0; 2194 switch (BuiltinID) { 2195 default: 2196 return false; 2197 #define GET_NEON_IMMEDIATE_CHECK 2198 #include "clang/Basic/arm_neon.inc" 2199 #include "clang/Basic/arm_fp16.inc" 2200 #undef GET_NEON_IMMEDIATE_CHECK 2201 } 2202 2203 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2204 } 2205 2206 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) { 2207 switch (BuiltinID) { 2208 default: 2209 return false; 2210 #include "clang/Basic/arm_mve_builtin_sema.inc" 2211 } 2212 } 2213 2214 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2215 CallExpr *TheCall) { 2216 bool Err = false; 2217 switch (BuiltinID) { 2218 default: 2219 return false; 2220 #include "clang/Basic/arm_cde_builtin_sema.inc" 2221 } 2222 2223 if (Err) 2224 return true; 2225 2226 return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true); 2227 } 2228 2229 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI, 2230 const Expr *CoprocArg, bool WantCDE) { 2231 if (isConstantEvaluated()) 2232 return false; 2233 2234 // We can't check the value of a dependent argument. 2235 if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent()) 2236 return false; 2237 2238 llvm::APSInt CoprocNoAP; 2239 bool IsICE = CoprocArg->isIntegerConstantExpr(CoprocNoAP, Context); 2240 (void)IsICE; 2241 assert(IsICE && "Coprocossor immediate is not a constant expression"); 2242 int64_t CoprocNo = CoprocNoAP.getExtValue(); 2243 assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative"); 2244 2245 uint32_t CDECoprocMask = TI.getARMCDECoprocMask(); 2246 bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo)); 2247 2248 if (IsCDECoproc != WantCDE) 2249 return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc) 2250 << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange(); 2251 2252 return false; 2253 } 2254 2255 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, 2256 unsigned MaxWidth) { 2257 assert((BuiltinID == ARM::BI__builtin_arm_ldrex || 2258 BuiltinID == ARM::BI__builtin_arm_ldaex || 2259 BuiltinID == ARM::BI__builtin_arm_strex || 2260 BuiltinID == ARM::BI__builtin_arm_stlex || 2261 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2262 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2263 BuiltinID == AArch64::BI__builtin_arm_strex || 2264 BuiltinID == AArch64::BI__builtin_arm_stlex) && 2265 "unexpected ARM builtin"); 2266 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex || 2267 BuiltinID == ARM::BI__builtin_arm_ldaex || 2268 BuiltinID == AArch64::BI__builtin_arm_ldrex || 2269 BuiltinID == AArch64::BI__builtin_arm_ldaex; 2270 2271 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 2272 2273 // Ensure that we have the proper number of arguments. 2274 if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2)) 2275 return true; 2276 2277 // Inspect the pointer argument of the atomic builtin. This should always be 2278 // a pointer type, whose element is an integral scalar or pointer type. 2279 // Because it is a pointer type, we don't have to worry about any implicit 2280 // casts here. 2281 Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1); 2282 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg); 2283 if (PointerArgRes.isInvalid()) 2284 return true; 2285 PointerArg = PointerArgRes.get(); 2286 2287 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 2288 if (!pointerType) { 2289 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 2290 << PointerArg->getType() << PointerArg->getSourceRange(); 2291 return true; 2292 } 2293 2294 // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next 2295 // task is to insert the appropriate casts into the AST. First work out just 2296 // what the appropriate type is. 2297 QualType ValType = pointerType->getPointeeType(); 2298 QualType AddrType = ValType.getUnqualifiedType().withVolatile(); 2299 if (IsLdrex) 2300 AddrType.addConst(); 2301 2302 // Issue a warning if the cast is dodgy. 2303 CastKind CastNeeded = CK_NoOp; 2304 if (!AddrType.isAtLeastAsQualifiedAs(ValType)) { 2305 CastNeeded = CK_BitCast; 2306 Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers) 2307 << PointerArg->getType() << Context.getPointerType(AddrType) 2308 << AA_Passing << PointerArg->getSourceRange(); 2309 } 2310 2311 // Finally, do the cast and replace the argument with the corrected version. 2312 AddrType = Context.getPointerType(AddrType); 2313 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded); 2314 if (PointerArgRes.isInvalid()) 2315 return true; 2316 PointerArg = PointerArgRes.get(); 2317 2318 TheCall->setArg(IsLdrex ? 0 : 1, PointerArg); 2319 2320 // In general, we allow ints, floats and pointers to be loaded and stored. 2321 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 2322 !ValType->isBlockPointerType() && !ValType->isFloatingType()) { 2323 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr) 2324 << PointerArg->getType() << PointerArg->getSourceRange(); 2325 return true; 2326 } 2327 2328 // But ARM doesn't have instructions to deal with 128-bit versions. 2329 if (Context.getTypeSize(ValType) > MaxWidth) { 2330 assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate"); 2331 Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size) 2332 << PointerArg->getType() << PointerArg->getSourceRange(); 2333 return true; 2334 } 2335 2336 switch (ValType.getObjCLifetime()) { 2337 case Qualifiers::OCL_None: 2338 case Qualifiers::OCL_ExplicitNone: 2339 // okay 2340 break; 2341 2342 case Qualifiers::OCL_Weak: 2343 case Qualifiers::OCL_Strong: 2344 case Qualifiers::OCL_Autoreleasing: 2345 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 2346 << ValType << PointerArg->getSourceRange(); 2347 return true; 2348 } 2349 2350 if (IsLdrex) { 2351 TheCall->setType(ValType); 2352 return false; 2353 } 2354 2355 // Initialize the argument to be stored. 2356 ExprResult ValArg = TheCall->getArg(0); 2357 InitializedEntity Entity = InitializedEntity::InitializeParameter( 2358 Context, ValType, /*consume*/ false); 2359 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 2360 if (ValArg.isInvalid()) 2361 return true; 2362 TheCall->setArg(0, ValArg.get()); 2363 2364 // __builtin_arm_strex always returns an int. It's marked as such in the .def, 2365 // but the custom checker bypasses all default analysis. 2366 TheCall->setType(Context.IntTy); 2367 return false; 2368 } 2369 2370 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 2371 CallExpr *TheCall) { 2372 if (BuiltinID == ARM::BI__builtin_arm_ldrex || 2373 BuiltinID == ARM::BI__builtin_arm_ldaex || 2374 BuiltinID == ARM::BI__builtin_arm_strex || 2375 BuiltinID == ARM::BI__builtin_arm_stlex) { 2376 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64); 2377 } 2378 2379 if (BuiltinID == ARM::BI__builtin_arm_prefetch) { 2380 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2381 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1); 2382 } 2383 2384 if (BuiltinID == ARM::BI__builtin_arm_rsr64 || 2385 BuiltinID == ARM::BI__builtin_arm_wsr64) 2386 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false); 2387 2388 if (BuiltinID == ARM::BI__builtin_arm_rsr || 2389 BuiltinID == ARM::BI__builtin_arm_rsrp || 2390 BuiltinID == ARM::BI__builtin_arm_wsr || 2391 BuiltinID == ARM::BI__builtin_arm_wsrp) 2392 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2393 2394 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2395 return true; 2396 if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall)) 2397 return true; 2398 if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2399 return true; 2400 2401 // For intrinsics which take an immediate value as part of the instruction, 2402 // range check them here. 2403 // FIXME: VFP Intrinsics should error if VFP not present. 2404 switch (BuiltinID) { 2405 default: return false; 2406 case ARM::BI__builtin_arm_ssat: 2407 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32); 2408 case ARM::BI__builtin_arm_usat: 2409 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31); 2410 case ARM::BI__builtin_arm_ssat16: 2411 return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16); 2412 case ARM::BI__builtin_arm_usat16: 2413 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 2414 case ARM::BI__builtin_arm_vcvtr_f: 2415 case ARM::BI__builtin_arm_vcvtr_d: 2416 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 2417 case ARM::BI__builtin_arm_dmb: 2418 case ARM::BI__builtin_arm_dsb: 2419 case ARM::BI__builtin_arm_isb: 2420 case ARM::BI__builtin_arm_dbg: 2421 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15); 2422 case ARM::BI__builtin_arm_cdp: 2423 case ARM::BI__builtin_arm_cdp2: 2424 case ARM::BI__builtin_arm_mcr: 2425 case ARM::BI__builtin_arm_mcr2: 2426 case ARM::BI__builtin_arm_mrc: 2427 case ARM::BI__builtin_arm_mrc2: 2428 case ARM::BI__builtin_arm_mcrr: 2429 case ARM::BI__builtin_arm_mcrr2: 2430 case ARM::BI__builtin_arm_mrrc: 2431 case ARM::BI__builtin_arm_mrrc2: 2432 case ARM::BI__builtin_arm_ldc: 2433 case ARM::BI__builtin_arm_ldcl: 2434 case ARM::BI__builtin_arm_ldc2: 2435 case ARM::BI__builtin_arm_ldc2l: 2436 case ARM::BI__builtin_arm_stc: 2437 case ARM::BI__builtin_arm_stcl: 2438 case ARM::BI__builtin_arm_stc2: 2439 case ARM::BI__builtin_arm_stc2l: 2440 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) || 2441 CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), 2442 /*WantCDE*/ false); 2443 } 2444 } 2445 2446 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, 2447 unsigned BuiltinID, 2448 CallExpr *TheCall) { 2449 if (BuiltinID == AArch64::BI__builtin_arm_ldrex || 2450 BuiltinID == AArch64::BI__builtin_arm_ldaex || 2451 BuiltinID == AArch64::BI__builtin_arm_strex || 2452 BuiltinID == AArch64::BI__builtin_arm_stlex) { 2453 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128); 2454 } 2455 2456 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) { 2457 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 2458 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) || 2459 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) || 2460 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1); 2461 } 2462 2463 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 || 2464 BuiltinID == AArch64::BI__builtin_arm_wsr64) 2465 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2466 2467 // Memory Tagging Extensions (MTE) Intrinsics 2468 if (BuiltinID == AArch64::BI__builtin_arm_irg || 2469 BuiltinID == AArch64::BI__builtin_arm_addg || 2470 BuiltinID == AArch64::BI__builtin_arm_gmi || 2471 BuiltinID == AArch64::BI__builtin_arm_ldg || 2472 BuiltinID == AArch64::BI__builtin_arm_stg || 2473 BuiltinID == AArch64::BI__builtin_arm_subp) { 2474 return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall); 2475 } 2476 2477 if (BuiltinID == AArch64::BI__builtin_arm_rsr || 2478 BuiltinID == AArch64::BI__builtin_arm_rsrp || 2479 BuiltinID == AArch64::BI__builtin_arm_wsr || 2480 BuiltinID == AArch64::BI__builtin_arm_wsrp) 2481 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true); 2482 2483 // Only check the valid encoding range. Any constant in this range would be 2484 // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw 2485 // an exception for incorrect registers. This matches MSVC behavior. 2486 if (BuiltinID == AArch64::BI_ReadStatusReg || 2487 BuiltinID == AArch64::BI_WriteStatusReg) 2488 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff); 2489 2490 if (BuiltinID == AArch64::BI__getReg) 2491 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31); 2492 2493 if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall)) 2494 return true; 2495 2496 if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall)) 2497 return true; 2498 2499 // For intrinsics which take an immediate value as part of the instruction, 2500 // range check them here. 2501 unsigned i = 0, l = 0, u = 0; 2502 switch (BuiltinID) { 2503 default: return false; 2504 case AArch64::BI__builtin_arm_dmb: 2505 case AArch64::BI__builtin_arm_dsb: 2506 case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break; 2507 case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break; 2508 } 2509 2510 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l); 2511 } 2512 2513 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, 2514 CallExpr *TheCall) { 2515 assert((BuiltinID == BPF::BI__builtin_preserve_field_info || 2516 BuiltinID == BPF::BI__builtin_btf_type_id) && 2517 "unexpected ARM builtin"); 2518 2519 if (checkArgCount(*this, TheCall, 2)) 2520 return true; 2521 2522 Expr *Arg; 2523 if (BuiltinID == BPF::BI__builtin_btf_type_id) { 2524 // The second argument needs to be a constant int 2525 llvm::APSInt Value; 2526 Arg = TheCall->getArg(1); 2527 if (!Arg->isIntegerConstantExpr(Value, Context)) { 2528 Diag(Arg->getBeginLoc(), diag::err_btf_type_id_not_const) 2529 << 2 << Arg->getSourceRange(); 2530 return true; 2531 } 2532 2533 TheCall->setType(Context.UnsignedIntTy); 2534 return false; 2535 } 2536 2537 // The first argument needs to be a record field access. 2538 // If it is an array element access, we delay decision 2539 // to BPF backend to check whether the access is a 2540 // field access or not. 2541 Arg = TheCall->getArg(0); 2542 if (Arg->getType()->getAsPlaceholderType() || 2543 (Arg->IgnoreParens()->getObjectKind() != OK_BitField && 2544 !dyn_cast<MemberExpr>(Arg->IgnoreParens()) && 2545 !dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()))) { 2546 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_field) 2547 << 1 << Arg->getSourceRange(); 2548 return true; 2549 } 2550 2551 // The second argument needs to be a constant int 2552 Arg = TheCall->getArg(1); 2553 llvm::APSInt Value; 2554 if (!Arg->isIntegerConstantExpr(Value, Context)) { 2555 Diag(Arg->getBeginLoc(), diag::err_preserve_field_info_not_const) 2556 << 2 << Arg->getSourceRange(); 2557 return true; 2558 } 2559 2560 TheCall->setType(Context.UnsignedIntTy); 2561 return false; 2562 } 2563 2564 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2565 struct ArgInfo { 2566 uint8_t OpNum; 2567 bool IsSigned; 2568 uint8_t BitWidth; 2569 uint8_t Align; 2570 }; 2571 struct BuiltinInfo { 2572 unsigned BuiltinID; 2573 ArgInfo Infos[2]; 2574 }; 2575 2576 static BuiltinInfo Infos[] = { 2577 { Hexagon::BI__builtin_circ_ldd, {{ 3, true, 4, 3 }} }, 2578 { Hexagon::BI__builtin_circ_ldw, {{ 3, true, 4, 2 }} }, 2579 { Hexagon::BI__builtin_circ_ldh, {{ 3, true, 4, 1 }} }, 2580 { Hexagon::BI__builtin_circ_lduh, {{ 3, true, 4, 1 }} }, 2581 { Hexagon::BI__builtin_circ_ldb, {{ 3, true, 4, 0 }} }, 2582 { Hexagon::BI__builtin_circ_ldub, {{ 3, true, 4, 0 }} }, 2583 { Hexagon::BI__builtin_circ_std, {{ 3, true, 4, 3 }} }, 2584 { Hexagon::BI__builtin_circ_stw, {{ 3, true, 4, 2 }} }, 2585 { Hexagon::BI__builtin_circ_sth, {{ 3, true, 4, 1 }} }, 2586 { Hexagon::BI__builtin_circ_sthhi, {{ 3, true, 4, 1 }} }, 2587 { Hexagon::BI__builtin_circ_stb, {{ 3, true, 4, 0 }} }, 2588 2589 { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci, {{ 1, true, 4, 0 }} }, 2590 { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci, {{ 1, true, 4, 0 }} }, 2591 { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci, {{ 1, true, 4, 1 }} }, 2592 { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci, {{ 1, true, 4, 1 }} }, 2593 { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci, {{ 1, true, 4, 2 }} }, 2594 { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci, {{ 1, true, 4, 3 }} }, 2595 { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci, {{ 1, true, 4, 0 }} }, 2596 { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci, {{ 1, true, 4, 1 }} }, 2597 { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci, {{ 1, true, 4, 1 }} }, 2598 { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci, {{ 1, true, 4, 2 }} }, 2599 { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci, {{ 1, true, 4, 3 }} }, 2600 2601 { Hexagon::BI__builtin_HEXAGON_A2_combineii, {{ 1, true, 8, 0 }} }, 2602 { Hexagon::BI__builtin_HEXAGON_A2_tfrih, {{ 1, false, 16, 0 }} }, 2603 { Hexagon::BI__builtin_HEXAGON_A2_tfril, {{ 1, false, 16, 0 }} }, 2604 { Hexagon::BI__builtin_HEXAGON_A2_tfrpi, {{ 0, true, 8, 0 }} }, 2605 { Hexagon::BI__builtin_HEXAGON_A4_bitspliti, {{ 1, false, 5, 0 }} }, 2606 { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi, {{ 1, false, 8, 0 }} }, 2607 { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti, {{ 1, true, 8, 0 }} }, 2608 { Hexagon::BI__builtin_HEXAGON_A4_cround_ri, {{ 1, false, 5, 0 }} }, 2609 { Hexagon::BI__builtin_HEXAGON_A4_round_ri, {{ 1, false, 5, 0 }} }, 2610 { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat, {{ 1, false, 5, 0 }} }, 2611 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi, {{ 1, false, 8, 0 }} }, 2612 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti, {{ 1, true, 8, 0 }} }, 2613 { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui, {{ 1, false, 7, 0 }} }, 2614 { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi, {{ 1, true, 8, 0 }} }, 2615 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti, {{ 1, true, 8, 0 }} }, 2616 { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui, {{ 1, false, 7, 0 }} }, 2617 { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi, {{ 1, true, 8, 0 }} }, 2618 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti, {{ 1, true, 8, 0 }} }, 2619 { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui, {{ 1, false, 7, 0 }} }, 2620 { Hexagon::BI__builtin_HEXAGON_C2_bitsclri, {{ 1, false, 6, 0 }} }, 2621 { Hexagon::BI__builtin_HEXAGON_C2_muxii, {{ 2, true, 8, 0 }} }, 2622 { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri, {{ 1, false, 6, 0 }} }, 2623 { Hexagon::BI__builtin_HEXAGON_F2_dfclass, {{ 1, false, 5, 0 }} }, 2624 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n, {{ 0, false, 10, 0 }} }, 2625 { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p, {{ 0, false, 10, 0 }} }, 2626 { Hexagon::BI__builtin_HEXAGON_F2_sfclass, {{ 1, false, 5, 0 }} }, 2627 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n, {{ 0, false, 10, 0 }} }, 2628 { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p, {{ 0, false, 10, 0 }} }, 2629 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi, {{ 2, false, 6, 0 }} }, 2630 { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2, {{ 1, false, 6, 2 }} }, 2631 { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri, {{ 2, false, 3, 0 }} }, 2632 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc, {{ 2, false, 6, 0 }} }, 2633 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and, {{ 2, false, 6, 0 }} }, 2634 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p, {{ 1, false, 6, 0 }} }, 2635 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac, {{ 2, false, 6, 0 }} }, 2636 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or, {{ 2, false, 6, 0 }} }, 2637 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc, {{ 2, false, 6, 0 }} }, 2638 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc, {{ 2, false, 5, 0 }} }, 2639 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and, {{ 2, false, 5, 0 }} }, 2640 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r, {{ 1, false, 5, 0 }} }, 2641 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac, {{ 2, false, 5, 0 }} }, 2642 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or, {{ 2, false, 5, 0 }} }, 2643 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat, {{ 1, false, 5, 0 }} }, 2644 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc, {{ 2, false, 5, 0 }} }, 2645 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh, {{ 1, false, 4, 0 }} }, 2646 { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw, {{ 1, false, 5, 0 }} }, 2647 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc, {{ 2, false, 6, 0 }} }, 2648 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and, {{ 2, false, 6, 0 }} }, 2649 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p, {{ 1, false, 6, 0 }} }, 2650 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac, {{ 2, false, 6, 0 }} }, 2651 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or, {{ 2, false, 6, 0 }} }, 2652 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax, 2653 {{ 1, false, 6, 0 }} }, 2654 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd, {{ 1, false, 6, 0 }} }, 2655 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc, {{ 2, false, 5, 0 }} }, 2656 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and, {{ 2, false, 5, 0 }} }, 2657 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r, {{ 1, false, 5, 0 }} }, 2658 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac, {{ 2, false, 5, 0 }} }, 2659 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or, {{ 2, false, 5, 0 }} }, 2660 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax, 2661 {{ 1, false, 5, 0 }} }, 2662 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd, {{ 1, false, 5, 0 }} }, 2663 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5, 0 }} }, 2664 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh, {{ 1, false, 4, 0 }} }, 2665 { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw, {{ 1, false, 5, 0 }} }, 2666 { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i, {{ 1, false, 5, 0 }} }, 2667 { Hexagon::BI__builtin_HEXAGON_S2_extractu, {{ 1, false, 5, 0 }, 2668 { 2, false, 5, 0 }} }, 2669 { Hexagon::BI__builtin_HEXAGON_S2_extractup, {{ 1, false, 6, 0 }, 2670 { 2, false, 6, 0 }} }, 2671 { Hexagon::BI__builtin_HEXAGON_S2_insert, {{ 2, false, 5, 0 }, 2672 { 3, false, 5, 0 }} }, 2673 { Hexagon::BI__builtin_HEXAGON_S2_insertp, {{ 2, false, 6, 0 }, 2674 { 3, false, 6, 0 }} }, 2675 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc, {{ 2, false, 6, 0 }} }, 2676 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and, {{ 2, false, 6, 0 }} }, 2677 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p, {{ 1, false, 6, 0 }} }, 2678 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac, {{ 2, false, 6, 0 }} }, 2679 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or, {{ 2, false, 6, 0 }} }, 2680 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc, {{ 2, false, 6, 0 }} }, 2681 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc, {{ 2, false, 5, 0 }} }, 2682 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and, {{ 2, false, 5, 0 }} }, 2683 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r, {{ 1, false, 5, 0 }} }, 2684 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac, {{ 2, false, 5, 0 }} }, 2685 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or, {{ 2, false, 5, 0 }} }, 2686 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc, {{ 2, false, 5, 0 }} }, 2687 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh, {{ 1, false, 4, 0 }} }, 2688 { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw, {{ 1, false, 5, 0 }} }, 2689 { Hexagon::BI__builtin_HEXAGON_S2_setbit_i, {{ 1, false, 5, 0 }} }, 2690 { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax, 2691 {{ 2, false, 4, 0 }, 2692 { 3, false, 5, 0 }} }, 2693 { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax, 2694 {{ 2, false, 4, 0 }, 2695 { 3, false, 5, 0 }} }, 2696 { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax, 2697 {{ 2, false, 4, 0 }, 2698 { 3, false, 5, 0 }} }, 2699 { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax, 2700 {{ 2, false, 4, 0 }, 2701 { 3, false, 5, 0 }} }, 2702 { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i, {{ 1, false, 5, 0 }} }, 2703 { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i, {{ 1, false, 5, 0 }} }, 2704 { Hexagon::BI__builtin_HEXAGON_S2_valignib, {{ 2, false, 3, 0 }} }, 2705 { Hexagon::BI__builtin_HEXAGON_S2_vspliceib, {{ 2, false, 3, 0 }} }, 2706 { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri, {{ 2, false, 5, 0 }} }, 2707 { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri, {{ 2, false, 5, 0 }} }, 2708 { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri, {{ 2, false, 5, 0 }} }, 2709 { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri, {{ 2, false, 5, 0 }} }, 2710 { Hexagon::BI__builtin_HEXAGON_S4_clbaddi, {{ 1, true , 6, 0 }} }, 2711 { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi, {{ 1, true, 6, 0 }} }, 2712 { Hexagon::BI__builtin_HEXAGON_S4_extract, {{ 1, false, 5, 0 }, 2713 { 2, false, 5, 0 }} }, 2714 { Hexagon::BI__builtin_HEXAGON_S4_extractp, {{ 1, false, 6, 0 }, 2715 { 2, false, 6, 0 }} }, 2716 { Hexagon::BI__builtin_HEXAGON_S4_lsli, {{ 0, true, 6, 0 }} }, 2717 { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i, {{ 1, false, 5, 0 }} }, 2718 { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri, {{ 2, false, 5, 0 }} }, 2719 { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri, {{ 2, false, 5, 0 }} }, 2720 { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri, {{ 2, false, 5, 0 }} }, 2721 { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri, {{ 2, false, 5, 0 }} }, 2722 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc, {{ 3, false, 2, 0 }} }, 2723 { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate, {{ 2, false, 2, 0 }} }, 2724 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax, 2725 {{ 1, false, 4, 0 }} }, 2726 { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat, {{ 1, false, 4, 0 }} }, 2727 { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax, 2728 {{ 1, false, 4, 0 }} }, 2729 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p, {{ 1, false, 6, 0 }} }, 2730 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc, {{ 2, false, 6, 0 }} }, 2731 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and, {{ 2, false, 6, 0 }} }, 2732 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac, {{ 2, false, 6, 0 }} }, 2733 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or, {{ 2, false, 6, 0 }} }, 2734 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc, {{ 2, false, 6, 0 }} }, 2735 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r, {{ 1, false, 5, 0 }} }, 2736 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc, {{ 2, false, 5, 0 }} }, 2737 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and, {{ 2, false, 5, 0 }} }, 2738 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac, {{ 2, false, 5, 0 }} }, 2739 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or, {{ 2, false, 5, 0 }} }, 2740 { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc, {{ 2, false, 5, 0 }} }, 2741 { Hexagon::BI__builtin_HEXAGON_V6_valignbi, {{ 2, false, 3, 0 }} }, 2742 { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B, {{ 2, false, 3, 0 }} }, 2743 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi, {{ 2, false, 3, 0 }} }, 2744 { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3, 0 }} }, 2745 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi, {{ 2, false, 1, 0 }} }, 2746 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1, 0 }} }, 2747 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc, {{ 3, false, 1, 0 }} }, 2748 { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B, 2749 {{ 3, false, 1, 0 }} }, 2750 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi, {{ 2, false, 1, 0 }} }, 2751 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B, {{ 2, false, 1, 0 }} }, 2752 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc, {{ 3, false, 1, 0 }} }, 2753 { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B, 2754 {{ 3, false, 1, 0 }} }, 2755 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi, {{ 2, false, 1, 0 }} }, 2756 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B, {{ 2, false, 1, 0 }} }, 2757 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc, {{ 3, false, 1, 0 }} }, 2758 { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B, 2759 {{ 3, false, 1, 0 }} }, 2760 }; 2761 2762 // Use a dynamically initialized static to sort the table exactly once on 2763 // first run. 2764 static const bool SortOnce = 2765 (llvm::sort(Infos, 2766 [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) { 2767 return LHS.BuiltinID < RHS.BuiltinID; 2768 }), 2769 true); 2770 (void)SortOnce; 2771 2772 const BuiltinInfo *F = llvm::partition_point( 2773 Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; }); 2774 if (F == std::end(Infos) || F->BuiltinID != BuiltinID) 2775 return false; 2776 2777 bool Error = false; 2778 2779 for (const ArgInfo &A : F->Infos) { 2780 // Ignore empty ArgInfo elements. 2781 if (A.BitWidth == 0) 2782 continue; 2783 2784 int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0; 2785 int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1; 2786 if (!A.Align) { 2787 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max); 2788 } else { 2789 unsigned M = 1 << A.Align; 2790 Min *= M; 2791 Max *= M; 2792 Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) | 2793 SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M); 2794 } 2795 } 2796 return Error; 2797 } 2798 2799 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, 2800 CallExpr *TheCall) { 2801 return CheckHexagonBuiltinArgument(BuiltinID, TheCall); 2802 } 2803 2804 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI, 2805 unsigned BuiltinID, CallExpr *TheCall) { 2806 return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) || 2807 CheckMipsBuiltinArgument(BuiltinID, TheCall); 2808 } 2809 2810 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, 2811 CallExpr *TheCall) { 2812 2813 if (Mips::BI__builtin_mips_addu_qb <= BuiltinID && 2814 BuiltinID <= Mips::BI__builtin_mips_lwx) { 2815 if (!TI.hasFeature("dsp")) 2816 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp); 2817 } 2818 2819 if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID && 2820 BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) { 2821 if (!TI.hasFeature("dspr2")) 2822 return Diag(TheCall->getBeginLoc(), 2823 diag::err_mips_builtin_requires_dspr2); 2824 } 2825 2826 if (Mips::BI__builtin_msa_add_a_b <= BuiltinID && 2827 BuiltinID <= Mips::BI__builtin_msa_xori_b) { 2828 if (!TI.hasFeature("msa")) 2829 return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa); 2830 } 2831 2832 return false; 2833 } 2834 2835 // CheckMipsBuiltinArgument - Checks the constant value passed to the 2836 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The 2837 // ordering for DSP is unspecified. MSA is ordered by the data format used 2838 // by the underlying instruction i.e., df/m, df/n and then by size. 2839 // 2840 // FIXME: The size tests here should instead be tablegen'd along with the 2841 // definitions from include/clang/Basic/BuiltinsMips.def. 2842 // FIXME: GCC is strict on signedness for some of these intrinsics, we should 2843 // be too. 2844 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) { 2845 unsigned i = 0, l = 0, u = 0, m = 0; 2846 switch (BuiltinID) { 2847 default: return false; 2848 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break; 2849 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break; 2850 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break; 2851 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break; 2852 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break; 2853 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break; 2854 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break; 2855 // MSA intrinsics. Instructions (which the intrinsics maps to) which use the 2856 // df/m field. 2857 // These intrinsics take an unsigned 3 bit immediate. 2858 case Mips::BI__builtin_msa_bclri_b: 2859 case Mips::BI__builtin_msa_bnegi_b: 2860 case Mips::BI__builtin_msa_bseti_b: 2861 case Mips::BI__builtin_msa_sat_s_b: 2862 case Mips::BI__builtin_msa_sat_u_b: 2863 case Mips::BI__builtin_msa_slli_b: 2864 case Mips::BI__builtin_msa_srai_b: 2865 case Mips::BI__builtin_msa_srari_b: 2866 case Mips::BI__builtin_msa_srli_b: 2867 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break; 2868 case Mips::BI__builtin_msa_binsli_b: 2869 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break; 2870 // These intrinsics take an unsigned 4 bit immediate. 2871 case Mips::BI__builtin_msa_bclri_h: 2872 case Mips::BI__builtin_msa_bnegi_h: 2873 case Mips::BI__builtin_msa_bseti_h: 2874 case Mips::BI__builtin_msa_sat_s_h: 2875 case Mips::BI__builtin_msa_sat_u_h: 2876 case Mips::BI__builtin_msa_slli_h: 2877 case Mips::BI__builtin_msa_srai_h: 2878 case Mips::BI__builtin_msa_srari_h: 2879 case Mips::BI__builtin_msa_srli_h: 2880 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break; 2881 case Mips::BI__builtin_msa_binsli_h: 2882 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break; 2883 // These intrinsics take an unsigned 5 bit immediate. 2884 // The first block of intrinsics actually have an unsigned 5 bit field, 2885 // not a df/n field. 2886 case Mips::BI__builtin_msa_cfcmsa: 2887 case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break; 2888 case Mips::BI__builtin_msa_clei_u_b: 2889 case Mips::BI__builtin_msa_clei_u_h: 2890 case Mips::BI__builtin_msa_clei_u_w: 2891 case Mips::BI__builtin_msa_clei_u_d: 2892 case Mips::BI__builtin_msa_clti_u_b: 2893 case Mips::BI__builtin_msa_clti_u_h: 2894 case Mips::BI__builtin_msa_clti_u_w: 2895 case Mips::BI__builtin_msa_clti_u_d: 2896 case Mips::BI__builtin_msa_maxi_u_b: 2897 case Mips::BI__builtin_msa_maxi_u_h: 2898 case Mips::BI__builtin_msa_maxi_u_w: 2899 case Mips::BI__builtin_msa_maxi_u_d: 2900 case Mips::BI__builtin_msa_mini_u_b: 2901 case Mips::BI__builtin_msa_mini_u_h: 2902 case Mips::BI__builtin_msa_mini_u_w: 2903 case Mips::BI__builtin_msa_mini_u_d: 2904 case Mips::BI__builtin_msa_addvi_b: 2905 case Mips::BI__builtin_msa_addvi_h: 2906 case Mips::BI__builtin_msa_addvi_w: 2907 case Mips::BI__builtin_msa_addvi_d: 2908 case Mips::BI__builtin_msa_bclri_w: 2909 case Mips::BI__builtin_msa_bnegi_w: 2910 case Mips::BI__builtin_msa_bseti_w: 2911 case Mips::BI__builtin_msa_sat_s_w: 2912 case Mips::BI__builtin_msa_sat_u_w: 2913 case Mips::BI__builtin_msa_slli_w: 2914 case Mips::BI__builtin_msa_srai_w: 2915 case Mips::BI__builtin_msa_srari_w: 2916 case Mips::BI__builtin_msa_srli_w: 2917 case Mips::BI__builtin_msa_srlri_w: 2918 case Mips::BI__builtin_msa_subvi_b: 2919 case Mips::BI__builtin_msa_subvi_h: 2920 case Mips::BI__builtin_msa_subvi_w: 2921 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break; 2922 case Mips::BI__builtin_msa_binsli_w: 2923 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break; 2924 // These intrinsics take an unsigned 6 bit immediate. 2925 case Mips::BI__builtin_msa_bclri_d: 2926 case Mips::BI__builtin_msa_bnegi_d: 2927 case Mips::BI__builtin_msa_bseti_d: 2928 case Mips::BI__builtin_msa_sat_s_d: 2929 case Mips::BI__builtin_msa_sat_u_d: 2930 case Mips::BI__builtin_msa_slli_d: 2931 case Mips::BI__builtin_msa_srai_d: 2932 case Mips::BI__builtin_msa_srari_d: 2933 case Mips::BI__builtin_msa_srli_d: 2934 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break; 2935 case Mips::BI__builtin_msa_binsli_d: 2936 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break; 2937 // These intrinsics take a signed 5 bit immediate. 2938 case Mips::BI__builtin_msa_ceqi_b: 2939 case Mips::BI__builtin_msa_ceqi_h: 2940 case Mips::BI__builtin_msa_ceqi_w: 2941 case Mips::BI__builtin_msa_ceqi_d: 2942 case Mips::BI__builtin_msa_clti_s_b: 2943 case Mips::BI__builtin_msa_clti_s_h: 2944 case Mips::BI__builtin_msa_clti_s_w: 2945 case Mips::BI__builtin_msa_clti_s_d: 2946 case Mips::BI__builtin_msa_clei_s_b: 2947 case Mips::BI__builtin_msa_clei_s_h: 2948 case Mips::BI__builtin_msa_clei_s_w: 2949 case Mips::BI__builtin_msa_clei_s_d: 2950 case Mips::BI__builtin_msa_maxi_s_b: 2951 case Mips::BI__builtin_msa_maxi_s_h: 2952 case Mips::BI__builtin_msa_maxi_s_w: 2953 case Mips::BI__builtin_msa_maxi_s_d: 2954 case Mips::BI__builtin_msa_mini_s_b: 2955 case Mips::BI__builtin_msa_mini_s_h: 2956 case Mips::BI__builtin_msa_mini_s_w: 2957 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break; 2958 // These intrinsics take an unsigned 8 bit immediate. 2959 case Mips::BI__builtin_msa_andi_b: 2960 case Mips::BI__builtin_msa_nori_b: 2961 case Mips::BI__builtin_msa_ori_b: 2962 case Mips::BI__builtin_msa_shf_b: 2963 case Mips::BI__builtin_msa_shf_h: 2964 case Mips::BI__builtin_msa_shf_w: 2965 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break; 2966 case Mips::BI__builtin_msa_bseli_b: 2967 case Mips::BI__builtin_msa_bmnzi_b: 2968 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break; 2969 // df/n format 2970 // These intrinsics take an unsigned 4 bit immediate. 2971 case Mips::BI__builtin_msa_copy_s_b: 2972 case Mips::BI__builtin_msa_copy_u_b: 2973 case Mips::BI__builtin_msa_insve_b: 2974 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break; 2975 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break; 2976 // These intrinsics take an unsigned 3 bit immediate. 2977 case Mips::BI__builtin_msa_copy_s_h: 2978 case Mips::BI__builtin_msa_copy_u_h: 2979 case Mips::BI__builtin_msa_insve_h: 2980 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break; 2981 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break; 2982 // These intrinsics take an unsigned 2 bit immediate. 2983 case Mips::BI__builtin_msa_copy_s_w: 2984 case Mips::BI__builtin_msa_copy_u_w: 2985 case Mips::BI__builtin_msa_insve_w: 2986 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break; 2987 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break; 2988 // These intrinsics take an unsigned 1 bit immediate. 2989 case Mips::BI__builtin_msa_copy_s_d: 2990 case Mips::BI__builtin_msa_copy_u_d: 2991 case Mips::BI__builtin_msa_insve_d: 2992 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break; 2993 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break; 2994 // Memory offsets and immediate loads. 2995 // These intrinsics take a signed 10 bit immediate. 2996 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break; 2997 case Mips::BI__builtin_msa_ldi_h: 2998 case Mips::BI__builtin_msa_ldi_w: 2999 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break; 3000 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break; 3001 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break; 3002 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break; 3003 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break; 3004 case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break; 3005 case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break; 3006 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break; 3007 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break; 3008 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break; 3009 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break; 3010 case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break; 3011 case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break; 3012 } 3013 3014 if (!m) 3015 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3016 3017 return SemaBuiltinConstantArgRange(TheCall, i, l, u) || 3018 SemaBuiltinConstantArgMultiple(TheCall, i, m); 3019 } 3020 3021 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3022 CallExpr *TheCall) { 3023 unsigned i = 0, l = 0, u = 0; 3024 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde || 3025 BuiltinID == PPC::BI__builtin_divdeu || 3026 BuiltinID == PPC::BI__builtin_bpermd; 3027 bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64; 3028 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe || 3029 BuiltinID == PPC::BI__builtin_divweu || 3030 BuiltinID == PPC::BI__builtin_divde || 3031 BuiltinID == PPC::BI__builtin_divdeu; 3032 3033 if (Is64BitBltin && !IsTarget64Bit) 3034 return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt) 3035 << TheCall->getSourceRange(); 3036 3037 if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) || 3038 (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd"))) 3039 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3040 << TheCall->getSourceRange(); 3041 3042 auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool { 3043 if (!TI.hasFeature("vsx")) 3044 return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7) 3045 << TheCall->getSourceRange(); 3046 return false; 3047 }; 3048 3049 switch (BuiltinID) { 3050 default: return false; 3051 case PPC::BI__builtin_altivec_crypto_vshasigmaw: 3052 case PPC::BI__builtin_altivec_crypto_vshasigmad: 3053 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) || 3054 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3055 case PPC::BI__builtin_altivec_dss: 3056 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3); 3057 case PPC::BI__builtin_tbegin: 3058 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break; 3059 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break; 3060 case PPC::BI__builtin_tabortwc: 3061 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break; 3062 case PPC::BI__builtin_tabortwci: 3063 case PPC::BI__builtin_tabortdci: 3064 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) || 3065 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31); 3066 case PPC::BI__builtin_altivec_dst: 3067 case PPC::BI__builtin_altivec_dstt: 3068 case PPC::BI__builtin_altivec_dstst: 3069 case PPC::BI__builtin_altivec_dststt: 3070 return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3); 3071 case PPC::BI__builtin_vsx_xxpermdi: 3072 case PPC::BI__builtin_vsx_xxsldwi: 3073 return SemaBuiltinVSX(TheCall); 3074 case PPC::BI__builtin_unpack_vector_int128: 3075 return SemaVSXCheck(TheCall) || 3076 SemaBuiltinConstantArgRange(TheCall, 1, 0, 1); 3077 case PPC::BI__builtin_pack_vector_int128: 3078 return SemaVSXCheck(TheCall); 3079 } 3080 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3081 } 3082 3083 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, 3084 CallExpr *TheCall) { 3085 // position of memory order and scope arguments in the builtin 3086 unsigned OrderIndex, ScopeIndex; 3087 switch (BuiltinID) { 3088 case AMDGPU::BI__builtin_amdgcn_atomic_inc32: 3089 case AMDGPU::BI__builtin_amdgcn_atomic_inc64: 3090 case AMDGPU::BI__builtin_amdgcn_atomic_dec32: 3091 case AMDGPU::BI__builtin_amdgcn_atomic_dec64: 3092 OrderIndex = 2; 3093 ScopeIndex = 3; 3094 break; 3095 case AMDGPU::BI__builtin_amdgcn_fence: 3096 OrderIndex = 0; 3097 ScopeIndex = 1; 3098 break; 3099 default: 3100 return false; 3101 } 3102 3103 ExprResult Arg = TheCall->getArg(OrderIndex); 3104 auto ArgExpr = Arg.get(); 3105 Expr::EvalResult ArgResult; 3106 3107 if (!ArgExpr->EvaluateAsInt(ArgResult, Context)) 3108 return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int) 3109 << ArgExpr->getType(); 3110 int ord = ArgResult.Val.getInt().getZExtValue(); 3111 3112 // Check valididty of memory ordering as per C11 / C++11's memody model. 3113 switch (static_cast<llvm::AtomicOrderingCABI>(ord)) { 3114 case llvm::AtomicOrderingCABI::acquire: 3115 case llvm::AtomicOrderingCABI::release: 3116 case llvm::AtomicOrderingCABI::acq_rel: 3117 case llvm::AtomicOrderingCABI::seq_cst: 3118 break; 3119 default: { 3120 return Diag(ArgExpr->getBeginLoc(), 3121 diag::warn_atomic_op_has_invalid_memory_order) 3122 << ArgExpr->getSourceRange(); 3123 } 3124 } 3125 3126 Arg = TheCall->getArg(ScopeIndex); 3127 ArgExpr = Arg.get(); 3128 Expr::EvalResult ArgResult1; 3129 // Check that sync scope is a constant literal 3130 if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Expr::EvaluateForCodeGen, 3131 Context)) 3132 return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal) 3133 << ArgExpr->getType(); 3134 3135 return false; 3136 } 3137 3138 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, 3139 CallExpr *TheCall) { 3140 if (BuiltinID == SystemZ::BI__builtin_tabort) { 3141 Expr *Arg = TheCall->getArg(0); 3142 llvm::APSInt AbortCode(32); 3143 if (Arg->isIntegerConstantExpr(AbortCode, Context) && 3144 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256) 3145 return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code) 3146 << Arg->getSourceRange(); 3147 } 3148 3149 // For intrinsics which take an immediate value as part of the instruction, 3150 // range check them here. 3151 unsigned i = 0, l = 0, u = 0; 3152 switch (BuiltinID) { 3153 default: return false; 3154 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break; 3155 case SystemZ::BI__builtin_s390_verimb: 3156 case SystemZ::BI__builtin_s390_verimh: 3157 case SystemZ::BI__builtin_s390_verimf: 3158 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break; 3159 case SystemZ::BI__builtin_s390_vfaeb: 3160 case SystemZ::BI__builtin_s390_vfaeh: 3161 case SystemZ::BI__builtin_s390_vfaef: 3162 case SystemZ::BI__builtin_s390_vfaebs: 3163 case SystemZ::BI__builtin_s390_vfaehs: 3164 case SystemZ::BI__builtin_s390_vfaefs: 3165 case SystemZ::BI__builtin_s390_vfaezb: 3166 case SystemZ::BI__builtin_s390_vfaezh: 3167 case SystemZ::BI__builtin_s390_vfaezf: 3168 case SystemZ::BI__builtin_s390_vfaezbs: 3169 case SystemZ::BI__builtin_s390_vfaezhs: 3170 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break; 3171 case SystemZ::BI__builtin_s390_vfisb: 3172 case SystemZ::BI__builtin_s390_vfidb: 3173 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) || 3174 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15); 3175 case SystemZ::BI__builtin_s390_vftcisb: 3176 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break; 3177 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break; 3178 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break; 3179 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break; 3180 case SystemZ::BI__builtin_s390_vstrcb: 3181 case SystemZ::BI__builtin_s390_vstrch: 3182 case SystemZ::BI__builtin_s390_vstrcf: 3183 case SystemZ::BI__builtin_s390_vstrczb: 3184 case SystemZ::BI__builtin_s390_vstrczh: 3185 case SystemZ::BI__builtin_s390_vstrczf: 3186 case SystemZ::BI__builtin_s390_vstrcbs: 3187 case SystemZ::BI__builtin_s390_vstrchs: 3188 case SystemZ::BI__builtin_s390_vstrcfs: 3189 case SystemZ::BI__builtin_s390_vstrczbs: 3190 case SystemZ::BI__builtin_s390_vstrczhs: 3191 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break; 3192 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break; 3193 case SystemZ::BI__builtin_s390_vfminsb: 3194 case SystemZ::BI__builtin_s390_vfmaxsb: 3195 case SystemZ::BI__builtin_s390_vfmindb: 3196 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break; 3197 case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break; 3198 case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break; 3199 } 3200 return SemaBuiltinConstantArgRange(TheCall, i, l, u); 3201 } 3202 3203 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *). 3204 /// This checks that the target supports __builtin_cpu_supports and 3205 /// that the string argument is constant and valid. 3206 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI, 3207 CallExpr *TheCall) { 3208 Expr *Arg = TheCall->getArg(0); 3209 3210 // Check if the argument is a string literal. 3211 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3212 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3213 << Arg->getSourceRange(); 3214 3215 // Check the contents of the string. 3216 StringRef Feature = 3217 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3218 if (!TI.validateCpuSupports(Feature)) 3219 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports) 3220 << Arg->getSourceRange(); 3221 return false; 3222 } 3223 3224 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *). 3225 /// This checks that the target supports __builtin_cpu_is and 3226 /// that the string argument is constant and valid. 3227 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) { 3228 Expr *Arg = TheCall->getArg(0); 3229 3230 // Check if the argument is a string literal. 3231 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 3232 return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 3233 << Arg->getSourceRange(); 3234 3235 // Check the contents of the string. 3236 StringRef Feature = 3237 cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 3238 if (!TI.validateCpuIs(Feature)) 3239 return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is) 3240 << Arg->getSourceRange(); 3241 return false; 3242 } 3243 3244 // Check if the rounding mode is legal. 3245 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) { 3246 // Indicates if this instruction has rounding control or just SAE. 3247 bool HasRC = false; 3248 3249 unsigned ArgNum = 0; 3250 switch (BuiltinID) { 3251 default: 3252 return false; 3253 case X86::BI__builtin_ia32_vcvttsd2si32: 3254 case X86::BI__builtin_ia32_vcvttsd2si64: 3255 case X86::BI__builtin_ia32_vcvttsd2usi32: 3256 case X86::BI__builtin_ia32_vcvttsd2usi64: 3257 case X86::BI__builtin_ia32_vcvttss2si32: 3258 case X86::BI__builtin_ia32_vcvttss2si64: 3259 case X86::BI__builtin_ia32_vcvttss2usi32: 3260 case X86::BI__builtin_ia32_vcvttss2usi64: 3261 ArgNum = 1; 3262 break; 3263 case X86::BI__builtin_ia32_maxpd512: 3264 case X86::BI__builtin_ia32_maxps512: 3265 case X86::BI__builtin_ia32_minpd512: 3266 case X86::BI__builtin_ia32_minps512: 3267 ArgNum = 2; 3268 break; 3269 case X86::BI__builtin_ia32_cvtps2pd512_mask: 3270 case X86::BI__builtin_ia32_cvttpd2dq512_mask: 3271 case X86::BI__builtin_ia32_cvttpd2qq512_mask: 3272 case X86::BI__builtin_ia32_cvttpd2udq512_mask: 3273 case X86::BI__builtin_ia32_cvttpd2uqq512_mask: 3274 case X86::BI__builtin_ia32_cvttps2dq512_mask: 3275 case X86::BI__builtin_ia32_cvttps2qq512_mask: 3276 case X86::BI__builtin_ia32_cvttps2udq512_mask: 3277 case X86::BI__builtin_ia32_cvttps2uqq512_mask: 3278 case X86::BI__builtin_ia32_exp2pd_mask: 3279 case X86::BI__builtin_ia32_exp2ps_mask: 3280 case X86::BI__builtin_ia32_getexppd512_mask: 3281 case X86::BI__builtin_ia32_getexpps512_mask: 3282 case X86::BI__builtin_ia32_rcp28pd_mask: 3283 case X86::BI__builtin_ia32_rcp28ps_mask: 3284 case X86::BI__builtin_ia32_rsqrt28pd_mask: 3285 case X86::BI__builtin_ia32_rsqrt28ps_mask: 3286 case X86::BI__builtin_ia32_vcomisd: 3287 case X86::BI__builtin_ia32_vcomiss: 3288 case X86::BI__builtin_ia32_vcvtph2ps512_mask: 3289 ArgNum = 3; 3290 break; 3291 case X86::BI__builtin_ia32_cmppd512_mask: 3292 case X86::BI__builtin_ia32_cmpps512_mask: 3293 case X86::BI__builtin_ia32_cmpsd_mask: 3294 case X86::BI__builtin_ia32_cmpss_mask: 3295 case X86::BI__builtin_ia32_cvtss2sd_round_mask: 3296 case X86::BI__builtin_ia32_getexpsd128_round_mask: 3297 case X86::BI__builtin_ia32_getexpss128_round_mask: 3298 case X86::BI__builtin_ia32_getmantpd512_mask: 3299 case X86::BI__builtin_ia32_getmantps512_mask: 3300 case X86::BI__builtin_ia32_maxsd_round_mask: 3301 case X86::BI__builtin_ia32_maxss_round_mask: 3302 case X86::BI__builtin_ia32_minsd_round_mask: 3303 case X86::BI__builtin_ia32_minss_round_mask: 3304 case X86::BI__builtin_ia32_rcp28sd_round_mask: 3305 case X86::BI__builtin_ia32_rcp28ss_round_mask: 3306 case X86::BI__builtin_ia32_reducepd512_mask: 3307 case X86::BI__builtin_ia32_reduceps512_mask: 3308 case X86::BI__builtin_ia32_rndscalepd_mask: 3309 case X86::BI__builtin_ia32_rndscaleps_mask: 3310 case X86::BI__builtin_ia32_rsqrt28sd_round_mask: 3311 case X86::BI__builtin_ia32_rsqrt28ss_round_mask: 3312 ArgNum = 4; 3313 break; 3314 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3315 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3316 case X86::BI__builtin_ia32_fixupimmps512_mask: 3317 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3318 case X86::BI__builtin_ia32_fixupimmsd_mask: 3319 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3320 case X86::BI__builtin_ia32_fixupimmss_mask: 3321 case X86::BI__builtin_ia32_fixupimmss_maskz: 3322 case X86::BI__builtin_ia32_getmantsd_round_mask: 3323 case X86::BI__builtin_ia32_getmantss_round_mask: 3324 case X86::BI__builtin_ia32_rangepd512_mask: 3325 case X86::BI__builtin_ia32_rangeps512_mask: 3326 case X86::BI__builtin_ia32_rangesd128_round_mask: 3327 case X86::BI__builtin_ia32_rangess128_round_mask: 3328 case X86::BI__builtin_ia32_reducesd_mask: 3329 case X86::BI__builtin_ia32_reducess_mask: 3330 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3331 case X86::BI__builtin_ia32_rndscaless_round_mask: 3332 ArgNum = 5; 3333 break; 3334 case X86::BI__builtin_ia32_vcvtsd2si64: 3335 case X86::BI__builtin_ia32_vcvtsd2si32: 3336 case X86::BI__builtin_ia32_vcvtsd2usi32: 3337 case X86::BI__builtin_ia32_vcvtsd2usi64: 3338 case X86::BI__builtin_ia32_vcvtss2si32: 3339 case X86::BI__builtin_ia32_vcvtss2si64: 3340 case X86::BI__builtin_ia32_vcvtss2usi32: 3341 case X86::BI__builtin_ia32_vcvtss2usi64: 3342 case X86::BI__builtin_ia32_sqrtpd512: 3343 case X86::BI__builtin_ia32_sqrtps512: 3344 ArgNum = 1; 3345 HasRC = true; 3346 break; 3347 case X86::BI__builtin_ia32_addpd512: 3348 case X86::BI__builtin_ia32_addps512: 3349 case X86::BI__builtin_ia32_divpd512: 3350 case X86::BI__builtin_ia32_divps512: 3351 case X86::BI__builtin_ia32_mulpd512: 3352 case X86::BI__builtin_ia32_mulps512: 3353 case X86::BI__builtin_ia32_subpd512: 3354 case X86::BI__builtin_ia32_subps512: 3355 case X86::BI__builtin_ia32_cvtsi2sd64: 3356 case X86::BI__builtin_ia32_cvtsi2ss32: 3357 case X86::BI__builtin_ia32_cvtsi2ss64: 3358 case X86::BI__builtin_ia32_cvtusi2sd64: 3359 case X86::BI__builtin_ia32_cvtusi2ss32: 3360 case X86::BI__builtin_ia32_cvtusi2ss64: 3361 ArgNum = 2; 3362 HasRC = true; 3363 break; 3364 case X86::BI__builtin_ia32_cvtdq2ps512_mask: 3365 case X86::BI__builtin_ia32_cvtudq2ps512_mask: 3366 case X86::BI__builtin_ia32_cvtpd2ps512_mask: 3367 case X86::BI__builtin_ia32_cvtpd2dq512_mask: 3368 case X86::BI__builtin_ia32_cvtpd2qq512_mask: 3369 case X86::BI__builtin_ia32_cvtpd2udq512_mask: 3370 case X86::BI__builtin_ia32_cvtpd2uqq512_mask: 3371 case X86::BI__builtin_ia32_cvtps2dq512_mask: 3372 case X86::BI__builtin_ia32_cvtps2qq512_mask: 3373 case X86::BI__builtin_ia32_cvtps2udq512_mask: 3374 case X86::BI__builtin_ia32_cvtps2uqq512_mask: 3375 case X86::BI__builtin_ia32_cvtqq2pd512_mask: 3376 case X86::BI__builtin_ia32_cvtqq2ps512_mask: 3377 case X86::BI__builtin_ia32_cvtuqq2pd512_mask: 3378 case X86::BI__builtin_ia32_cvtuqq2ps512_mask: 3379 ArgNum = 3; 3380 HasRC = true; 3381 break; 3382 case X86::BI__builtin_ia32_addss_round_mask: 3383 case X86::BI__builtin_ia32_addsd_round_mask: 3384 case X86::BI__builtin_ia32_divss_round_mask: 3385 case X86::BI__builtin_ia32_divsd_round_mask: 3386 case X86::BI__builtin_ia32_mulss_round_mask: 3387 case X86::BI__builtin_ia32_mulsd_round_mask: 3388 case X86::BI__builtin_ia32_subss_round_mask: 3389 case X86::BI__builtin_ia32_subsd_round_mask: 3390 case X86::BI__builtin_ia32_scalefpd512_mask: 3391 case X86::BI__builtin_ia32_scalefps512_mask: 3392 case X86::BI__builtin_ia32_scalefsd_round_mask: 3393 case X86::BI__builtin_ia32_scalefss_round_mask: 3394 case X86::BI__builtin_ia32_cvtsd2ss_round_mask: 3395 case X86::BI__builtin_ia32_sqrtsd_round_mask: 3396 case X86::BI__builtin_ia32_sqrtss_round_mask: 3397 case X86::BI__builtin_ia32_vfmaddsd3_mask: 3398 case X86::BI__builtin_ia32_vfmaddsd3_maskz: 3399 case X86::BI__builtin_ia32_vfmaddsd3_mask3: 3400 case X86::BI__builtin_ia32_vfmaddss3_mask: 3401 case X86::BI__builtin_ia32_vfmaddss3_maskz: 3402 case X86::BI__builtin_ia32_vfmaddss3_mask3: 3403 case X86::BI__builtin_ia32_vfmaddpd512_mask: 3404 case X86::BI__builtin_ia32_vfmaddpd512_maskz: 3405 case X86::BI__builtin_ia32_vfmaddpd512_mask3: 3406 case X86::BI__builtin_ia32_vfmsubpd512_mask3: 3407 case X86::BI__builtin_ia32_vfmaddps512_mask: 3408 case X86::BI__builtin_ia32_vfmaddps512_maskz: 3409 case X86::BI__builtin_ia32_vfmaddps512_mask3: 3410 case X86::BI__builtin_ia32_vfmsubps512_mask3: 3411 case X86::BI__builtin_ia32_vfmaddsubpd512_mask: 3412 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz: 3413 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3: 3414 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3: 3415 case X86::BI__builtin_ia32_vfmaddsubps512_mask: 3416 case X86::BI__builtin_ia32_vfmaddsubps512_maskz: 3417 case X86::BI__builtin_ia32_vfmaddsubps512_mask3: 3418 case X86::BI__builtin_ia32_vfmsubaddps512_mask3: 3419 ArgNum = 4; 3420 HasRC = true; 3421 break; 3422 } 3423 3424 llvm::APSInt Result; 3425 3426 // We can't check the value of a dependent argument. 3427 Expr *Arg = TheCall->getArg(ArgNum); 3428 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3429 return false; 3430 3431 // Check constant-ness first. 3432 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3433 return true; 3434 3435 // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit 3436 // is set. If the intrinsic has rounding control(bits 1:0), make sure its only 3437 // combined with ROUND_NO_EXC. If the intrinsic does not have rounding 3438 // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together. 3439 if (Result == 4/*ROUND_CUR_DIRECTION*/ || 3440 Result == 8/*ROUND_NO_EXC*/ || 3441 (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) || 3442 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11)) 3443 return false; 3444 3445 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding) 3446 << Arg->getSourceRange(); 3447 } 3448 3449 // Check if the gather/scatter scale is legal. 3450 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, 3451 CallExpr *TheCall) { 3452 unsigned ArgNum = 0; 3453 switch (BuiltinID) { 3454 default: 3455 return false; 3456 case X86::BI__builtin_ia32_gatherpfdpd: 3457 case X86::BI__builtin_ia32_gatherpfdps: 3458 case X86::BI__builtin_ia32_gatherpfqpd: 3459 case X86::BI__builtin_ia32_gatherpfqps: 3460 case X86::BI__builtin_ia32_scatterpfdpd: 3461 case X86::BI__builtin_ia32_scatterpfdps: 3462 case X86::BI__builtin_ia32_scatterpfqpd: 3463 case X86::BI__builtin_ia32_scatterpfqps: 3464 ArgNum = 3; 3465 break; 3466 case X86::BI__builtin_ia32_gatherd_pd: 3467 case X86::BI__builtin_ia32_gatherd_pd256: 3468 case X86::BI__builtin_ia32_gatherq_pd: 3469 case X86::BI__builtin_ia32_gatherq_pd256: 3470 case X86::BI__builtin_ia32_gatherd_ps: 3471 case X86::BI__builtin_ia32_gatherd_ps256: 3472 case X86::BI__builtin_ia32_gatherq_ps: 3473 case X86::BI__builtin_ia32_gatherq_ps256: 3474 case X86::BI__builtin_ia32_gatherd_q: 3475 case X86::BI__builtin_ia32_gatherd_q256: 3476 case X86::BI__builtin_ia32_gatherq_q: 3477 case X86::BI__builtin_ia32_gatherq_q256: 3478 case X86::BI__builtin_ia32_gatherd_d: 3479 case X86::BI__builtin_ia32_gatherd_d256: 3480 case X86::BI__builtin_ia32_gatherq_d: 3481 case X86::BI__builtin_ia32_gatherq_d256: 3482 case X86::BI__builtin_ia32_gather3div2df: 3483 case X86::BI__builtin_ia32_gather3div2di: 3484 case X86::BI__builtin_ia32_gather3div4df: 3485 case X86::BI__builtin_ia32_gather3div4di: 3486 case X86::BI__builtin_ia32_gather3div4sf: 3487 case X86::BI__builtin_ia32_gather3div4si: 3488 case X86::BI__builtin_ia32_gather3div8sf: 3489 case X86::BI__builtin_ia32_gather3div8si: 3490 case X86::BI__builtin_ia32_gather3siv2df: 3491 case X86::BI__builtin_ia32_gather3siv2di: 3492 case X86::BI__builtin_ia32_gather3siv4df: 3493 case X86::BI__builtin_ia32_gather3siv4di: 3494 case X86::BI__builtin_ia32_gather3siv4sf: 3495 case X86::BI__builtin_ia32_gather3siv4si: 3496 case X86::BI__builtin_ia32_gather3siv8sf: 3497 case X86::BI__builtin_ia32_gather3siv8si: 3498 case X86::BI__builtin_ia32_gathersiv8df: 3499 case X86::BI__builtin_ia32_gathersiv16sf: 3500 case X86::BI__builtin_ia32_gatherdiv8df: 3501 case X86::BI__builtin_ia32_gatherdiv16sf: 3502 case X86::BI__builtin_ia32_gathersiv8di: 3503 case X86::BI__builtin_ia32_gathersiv16si: 3504 case X86::BI__builtin_ia32_gatherdiv8di: 3505 case X86::BI__builtin_ia32_gatherdiv16si: 3506 case X86::BI__builtin_ia32_scatterdiv2df: 3507 case X86::BI__builtin_ia32_scatterdiv2di: 3508 case X86::BI__builtin_ia32_scatterdiv4df: 3509 case X86::BI__builtin_ia32_scatterdiv4di: 3510 case X86::BI__builtin_ia32_scatterdiv4sf: 3511 case X86::BI__builtin_ia32_scatterdiv4si: 3512 case X86::BI__builtin_ia32_scatterdiv8sf: 3513 case X86::BI__builtin_ia32_scatterdiv8si: 3514 case X86::BI__builtin_ia32_scattersiv2df: 3515 case X86::BI__builtin_ia32_scattersiv2di: 3516 case X86::BI__builtin_ia32_scattersiv4df: 3517 case X86::BI__builtin_ia32_scattersiv4di: 3518 case X86::BI__builtin_ia32_scattersiv4sf: 3519 case X86::BI__builtin_ia32_scattersiv4si: 3520 case X86::BI__builtin_ia32_scattersiv8sf: 3521 case X86::BI__builtin_ia32_scattersiv8si: 3522 case X86::BI__builtin_ia32_scattersiv8df: 3523 case X86::BI__builtin_ia32_scattersiv16sf: 3524 case X86::BI__builtin_ia32_scatterdiv8df: 3525 case X86::BI__builtin_ia32_scatterdiv16sf: 3526 case X86::BI__builtin_ia32_scattersiv8di: 3527 case X86::BI__builtin_ia32_scattersiv16si: 3528 case X86::BI__builtin_ia32_scatterdiv8di: 3529 case X86::BI__builtin_ia32_scatterdiv16si: 3530 ArgNum = 4; 3531 break; 3532 } 3533 3534 llvm::APSInt Result; 3535 3536 // We can't check the value of a dependent argument. 3537 Expr *Arg = TheCall->getArg(ArgNum); 3538 if (Arg->isTypeDependent() || Arg->isValueDependent()) 3539 return false; 3540 3541 // Check constant-ness first. 3542 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 3543 return true; 3544 3545 if (Result == 1 || Result == 2 || Result == 4 || Result == 8) 3546 return false; 3547 3548 return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale) 3549 << Arg->getSourceRange(); 3550 } 3551 3552 static bool isX86_32Builtin(unsigned BuiltinID) { 3553 // These builtins only work on x86-32 targets. 3554 switch (BuiltinID) { 3555 case X86::BI__builtin_ia32_readeflags_u32: 3556 case X86::BI__builtin_ia32_writeeflags_u32: 3557 return true; 3558 } 3559 3560 return false; 3561 } 3562 3563 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, 3564 CallExpr *TheCall) { 3565 if (BuiltinID == X86::BI__builtin_cpu_supports) 3566 return SemaBuiltinCpuSupports(*this, TI, TheCall); 3567 3568 if (BuiltinID == X86::BI__builtin_cpu_is) 3569 return SemaBuiltinCpuIs(*this, TI, TheCall); 3570 3571 // Check for 32-bit only builtins on a 64-bit target. 3572 const llvm::Triple &TT = TI.getTriple(); 3573 if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID)) 3574 return Diag(TheCall->getCallee()->getBeginLoc(), 3575 diag::err_32_bit_builtin_64_bit_tgt); 3576 3577 // If the intrinsic has rounding or SAE make sure its valid. 3578 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall)) 3579 return true; 3580 3581 // If the intrinsic has a gather/scatter scale immediate make sure its valid. 3582 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall)) 3583 return true; 3584 3585 // For intrinsics which take an immediate value as part of the instruction, 3586 // range check them here. 3587 int i = 0, l = 0, u = 0; 3588 switch (BuiltinID) { 3589 default: 3590 return false; 3591 case X86::BI__builtin_ia32_vec_ext_v2si: 3592 case X86::BI__builtin_ia32_vec_ext_v2di: 3593 case X86::BI__builtin_ia32_vextractf128_pd256: 3594 case X86::BI__builtin_ia32_vextractf128_ps256: 3595 case X86::BI__builtin_ia32_vextractf128_si256: 3596 case X86::BI__builtin_ia32_extract128i256: 3597 case X86::BI__builtin_ia32_extractf64x4_mask: 3598 case X86::BI__builtin_ia32_extracti64x4_mask: 3599 case X86::BI__builtin_ia32_extractf32x8_mask: 3600 case X86::BI__builtin_ia32_extracti32x8_mask: 3601 case X86::BI__builtin_ia32_extractf64x2_256_mask: 3602 case X86::BI__builtin_ia32_extracti64x2_256_mask: 3603 case X86::BI__builtin_ia32_extractf32x4_256_mask: 3604 case X86::BI__builtin_ia32_extracti32x4_256_mask: 3605 i = 1; l = 0; u = 1; 3606 break; 3607 case X86::BI__builtin_ia32_vec_set_v2di: 3608 case X86::BI__builtin_ia32_vinsertf128_pd256: 3609 case X86::BI__builtin_ia32_vinsertf128_ps256: 3610 case X86::BI__builtin_ia32_vinsertf128_si256: 3611 case X86::BI__builtin_ia32_insert128i256: 3612 case X86::BI__builtin_ia32_insertf32x8: 3613 case X86::BI__builtin_ia32_inserti32x8: 3614 case X86::BI__builtin_ia32_insertf64x4: 3615 case X86::BI__builtin_ia32_inserti64x4: 3616 case X86::BI__builtin_ia32_insertf64x2_256: 3617 case X86::BI__builtin_ia32_inserti64x2_256: 3618 case X86::BI__builtin_ia32_insertf32x4_256: 3619 case X86::BI__builtin_ia32_inserti32x4_256: 3620 i = 2; l = 0; u = 1; 3621 break; 3622 case X86::BI__builtin_ia32_vpermilpd: 3623 case X86::BI__builtin_ia32_vec_ext_v4hi: 3624 case X86::BI__builtin_ia32_vec_ext_v4si: 3625 case X86::BI__builtin_ia32_vec_ext_v4sf: 3626 case X86::BI__builtin_ia32_vec_ext_v4di: 3627 case X86::BI__builtin_ia32_extractf32x4_mask: 3628 case X86::BI__builtin_ia32_extracti32x4_mask: 3629 case X86::BI__builtin_ia32_extractf64x2_512_mask: 3630 case X86::BI__builtin_ia32_extracti64x2_512_mask: 3631 i = 1; l = 0; u = 3; 3632 break; 3633 case X86::BI_mm_prefetch: 3634 case X86::BI__builtin_ia32_vec_ext_v8hi: 3635 case X86::BI__builtin_ia32_vec_ext_v8si: 3636 i = 1; l = 0; u = 7; 3637 break; 3638 case X86::BI__builtin_ia32_sha1rnds4: 3639 case X86::BI__builtin_ia32_blendpd: 3640 case X86::BI__builtin_ia32_shufpd: 3641 case X86::BI__builtin_ia32_vec_set_v4hi: 3642 case X86::BI__builtin_ia32_vec_set_v4si: 3643 case X86::BI__builtin_ia32_vec_set_v4di: 3644 case X86::BI__builtin_ia32_shuf_f32x4_256: 3645 case X86::BI__builtin_ia32_shuf_f64x2_256: 3646 case X86::BI__builtin_ia32_shuf_i32x4_256: 3647 case X86::BI__builtin_ia32_shuf_i64x2_256: 3648 case X86::BI__builtin_ia32_insertf64x2_512: 3649 case X86::BI__builtin_ia32_inserti64x2_512: 3650 case X86::BI__builtin_ia32_insertf32x4: 3651 case X86::BI__builtin_ia32_inserti32x4: 3652 i = 2; l = 0; u = 3; 3653 break; 3654 case X86::BI__builtin_ia32_vpermil2pd: 3655 case X86::BI__builtin_ia32_vpermil2pd256: 3656 case X86::BI__builtin_ia32_vpermil2ps: 3657 case X86::BI__builtin_ia32_vpermil2ps256: 3658 i = 3; l = 0; u = 3; 3659 break; 3660 case X86::BI__builtin_ia32_cmpb128_mask: 3661 case X86::BI__builtin_ia32_cmpw128_mask: 3662 case X86::BI__builtin_ia32_cmpd128_mask: 3663 case X86::BI__builtin_ia32_cmpq128_mask: 3664 case X86::BI__builtin_ia32_cmpb256_mask: 3665 case X86::BI__builtin_ia32_cmpw256_mask: 3666 case X86::BI__builtin_ia32_cmpd256_mask: 3667 case X86::BI__builtin_ia32_cmpq256_mask: 3668 case X86::BI__builtin_ia32_cmpb512_mask: 3669 case X86::BI__builtin_ia32_cmpw512_mask: 3670 case X86::BI__builtin_ia32_cmpd512_mask: 3671 case X86::BI__builtin_ia32_cmpq512_mask: 3672 case X86::BI__builtin_ia32_ucmpb128_mask: 3673 case X86::BI__builtin_ia32_ucmpw128_mask: 3674 case X86::BI__builtin_ia32_ucmpd128_mask: 3675 case X86::BI__builtin_ia32_ucmpq128_mask: 3676 case X86::BI__builtin_ia32_ucmpb256_mask: 3677 case X86::BI__builtin_ia32_ucmpw256_mask: 3678 case X86::BI__builtin_ia32_ucmpd256_mask: 3679 case X86::BI__builtin_ia32_ucmpq256_mask: 3680 case X86::BI__builtin_ia32_ucmpb512_mask: 3681 case X86::BI__builtin_ia32_ucmpw512_mask: 3682 case X86::BI__builtin_ia32_ucmpd512_mask: 3683 case X86::BI__builtin_ia32_ucmpq512_mask: 3684 case X86::BI__builtin_ia32_vpcomub: 3685 case X86::BI__builtin_ia32_vpcomuw: 3686 case X86::BI__builtin_ia32_vpcomud: 3687 case X86::BI__builtin_ia32_vpcomuq: 3688 case X86::BI__builtin_ia32_vpcomb: 3689 case X86::BI__builtin_ia32_vpcomw: 3690 case X86::BI__builtin_ia32_vpcomd: 3691 case X86::BI__builtin_ia32_vpcomq: 3692 case X86::BI__builtin_ia32_vec_set_v8hi: 3693 case X86::BI__builtin_ia32_vec_set_v8si: 3694 i = 2; l = 0; u = 7; 3695 break; 3696 case X86::BI__builtin_ia32_vpermilpd256: 3697 case X86::BI__builtin_ia32_roundps: 3698 case X86::BI__builtin_ia32_roundpd: 3699 case X86::BI__builtin_ia32_roundps256: 3700 case X86::BI__builtin_ia32_roundpd256: 3701 case X86::BI__builtin_ia32_getmantpd128_mask: 3702 case X86::BI__builtin_ia32_getmantpd256_mask: 3703 case X86::BI__builtin_ia32_getmantps128_mask: 3704 case X86::BI__builtin_ia32_getmantps256_mask: 3705 case X86::BI__builtin_ia32_getmantpd512_mask: 3706 case X86::BI__builtin_ia32_getmantps512_mask: 3707 case X86::BI__builtin_ia32_vec_ext_v16qi: 3708 case X86::BI__builtin_ia32_vec_ext_v16hi: 3709 i = 1; l = 0; u = 15; 3710 break; 3711 case X86::BI__builtin_ia32_pblendd128: 3712 case X86::BI__builtin_ia32_blendps: 3713 case X86::BI__builtin_ia32_blendpd256: 3714 case X86::BI__builtin_ia32_shufpd256: 3715 case X86::BI__builtin_ia32_roundss: 3716 case X86::BI__builtin_ia32_roundsd: 3717 case X86::BI__builtin_ia32_rangepd128_mask: 3718 case X86::BI__builtin_ia32_rangepd256_mask: 3719 case X86::BI__builtin_ia32_rangepd512_mask: 3720 case X86::BI__builtin_ia32_rangeps128_mask: 3721 case X86::BI__builtin_ia32_rangeps256_mask: 3722 case X86::BI__builtin_ia32_rangeps512_mask: 3723 case X86::BI__builtin_ia32_getmantsd_round_mask: 3724 case X86::BI__builtin_ia32_getmantss_round_mask: 3725 case X86::BI__builtin_ia32_vec_set_v16qi: 3726 case X86::BI__builtin_ia32_vec_set_v16hi: 3727 i = 2; l = 0; u = 15; 3728 break; 3729 case X86::BI__builtin_ia32_vec_ext_v32qi: 3730 i = 1; l = 0; u = 31; 3731 break; 3732 case X86::BI__builtin_ia32_cmpps: 3733 case X86::BI__builtin_ia32_cmpss: 3734 case X86::BI__builtin_ia32_cmppd: 3735 case X86::BI__builtin_ia32_cmpsd: 3736 case X86::BI__builtin_ia32_cmpps256: 3737 case X86::BI__builtin_ia32_cmppd256: 3738 case X86::BI__builtin_ia32_cmpps128_mask: 3739 case X86::BI__builtin_ia32_cmppd128_mask: 3740 case X86::BI__builtin_ia32_cmpps256_mask: 3741 case X86::BI__builtin_ia32_cmppd256_mask: 3742 case X86::BI__builtin_ia32_cmpps512_mask: 3743 case X86::BI__builtin_ia32_cmppd512_mask: 3744 case X86::BI__builtin_ia32_cmpsd_mask: 3745 case X86::BI__builtin_ia32_cmpss_mask: 3746 case X86::BI__builtin_ia32_vec_set_v32qi: 3747 i = 2; l = 0; u = 31; 3748 break; 3749 case X86::BI__builtin_ia32_permdf256: 3750 case X86::BI__builtin_ia32_permdi256: 3751 case X86::BI__builtin_ia32_permdf512: 3752 case X86::BI__builtin_ia32_permdi512: 3753 case X86::BI__builtin_ia32_vpermilps: 3754 case X86::BI__builtin_ia32_vpermilps256: 3755 case X86::BI__builtin_ia32_vpermilpd512: 3756 case X86::BI__builtin_ia32_vpermilps512: 3757 case X86::BI__builtin_ia32_pshufd: 3758 case X86::BI__builtin_ia32_pshufd256: 3759 case X86::BI__builtin_ia32_pshufd512: 3760 case X86::BI__builtin_ia32_pshufhw: 3761 case X86::BI__builtin_ia32_pshufhw256: 3762 case X86::BI__builtin_ia32_pshufhw512: 3763 case X86::BI__builtin_ia32_pshuflw: 3764 case X86::BI__builtin_ia32_pshuflw256: 3765 case X86::BI__builtin_ia32_pshuflw512: 3766 case X86::BI__builtin_ia32_vcvtps2ph: 3767 case X86::BI__builtin_ia32_vcvtps2ph_mask: 3768 case X86::BI__builtin_ia32_vcvtps2ph256: 3769 case X86::BI__builtin_ia32_vcvtps2ph256_mask: 3770 case X86::BI__builtin_ia32_vcvtps2ph512_mask: 3771 case X86::BI__builtin_ia32_rndscaleps_128_mask: 3772 case X86::BI__builtin_ia32_rndscalepd_128_mask: 3773 case X86::BI__builtin_ia32_rndscaleps_256_mask: 3774 case X86::BI__builtin_ia32_rndscalepd_256_mask: 3775 case X86::BI__builtin_ia32_rndscaleps_mask: 3776 case X86::BI__builtin_ia32_rndscalepd_mask: 3777 case X86::BI__builtin_ia32_reducepd128_mask: 3778 case X86::BI__builtin_ia32_reducepd256_mask: 3779 case X86::BI__builtin_ia32_reducepd512_mask: 3780 case X86::BI__builtin_ia32_reduceps128_mask: 3781 case X86::BI__builtin_ia32_reduceps256_mask: 3782 case X86::BI__builtin_ia32_reduceps512_mask: 3783 case X86::BI__builtin_ia32_prold512: 3784 case X86::BI__builtin_ia32_prolq512: 3785 case X86::BI__builtin_ia32_prold128: 3786 case X86::BI__builtin_ia32_prold256: 3787 case X86::BI__builtin_ia32_prolq128: 3788 case X86::BI__builtin_ia32_prolq256: 3789 case X86::BI__builtin_ia32_prord512: 3790 case X86::BI__builtin_ia32_prorq512: 3791 case X86::BI__builtin_ia32_prord128: 3792 case X86::BI__builtin_ia32_prord256: 3793 case X86::BI__builtin_ia32_prorq128: 3794 case X86::BI__builtin_ia32_prorq256: 3795 case X86::BI__builtin_ia32_fpclasspd128_mask: 3796 case X86::BI__builtin_ia32_fpclasspd256_mask: 3797 case X86::BI__builtin_ia32_fpclassps128_mask: 3798 case X86::BI__builtin_ia32_fpclassps256_mask: 3799 case X86::BI__builtin_ia32_fpclassps512_mask: 3800 case X86::BI__builtin_ia32_fpclasspd512_mask: 3801 case X86::BI__builtin_ia32_fpclasssd_mask: 3802 case X86::BI__builtin_ia32_fpclassss_mask: 3803 case X86::BI__builtin_ia32_pslldqi128_byteshift: 3804 case X86::BI__builtin_ia32_pslldqi256_byteshift: 3805 case X86::BI__builtin_ia32_pslldqi512_byteshift: 3806 case X86::BI__builtin_ia32_psrldqi128_byteshift: 3807 case X86::BI__builtin_ia32_psrldqi256_byteshift: 3808 case X86::BI__builtin_ia32_psrldqi512_byteshift: 3809 case X86::BI__builtin_ia32_kshiftliqi: 3810 case X86::BI__builtin_ia32_kshiftlihi: 3811 case X86::BI__builtin_ia32_kshiftlisi: 3812 case X86::BI__builtin_ia32_kshiftlidi: 3813 case X86::BI__builtin_ia32_kshiftriqi: 3814 case X86::BI__builtin_ia32_kshiftrihi: 3815 case X86::BI__builtin_ia32_kshiftrisi: 3816 case X86::BI__builtin_ia32_kshiftridi: 3817 i = 1; l = 0; u = 255; 3818 break; 3819 case X86::BI__builtin_ia32_vperm2f128_pd256: 3820 case X86::BI__builtin_ia32_vperm2f128_ps256: 3821 case X86::BI__builtin_ia32_vperm2f128_si256: 3822 case X86::BI__builtin_ia32_permti256: 3823 case X86::BI__builtin_ia32_pblendw128: 3824 case X86::BI__builtin_ia32_pblendw256: 3825 case X86::BI__builtin_ia32_blendps256: 3826 case X86::BI__builtin_ia32_pblendd256: 3827 case X86::BI__builtin_ia32_palignr128: 3828 case X86::BI__builtin_ia32_palignr256: 3829 case X86::BI__builtin_ia32_palignr512: 3830 case X86::BI__builtin_ia32_alignq512: 3831 case X86::BI__builtin_ia32_alignd512: 3832 case X86::BI__builtin_ia32_alignd128: 3833 case X86::BI__builtin_ia32_alignd256: 3834 case X86::BI__builtin_ia32_alignq128: 3835 case X86::BI__builtin_ia32_alignq256: 3836 case X86::BI__builtin_ia32_vcomisd: 3837 case X86::BI__builtin_ia32_vcomiss: 3838 case X86::BI__builtin_ia32_shuf_f32x4: 3839 case X86::BI__builtin_ia32_shuf_f64x2: 3840 case X86::BI__builtin_ia32_shuf_i32x4: 3841 case X86::BI__builtin_ia32_shuf_i64x2: 3842 case X86::BI__builtin_ia32_shufpd512: 3843 case X86::BI__builtin_ia32_shufps: 3844 case X86::BI__builtin_ia32_shufps256: 3845 case X86::BI__builtin_ia32_shufps512: 3846 case X86::BI__builtin_ia32_dbpsadbw128: 3847 case X86::BI__builtin_ia32_dbpsadbw256: 3848 case X86::BI__builtin_ia32_dbpsadbw512: 3849 case X86::BI__builtin_ia32_vpshldd128: 3850 case X86::BI__builtin_ia32_vpshldd256: 3851 case X86::BI__builtin_ia32_vpshldd512: 3852 case X86::BI__builtin_ia32_vpshldq128: 3853 case X86::BI__builtin_ia32_vpshldq256: 3854 case X86::BI__builtin_ia32_vpshldq512: 3855 case X86::BI__builtin_ia32_vpshldw128: 3856 case X86::BI__builtin_ia32_vpshldw256: 3857 case X86::BI__builtin_ia32_vpshldw512: 3858 case X86::BI__builtin_ia32_vpshrdd128: 3859 case X86::BI__builtin_ia32_vpshrdd256: 3860 case X86::BI__builtin_ia32_vpshrdd512: 3861 case X86::BI__builtin_ia32_vpshrdq128: 3862 case X86::BI__builtin_ia32_vpshrdq256: 3863 case X86::BI__builtin_ia32_vpshrdq512: 3864 case X86::BI__builtin_ia32_vpshrdw128: 3865 case X86::BI__builtin_ia32_vpshrdw256: 3866 case X86::BI__builtin_ia32_vpshrdw512: 3867 i = 2; l = 0; u = 255; 3868 break; 3869 case X86::BI__builtin_ia32_fixupimmpd512_mask: 3870 case X86::BI__builtin_ia32_fixupimmpd512_maskz: 3871 case X86::BI__builtin_ia32_fixupimmps512_mask: 3872 case X86::BI__builtin_ia32_fixupimmps512_maskz: 3873 case X86::BI__builtin_ia32_fixupimmsd_mask: 3874 case X86::BI__builtin_ia32_fixupimmsd_maskz: 3875 case X86::BI__builtin_ia32_fixupimmss_mask: 3876 case X86::BI__builtin_ia32_fixupimmss_maskz: 3877 case X86::BI__builtin_ia32_fixupimmpd128_mask: 3878 case X86::BI__builtin_ia32_fixupimmpd128_maskz: 3879 case X86::BI__builtin_ia32_fixupimmpd256_mask: 3880 case X86::BI__builtin_ia32_fixupimmpd256_maskz: 3881 case X86::BI__builtin_ia32_fixupimmps128_mask: 3882 case X86::BI__builtin_ia32_fixupimmps128_maskz: 3883 case X86::BI__builtin_ia32_fixupimmps256_mask: 3884 case X86::BI__builtin_ia32_fixupimmps256_maskz: 3885 case X86::BI__builtin_ia32_pternlogd512_mask: 3886 case X86::BI__builtin_ia32_pternlogd512_maskz: 3887 case X86::BI__builtin_ia32_pternlogq512_mask: 3888 case X86::BI__builtin_ia32_pternlogq512_maskz: 3889 case X86::BI__builtin_ia32_pternlogd128_mask: 3890 case X86::BI__builtin_ia32_pternlogd128_maskz: 3891 case X86::BI__builtin_ia32_pternlogd256_mask: 3892 case X86::BI__builtin_ia32_pternlogd256_maskz: 3893 case X86::BI__builtin_ia32_pternlogq128_mask: 3894 case X86::BI__builtin_ia32_pternlogq128_maskz: 3895 case X86::BI__builtin_ia32_pternlogq256_mask: 3896 case X86::BI__builtin_ia32_pternlogq256_maskz: 3897 i = 3; l = 0; u = 255; 3898 break; 3899 case X86::BI__builtin_ia32_gatherpfdpd: 3900 case X86::BI__builtin_ia32_gatherpfdps: 3901 case X86::BI__builtin_ia32_gatherpfqpd: 3902 case X86::BI__builtin_ia32_gatherpfqps: 3903 case X86::BI__builtin_ia32_scatterpfdpd: 3904 case X86::BI__builtin_ia32_scatterpfdps: 3905 case X86::BI__builtin_ia32_scatterpfqpd: 3906 case X86::BI__builtin_ia32_scatterpfqps: 3907 i = 4; l = 2; u = 3; 3908 break; 3909 case X86::BI__builtin_ia32_reducesd_mask: 3910 case X86::BI__builtin_ia32_reducess_mask: 3911 case X86::BI__builtin_ia32_rndscalesd_round_mask: 3912 case X86::BI__builtin_ia32_rndscaless_round_mask: 3913 i = 4; l = 0; u = 255; 3914 break; 3915 } 3916 3917 // Note that we don't force a hard error on the range check here, allowing 3918 // template-generated or macro-generated dead code to potentially have out-of- 3919 // range values. These need to code generate, but don't need to necessarily 3920 // make any sense. We use a warning that defaults to an error. 3921 return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false); 3922 } 3923 3924 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo 3925 /// parameter with the FormatAttr's correct format_idx and firstDataArg. 3926 /// Returns true when the format fits the function and the FormatStringInfo has 3927 /// been populated. 3928 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, 3929 FormatStringInfo *FSI) { 3930 FSI->HasVAListArg = Format->getFirstArg() == 0; 3931 FSI->FormatIdx = Format->getFormatIdx() - 1; 3932 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1; 3933 3934 // The way the format attribute works in GCC, the implicit this argument 3935 // of member functions is counted. However, it doesn't appear in our own 3936 // lists, so decrement format_idx in that case. 3937 if (IsCXXMember) { 3938 if(FSI->FormatIdx == 0) 3939 return false; 3940 --FSI->FormatIdx; 3941 if (FSI->FirstDataArg != 0) 3942 --FSI->FirstDataArg; 3943 } 3944 return true; 3945 } 3946 3947 /// Checks if a the given expression evaluates to null. 3948 /// 3949 /// Returns true if the value evaluates to null. 3950 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) { 3951 // If the expression has non-null type, it doesn't evaluate to null. 3952 if (auto nullability 3953 = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) { 3954 if (*nullability == NullabilityKind::NonNull) 3955 return false; 3956 } 3957 3958 // As a special case, transparent unions initialized with zero are 3959 // considered null for the purposes of the nonnull attribute. 3960 if (const RecordType *UT = Expr->getType()->getAsUnionType()) { 3961 if (UT->getDecl()->hasAttr<TransparentUnionAttr>()) 3962 if (const CompoundLiteralExpr *CLE = 3963 dyn_cast<CompoundLiteralExpr>(Expr)) 3964 if (const InitListExpr *ILE = 3965 dyn_cast<InitListExpr>(CLE->getInitializer())) 3966 Expr = ILE->getInit(0); 3967 } 3968 3969 bool Result; 3970 return (!Expr->isValueDependent() && 3971 Expr->EvaluateAsBooleanCondition(Result, S.Context) && 3972 !Result); 3973 } 3974 3975 static void CheckNonNullArgument(Sema &S, 3976 const Expr *ArgExpr, 3977 SourceLocation CallSiteLoc) { 3978 if (CheckNonNullExpr(S, ArgExpr)) 3979 S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr, 3980 S.PDiag(diag::warn_null_arg) 3981 << ArgExpr->getSourceRange()); 3982 } 3983 3984 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) { 3985 FormatStringInfo FSI; 3986 if ((GetFormatStringType(Format) == FST_NSString) && 3987 getFormatStringInfo(Format, false, &FSI)) { 3988 Idx = FSI.FormatIdx; 3989 return true; 3990 } 3991 return false; 3992 } 3993 3994 /// Diagnose use of %s directive in an NSString which is being passed 3995 /// as formatting string to formatting method. 3996 static void 3997 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, 3998 const NamedDecl *FDecl, 3999 Expr **Args, 4000 unsigned NumArgs) { 4001 unsigned Idx = 0; 4002 bool Format = false; 4003 ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily(); 4004 if (SFFamily == ObjCStringFormatFamily::SFF_CFString) { 4005 Idx = 2; 4006 Format = true; 4007 } 4008 else 4009 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4010 if (S.GetFormatNSStringIdx(I, Idx)) { 4011 Format = true; 4012 break; 4013 } 4014 } 4015 if (!Format || NumArgs <= Idx) 4016 return; 4017 const Expr *FormatExpr = Args[Idx]; 4018 if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr)) 4019 FormatExpr = CSCE->getSubExpr(); 4020 const StringLiteral *FormatString; 4021 if (const ObjCStringLiteral *OSL = 4022 dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts())) 4023 FormatString = OSL->getString(); 4024 else 4025 FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts()); 4026 if (!FormatString) 4027 return; 4028 if (S.FormatStringHasSArg(FormatString)) { 4029 S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string) 4030 << "%s" << 1 << 1; 4031 S.Diag(FDecl->getLocation(), diag::note_entity_declared_at) 4032 << FDecl->getDeclName(); 4033 } 4034 } 4035 4036 /// Determine whether the given type has a non-null nullability annotation. 4037 static bool isNonNullType(ASTContext &ctx, QualType type) { 4038 if (auto nullability = type->getNullability(ctx)) 4039 return *nullability == NullabilityKind::NonNull; 4040 4041 return false; 4042 } 4043 4044 static void CheckNonNullArguments(Sema &S, 4045 const NamedDecl *FDecl, 4046 const FunctionProtoType *Proto, 4047 ArrayRef<const Expr *> Args, 4048 SourceLocation CallSiteLoc) { 4049 assert((FDecl || Proto) && "Need a function declaration or prototype"); 4050 4051 // Already checked by by constant evaluator. 4052 if (S.isConstantEvaluated()) 4053 return; 4054 // Check the attributes attached to the method/function itself. 4055 llvm::SmallBitVector NonNullArgs; 4056 if (FDecl) { 4057 // Handle the nonnull attribute on the function/method declaration itself. 4058 for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) { 4059 if (!NonNull->args_size()) { 4060 // Easy case: all pointer arguments are nonnull. 4061 for (const auto *Arg : Args) 4062 if (S.isValidPointerAttrType(Arg->getType())) 4063 CheckNonNullArgument(S, Arg, CallSiteLoc); 4064 return; 4065 } 4066 4067 for (const ParamIdx &Idx : NonNull->args()) { 4068 unsigned IdxAST = Idx.getASTIndex(); 4069 if (IdxAST >= Args.size()) 4070 continue; 4071 if (NonNullArgs.empty()) 4072 NonNullArgs.resize(Args.size()); 4073 NonNullArgs.set(IdxAST); 4074 } 4075 } 4076 } 4077 4078 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) { 4079 // Handle the nonnull attribute on the parameters of the 4080 // function/method. 4081 ArrayRef<ParmVarDecl*> parms; 4082 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl)) 4083 parms = FD->parameters(); 4084 else 4085 parms = cast<ObjCMethodDecl>(FDecl)->parameters(); 4086 4087 unsigned ParamIndex = 0; 4088 for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end(); 4089 I != E; ++I, ++ParamIndex) { 4090 const ParmVarDecl *PVD = *I; 4091 if (PVD->hasAttr<NonNullAttr>() || 4092 isNonNullType(S.Context, PVD->getType())) { 4093 if (NonNullArgs.empty()) 4094 NonNullArgs.resize(Args.size()); 4095 4096 NonNullArgs.set(ParamIndex); 4097 } 4098 } 4099 } else { 4100 // If we have a non-function, non-method declaration but no 4101 // function prototype, try to dig out the function prototype. 4102 if (!Proto) { 4103 if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) { 4104 QualType type = VD->getType().getNonReferenceType(); 4105 if (auto pointerType = type->getAs<PointerType>()) 4106 type = pointerType->getPointeeType(); 4107 else if (auto blockType = type->getAs<BlockPointerType>()) 4108 type = blockType->getPointeeType(); 4109 // FIXME: data member pointers? 4110 4111 // Dig out the function prototype, if there is one. 4112 Proto = type->getAs<FunctionProtoType>(); 4113 } 4114 } 4115 4116 // Fill in non-null argument information from the nullability 4117 // information on the parameter types (if we have them). 4118 if (Proto) { 4119 unsigned Index = 0; 4120 for (auto paramType : Proto->getParamTypes()) { 4121 if (isNonNullType(S.Context, paramType)) { 4122 if (NonNullArgs.empty()) 4123 NonNullArgs.resize(Args.size()); 4124 4125 NonNullArgs.set(Index); 4126 } 4127 4128 ++Index; 4129 } 4130 } 4131 } 4132 4133 // Check for non-null arguments. 4134 for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size(); 4135 ArgIndex != ArgIndexEnd; ++ArgIndex) { 4136 if (NonNullArgs[ArgIndex]) 4137 CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc); 4138 } 4139 } 4140 4141 /// Handles the checks for format strings, non-POD arguments to vararg 4142 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if 4143 /// attributes. 4144 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, 4145 const Expr *ThisArg, ArrayRef<const Expr *> Args, 4146 bool IsMemberFunction, SourceLocation Loc, 4147 SourceRange Range, VariadicCallType CallType) { 4148 // FIXME: We should check as much as we can in the template definition. 4149 if (CurContext->isDependentContext()) 4150 return; 4151 4152 // Printf and scanf checking. 4153 llvm::SmallBitVector CheckedVarArgs; 4154 if (FDecl) { 4155 for (const auto *I : FDecl->specific_attrs<FormatAttr>()) { 4156 // Only create vector if there are format attributes. 4157 CheckedVarArgs.resize(Args.size()); 4158 4159 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range, 4160 CheckedVarArgs); 4161 } 4162 } 4163 4164 // Refuse POD arguments that weren't caught by the format string 4165 // checks above. 4166 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl); 4167 if (CallType != VariadicDoesNotApply && 4168 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) { 4169 unsigned NumParams = Proto ? Proto->getNumParams() 4170 : FDecl && isa<FunctionDecl>(FDecl) 4171 ? cast<FunctionDecl>(FDecl)->getNumParams() 4172 : FDecl && isa<ObjCMethodDecl>(FDecl) 4173 ? cast<ObjCMethodDecl>(FDecl)->param_size() 4174 : 0; 4175 4176 for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) { 4177 // Args[ArgIdx] can be null in malformed code. 4178 if (const Expr *Arg = Args[ArgIdx]) { 4179 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx]) 4180 checkVariadicArgument(Arg, CallType); 4181 } 4182 } 4183 } 4184 4185 if (FDecl || Proto) { 4186 CheckNonNullArguments(*this, FDecl, Proto, Args, Loc); 4187 4188 // Type safety checking. 4189 if (FDecl) { 4190 for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>()) 4191 CheckArgumentWithTypeTag(I, Args, Loc); 4192 } 4193 } 4194 4195 if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) { 4196 auto *AA = FDecl->getAttr<AllocAlignAttr>(); 4197 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()]; 4198 if (!Arg->isValueDependent()) { 4199 Expr::EvalResult Align; 4200 if (Arg->EvaluateAsInt(Align, Context)) { 4201 const llvm::APSInt &I = Align.Val.getInt(); 4202 if (!I.isPowerOf2()) 4203 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two) 4204 << Arg->getSourceRange(); 4205 4206 if (I > Sema::MaximumAlignment) 4207 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great) 4208 << Arg->getSourceRange() << Sema::MaximumAlignment; 4209 } 4210 } 4211 } 4212 4213 if (FD) 4214 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc); 4215 } 4216 4217 /// CheckConstructorCall - Check a constructor call for correctness and safety 4218 /// properties not enforced by the C type system. 4219 void Sema::CheckConstructorCall(FunctionDecl *FDecl, 4220 ArrayRef<const Expr *> Args, 4221 const FunctionProtoType *Proto, 4222 SourceLocation Loc) { 4223 VariadicCallType CallType = 4224 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply; 4225 checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true, 4226 Loc, SourceRange(), CallType); 4227 } 4228 4229 /// CheckFunctionCall - Check a direct function call for various correctness 4230 /// and safety properties not strictly enforced by the C type system. 4231 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, 4232 const FunctionProtoType *Proto) { 4233 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) && 4234 isa<CXXMethodDecl>(FDecl); 4235 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) || 4236 IsMemberOperatorCall; 4237 VariadicCallType CallType = getVariadicCallType(FDecl, Proto, 4238 TheCall->getCallee()); 4239 Expr** Args = TheCall->getArgs(); 4240 unsigned NumArgs = TheCall->getNumArgs(); 4241 4242 Expr *ImplicitThis = nullptr; 4243 if (IsMemberOperatorCall) { 4244 // If this is a call to a member operator, hide the first argument 4245 // from checkCall. 4246 // FIXME: Our choice of AST representation here is less than ideal. 4247 ImplicitThis = Args[0]; 4248 ++Args; 4249 --NumArgs; 4250 } else if (IsMemberFunction) 4251 ImplicitThis = 4252 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument(); 4253 4254 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs), 4255 IsMemberFunction, TheCall->getRParenLoc(), 4256 TheCall->getCallee()->getSourceRange(), CallType); 4257 4258 IdentifierInfo *FnInfo = FDecl->getIdentifier(); 4259 // None of the checks below are needed for functions that don't have 4260 // simple names (e.g., C++ conversion functions). 4261 if (!FnInfo) 4262 return false; 4263 4264 CheckAbsoluteValueFunction(TheCall, FDecl); 4265 CheckMaxUnsignedZero(TheCall, FDecl); 4266 4267 if (getLangOpts().ObjC) 4268 DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs); 4269 4270 unsigned CMId = FDecl->getMemoryFunctionKind(); 4271 if (CMId == 0) 4272 return false; 4273 4274 // Handle memory setting and copying functions. 4275 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat) 4276 CheckStrlcpycatArguments(TheCall, FnInfo); 4277 else if (CMId == Builtin::BIstrncat) 4278 CheckStrncatArguments(TheCall, FnInfo); 4279 else 4280 CheckMemaccessArguments(TheCall, CMId, FnInfo); 4281 4282 return false; 4283 } 4284 4285 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac, 4286 ArrayRef<const Expr *> Args) { 4287 VariadicCallType CallType = 4288 Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply; 4289 4290 checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args, 4291 /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(), 4292 CallType); 4293 4294 return false; 4295 } 4296 4297 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, 4298 const FunctionProtoType *Proto) { 4299 QualType Ty; 4300 if (const auto *V = dyn_cast<VarDecl>(NDecl)) 4301 Ty = V->getType().getNonReferenceType(); 4302 else if (const auto *F = dyn_cast<FieldDecl>(NDecl)) 4303 Ty = F->getType().getNonReferenceType(); 4304 else 4305 return false; 4306 4307 if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() && 4308 !Ty->isFunctionProtoType()) 4309 return false; 4310 4311 VariadicCallType CallType; 4312 if (!Proto || !Proto->isVariadic()) { 4313 CallType = VariadicDoesNotApply; 4314 } else if (Ty->isBlockPointerType()) { 4315 CallType = VariadicBlock; 4316 } else { // Ty->isFunctionPointerType() 4317 CallType = VariadicFunction; 4318 } 4319 4320 checkCall(NDecl, Proto, /*ThisArg=*/nullptr, 4321 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4322 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4323 TheCall->getCallee()->getSourceRange(), CallType); 4324 4325 return false; 4326 } 4327 4328 /// Checks function calls when a FunctionDecl or a NamedDecl is not available, 4329 /// such as function pointers returned from functions. 4330 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) { 4331 VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto, 4332 TheCall->getCallee()); 4333 checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr, 4334 llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()), 4335 /*IsMemberFunction=*/false, TheCall->getRParenLoc(), 4336 TheCall->getCallee()->getSourceRange(), CallType); 4337 4338 return false; 4339 } 4340 4341 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) { 4342 if (!llvm::isValidAtomicOrderingCABI(Ordering)) 4343 return false; 4344 4345 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering; 4346 switch (Op) { 4347 case AtomicExpr::AO__c11_atomic_init: 4348 case AtomicExpr::AO__opencl_atomic_init: 4349 llvm_unreachable("There is no ordering argument for an init"); 4350 4351 case AtomicExpr::AO__c11_atomic_load: 4352 case AtomicExpr::AO__opencl_atomic_load: 4353 case AtomicExpr::AO__atomic_load_n: 4354 case AtomicExpr::AO__atomic_load: 4355 return OrderingCABI != llvm::AtomicOrderingCABI::release && 4356 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4357 4358 case AtomicExpr::AO__c11_atomic_store: 4359 case AtomicExpr::AO__opencl_atomic_store: 4360 case AtomicExpr::AO__atomic_store: 4361 case AtomicExpr::AO__atomic_store_n: 4362 return OrderingCABI != llvm::AtomicOrderingCABI::consume && 4363 OrderingCABI != llvm::AtomicOrderingCABI::acquire && 4364 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel; 4365 4366 default: 4367 return true; 4368 } 4369 } 4370 4371 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult, 4372 AtomicExpr::AtomicOp Op) { 4373 CallExpr *TheCall = cast<CallExpr>(TheCallResult.get()); 4374 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 4375 MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()}; 4376 return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()}, 4377 DRE->getSourceRange(), TheCall->getRParenLoc(), Args, 4378 Op); 4379 } 4380 4381 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, 4382 SourceLocation RParenLoc, MultiExprArg Args, 4383 AtomicExpr::AtomicOp Op, 4384 AtomicArgumentOrder ArgOrder) { 4385 // All the non-OpenCL operations take one of the following forms. 4386 // The OpenCL operations take the __c11 forms with one extra argument for 4387 // synchronization scope. 4388 enum { 4389 // C __c11_atomic_init(A *, C) 4390 Init, 4391 4392 // C __c11_atomic_load(A *, int) 4393 Load, 4394 4395 // void __atomic_load(A *, CP, int) 4396 LoadCopy, 4397 4398 // void __atomic_store(A *, CP, int) 4399 Copy, 4400 4401 // C __c11_atomic_add(A *, M, int) 4402 Arithmetic, 4403 4404 // C __atomic_exchange_n(A *, CP, int) 4405 Xchg, 4406 4407 // void __atomic_exchange(A *, C *, CP, int) 4408 GNUXchg, 4409 4410 // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int) 4411 C11CmpXchg, 4412 4413 // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int) 4414 GNUCmpXchg 4415 } Form = Init; 4416 4417 const unsigned NumForm = GNUCmpXchg + 1; 4418 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 }; 4419 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 }; 4420 // where: 4421 // C is an appropriate type, 4422 // A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins, 4423 // CP is C for __c11 builtins and GNU _n builtins and is C * otherwise, 4424 // M is C if C is an integer, and ptrdiff_t if C is a pointer, and 4425 // the int parameters are for orderings. 4426 4427 static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm 4428 && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm, 4429 "need to update code for modified forms"); 4430 static_assert(AtomicExpr::AO__c11_atomic_init == 0 && 4431 AtomicExpr::AO__c11_atomic_fetch_min + 1 == 4432 AtomicExpr::AO__atomic_load, 4433 "need to update code for modified C11 atomics"); 4434 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init && 4435 Op <= AtomicExpr::AO__opencl_atomic_fetch_max; 4436 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init && 4437 Op <= AtomicExpr::AO__c11_atomic_fetch_min) || 4438 IsOpenCL; 4439 bool IsN = Op == AtomicExpr::AO__atomic_load_n || 4440 Op == AtomicExpr::AO__atomic_store_n || 4441 Op == AtomicExpr::AO__atomic_exchange_n || 4442 Op == AtomicExpr::AO__atomic_compare_exchange_n; 4443 bool IsAddSub = false; 4444 4445 switch (Op) { 4446 case AtomicExpr::AO__c11_atomic_init: 4447 case AtomicExpr::AO__opencl_atomic_init: 4448 Form = Init; 4449 break; 4450 4451 case AtomicExpr::AO__c11_atomic_load: 4452 case AtomicExpr::AO__opencl_atomic_load: 4453 case AtomicExpr::AO__atomic_load_n: 4454 Form = Load; 4455 break; 4456 4457 case AtomicExpr::AO__atomic_load: 4458 Form = LoadCopy; 4459 break; 4460 4461 case AtomicExpr::AO__c11_atomic_store: 4462 case AtomicExpr::AO__opencl_atomic_store: 4463 case AtomicExpr::AO__atomic_store: 4464 case AtomicExpr::AO__atomic_store_n: 4465 Form = Copy; 4466 break; 4467 4468 case AtomicExpr::AO__c11_atomic_fetch_add: 4469 case AtomicExpr::AO__c11_atomic_fetch_sub: 4470 case AtomicExpr::AO__opencl_atomic_fetch_add: 4471 case AtomicExpr::AO__opencl_atomic_fetch_sub: 4472 case AtomicExpr::AO__atomic_fetch_add: 4473 case AtomicExpr::AO__atomic_fetch_sub: 4474 case AtomicExpr::AO__atomic_add_fetch: 4475 case AtomicExpr::AO__atomic_sub_fetch: 4476 IsAddSub = true; 4477 LLVM_FALLTHROUGH; 4478 case AtomicExpr::AO__c11_atomic_fetch_and: 4479 case AtomicExpr::AO__c11_atomic_fetch_or: 4480 case AtomicExpr::AO__c11_atomic_fetch_xor: 4481 case AtomicExpr::AO__opencl_atomic_fetch_and: 4482 case AtomicExpr::AO__opencl_atomic_fetch_or: 4483 case AtomicExpr::AO__opencl_atomic_fetch_xor: 4484 case AtomicExpr::AO__atomic_fetch_and: 4485 case AtomicExpr::AO__atomic_fetch_or: 4486 case AtomicExpr::AO__atomic_fetch_xor: 4487 case AtomicExpr::AO__atomic_fetch_nand: 4488 case AtomicExpr::AO__atomic_and_fetch: 4489 case AtomicExpr::AO__atomic_or_fetch: 4490 case AtomicExpr::AO__atomic_xor_fetch: 4491 case AtomicExpr::AO__atomic_nand_fetch: 4492 case AtomicExpr::AO__c11_atomic_fetch_min: 4493 case AtomicExpr::AO__c11_atomic_fetch_max: 4494 case AtomicExpr::AO__opencl_atomic_fetch_min: 4495 case AtomicExpr::AO__opencl_atomic_fetch_max: 4496 case AtomicExpr::AO__atomic_min_fetch: 4497 case AtomicExpr::AO__atomic_max_fetch: 4498 case AtomicExpr::AO__atomic_fetch_min: 4499 case AtomicExpr::AO__atomic_fetch_max: 4500 Form = Arithmetic; 4501 break; 4502 4503 case AtomicExpr::AO__c11_atomic_exchange: 4504 case AtomicExpr::AO__opencl_atomic_exchange: 4505 case AtomicExpr::AO__atomic_exchange_n: 4506 Form = Xchg; 4507 break; 4508 4509 case AtomicExpr::AO__atomic_exchange: 4510 Form = GNUXchg; 4511 break; 4512 4513 case AtomicExpr::AO__c11_atomic_compare_exchange_strong: 4514 case AtomicExpr::AO__c11_atomic_compare_exchange_weak: 4515 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong: 4516 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak: 4517 Form = C11CmpXchg; 4518 break; 4519 4520 case AtomicExpr::AO__atomic_compare_exchange: 4521 case AtomicExpr::AO__atomic_compare_exchange_n: 4522 Form = GNUCmpXchg; 4523 break; 4524 } 4525 4526 unsigned AdjustedNumArgs = NumArgs[Form]; 4527 if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init) 4528 ++AdjustedNumArgs; 4529 // Check we have the right number of arguments. 4530 if (Args.size() < AdjustedNumArgs) { 4531 Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args) 4532 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4533 << ExprRange; 4534 return ExprError(); 4535 } else if (Args.size() > AdjustedNumArgs) { 4536 Diag(Args[AdjustedNumArgs]->getBeginLoc(), 4537 diag::err_typecheck_call_too_many_args) 4538 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size()) 4539 << ExprRange; 4540 return ExprError(); 4541 } 4542 4543 // Inspect the first argument of the atomic operation. 4544 Expr *Ptr = Args[0]; 4545 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr); 4546 if (ConvertedPtr.isInvalid()) 4547 return ExprError(); 4548 4549 Ptr = ConvertedPtr.get(); 4550 const PointerType *pointerType = Ptr->getType()->getAs<PointerType>(); 4551 if (!pointerType) { 4552 Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer) 4553 << Ptr->getType() << Ptr->getSourceRange(); 4554 return ExprError(); 4555 } 4556 4557 // For a __c11 builtin, this should be a pointer to an _Atomic type. 4558 QualType AtomTy = pointerType->getPointeeType(); // 'A' 4559 QualType ValType = AtomTy; // 'C' 4560 if (IsC11) { 4561 if (!AtomTy->isAtomicType()) { 4562 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic) 4563 << Ptr->getType() << Ptr->getSourceRange(); 4564 return ExprError(); 4565 } 4566 if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) || 4567 AtomTy.getAddressSpace() == LangAS::opencl_constant) { 4568 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic) 4569 << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType() 4570 << Ptr->getSourceRange(); 4571 return ExprError(); 4572 } 4573 ValType = AtomTy->castAs<AtomicType>()->getValueType(); 4574 } else if (Form != Load && Form != LoadCopy) { 4575 if (ValType.isConstQualified()) { 4576 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer) 4577 << Ptr->getType() << Ptr->getSourceRange(); 4578 return ExprError(); 4579 } 4580 } 4581 4582 // For an arithmetic operation, the implied arithmetic must be well-formed. 4583 if (Form == Arithmetic) { 4584 // gcc does not enforce these rules for GNU atomics, but we do so for sanity. 4585 if (IsAddSub && !ValType->isIntegerType() 4586 && !ValType->isPointerType()) { 4587 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4588 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4589 return ExprError(); 4590 } 4591 if (!IsAddSub && !ValType->isIntegerType()) { 4592 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int) 4593 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4594 return ExprError(); 4595 } 4596 if (IsC11 && ValType->isPointerType() && 4597 RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(), 4598 diag::err_incomplete_type)) { 4599 return ExprError(); 4600 } 4601 } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) { 4602 // For __atomic_*_n operations, the value type must be a scalar integral or 4603 // pointer type which is 1, 2, 4, 8 or 16 bytes in length. 4604 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr) 4605 << IsC11 << Ptr->getType() << Ptr->getSourceRange(); 4606 return ExprError(); 4607 } 4608 4609 if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) && 4610 !AtomTy->isScalarType()) { 4611 // For GNU atomics, require a trivially-copyable type. This is not part of 4612 // the GNU atomics specification, but we enforce it for sanity. 4613 Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy) 4614 << Ptr->getType() << Ptr->getSourceRange(); 4615 return ExprError(); 4616 } 4617 4618 switch (ValType.getObjCLifetime()) { 4619 case Qualifiers::OCL_None: 4620 case Qualifiers::OCL_ExplicitNone: 4621 // okay 4622 break; 4623 4624 case Qualifiers::OCL_Weak: 4625 case Qualifiers::OCL_Strong: 4626 case Qualifiers::OCL_Autoreleasing: 4627 // FIXME: Can this happen? By this point, ValType should be known 4628 // to be trivially copyable. 4629 Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership) 4630 << ValType << Ptr->getSourceRange(); 4631 return ExprError(); 4632 } 4633 4634 // All atomic operations have an overload which takes a pointer to a volatile 4635 // 'A'. We shouldn't let the volatile-ness of the pointee-type inject itself 4636 // into the result or the other operands. Similarly atomic_load takes a 4637 // pointer to a const 'A'. 4638 ValType.removeLocalVolatile(); 4639 ValType.removeLocalConst(); 4640 QualType ResultType = ValType; 4641 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || 4642 Form == Init) 4643 ResultType = Context.VoidTy; 4644 else if (Form == C11CmpXchg || Form == GNUCmpXchg) 4645 ResultType = Context.BoolTy; 4646 4647 // The type of a parameter passed 'by value'. In the GNU atomics, such 4648 // arguments are actually passed as pointers. 4649 QualType ByValType = ValType; // 'CP' 4650 bool IsPassedByAddress = false; 4651 if (!IsC11 && !IsN) { 4652 ByValType = Ptr->getType(); 4653 IsPassedByAddress = true; 4654 } 4655 4656 SmallVector<Expr *, 5> APIOrderedArgs; 4657 if (ArgOrder == Sema::AtomicArgumentOrder::AST) { 4658 APIOrderedArgs.push_back(Args[0]); 4659 switch (Form) { 4660 case Init: 4661 case Load: 4662 APIOrderedArgs.push_back(Args[1]); // Val1/Order 4663 break; 4664 case LoadCopy: 4665 case Copy: 4666 case Arithmetic: 4667 case Xchg: 4668 APIOrderedArgs.push_back(Args[2]); // Val1 4669 APIOrderedArgs.push_back(Args[1]); // Order 4670 break; 4671 case GNUXchg: 4672 APIOrderedArgs.push_back(Args[2]); // Val1 4673 APIOrderedArgs.push_back(Args[3]); // Val2 4674 APIOrderedArgs.push_back(Args[1]); // Order 4675 break; 4676 case C11CmpXchg: 4677 APIOrderedArgs.push_back(Args[2]); // Val1 4678 APIOrderedArgs.push_back(Args[4]); // Val2 4679 APIOrderedArgs.push_back(Args[1]); // Order 4680 APIOrderedArgs.push_back(Args[3]); // OrderFail 4681 break; 4682 case GNUCmpXchg: 4683 APIOrderedArgs.push_back(Args[2]); // Val1 4684 APIOrderedArgs.push_back(Args[4]); // Val2 4685 APIOrderedArgs.push_back(Args[5]); // Weak 4686 APIOrderedArgs.push_back(Args[1]); // Order 4687 APIOrderedArgs.push_back(Args[3]); // OrderFail 4688 break; 4689 } 4690 } else 4691 APIOrderedArgs.append(Args.begin(), Args.end()); 4692 4693 // The first argument's non-CV pointer type is used to deduce the type of 4694 // subsequent arguments, except for: 4695 // - weak flag (always converted to bool) 4696 // - memory order (always converted to int) 4697 // - scope (always converted to int) 4698 for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) { 4699 QualType Ty; 4700 if (i < NumVals[Form] + 1) { 4701 switch (i) { 4702 case 0: 4703 // The first argument is always a pointer. It has a fixed type. 4704 // It is always dereferenced, a nullptr is undefined. 4705 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4706 // Nothing else to do: we already know all we want about this pointer. 4707 continue; 4708 case 1: 4709 // The second argument is the non-atomic operand. For arithmetic, this 4710 // is always passed by value, and for a compare_exchange it is always 4711 // passed by address. For the rest, GNU uses by-address and C11 uses 4712 // by-value. 4713 assert(Form != Load); 4714 if (Form == Init || (Form == Arithmetic && ValType->isIntegerType())) 4715 Ty = ValType; 4716 else if (Form == Copy || Form == Xchg) { 4717 if (IsPassedByAddress) { 4718 // The value pointer is always dereferenced, a nullptr is undefined. 4719 CheckNonNullArgument(*this, APIOrderedArgs[i], 4720 ExprRange.getBegin()); 4721 } 4722 Ty = ByValType; 4723 } else if (Form == Arithmetic) 4724 Ty = Context.getPointerDiffType(); 4725 else { 4726 Expr *ValArg = APIOrderedArgs[i]; 4727 // The value pointer is always dereferenced, a nullptr is undefined. 4728 CheckNonNullArgument(*this, ValArg, ExprRange.getBegin()); 4729 LangAS AS = LangAS::Default; 4730 // Keep address space of non-atomic pointer type. 4731 if (const PointerType *PtrTy = 4732 ValArg->getType()->getAs<PointerType>()) { 4733 AS = PtrTy->getPointeeType().getAddressSpace(); 4734 } 4735 Ty = Context.getPointerType( 4736 Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS)); 4737 } 4738 break; 4739 case 2: 4740 // The third argument to compare_exchange / GNU exchange is the desired 4741 // value, either by-value (for the C11 and *_n variant) or as a pointer. 4742 if (IsPassedByAddress) 4743 CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin()); 4744 Ty = ByValType; 4745 break; 4746 case 3: 4747 // The fourth argument to GNU compare_exchange is a 'weak' flag. 4748 Ty = Context.BoolTy; 4749 break; 4750 } 4751 } else { 4752 // The order(s) and scope are always converted to int. 4753 Ty = Context.IntTy; 4754 } 4755 4756 InitializedEntity Entity = 4757 InitializedEntity::InitializeParameter(Context, Ty, false); 4758 ExprResult Arg = APIOrderedArgs[i]; 4759 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 4760 if (Arg.isInvalid()) 4761 return true; 4762 APIOrderedArgs[i] = Arg.get(); 4763 } 4764 4765 // Permute the arguments into a 'consistent' order. 4766 SmallVector<Expr*, 5> SubExprs; 4767 SubExprs.push_back(Ptr); 4768 switch (Form) { 4769 case Init: 4770 // Note, AtomicExpr::getVal1() has a special case for this atomic. 4771 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4772 break; 4773 case Load: 4774 SubExprs.push_back(APIOrderedArgs[1]); // Order 4775 break; 4776 case LoadCopy: 4777 case Copy: 4778 case Arithmetic: 4779 case Xchg: 4780 SubExprs.push_back(APIOrderedArgs[2]); // Order 4781 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4782 break; 4783 case GNUXchg: 4784 // Note, AtomicExpr::getVal2() has a special case for this atomic. 4785 SubExprs.push_back(APIOrderedArgs[3]); // Order 4786 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4787 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4788 break; 4789 case C11CmpXchg: 4790 SubExprs.push_back(APIOrderedArgs[3]); // Order 4791 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4792 SubExprs.push_back(APIOrderedArgs[4]); // OrderFail 4793 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4794 break; 4795 case GNUCmpXchg: 4796 SubExprs.push_back(APIOrderedArgs[4]); // Order 4797 SubExprs.push_back(APIOrderedArgs[1]); // Val1 4798 SubExprs.push_back(APIOrderedArgs[5]); // OrderFail 4799 SubExprs.push_back(APIOrderedArgs[2]); // Val2 4800 SubExprs.push_back(APIOrderedArgs[3]); // Weak 4801 break; 4802 } 4803 4804 if (SubExprs.size() >= 2 && Form != Init) { 4805 llvm::APSInt Result(32); 4806 if (SubExprs[1]->isIntegerConstantExpr(Result, Context) && 4807 !isValidOrderingForOp(Result.getSExtValue(), Op)) 4808 Diag(SubExprs[1]->getBeginLoc(), 4809 diag::warn_atomic_op_has_invalid_memory_order) 4810 << SubExprs[1]->getSourceRange(); 4811 } 4812 4813 if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) { 4814 auto *Scope = Args[Args.size() - 1]; 4815 llvm::APSInt Result(32); 4816 if (Scope->isIntegerConstantExpr(Result, Context) && 4817 !ScopeModel->isValid(Result.getZExtValue())) { 4818 Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope) 4819 << Scope->getSourceRange(); 4820 } 4821 SubExprs.push_back(Scope); 4822 } 4823 4824 AtomicExpr *AE = new (Context) 4825 AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc); 4826 4827 if ((Op == AtomicExpr::AO__c11_atomic_load || 4828 Op == AtomicExpr::AO__c11_atomic_store || 4829 Op == AtomicExpr::AO__opencl_atomic_load || 4830 Op == AtomicExpr::AO__opencl_atomic_store ) && 4831 Context.AtomicUsesUnsupportedLibcall(AE)) 4832 Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib) 4833 << ((Op == AtomicExpr::AO__c11_atomic_load || 4834 Op == AtomicExpr::AO__opencl_atomic_load) 4835 ? 0 4836 : 1); 4837 4838 return AE; 4839 } 4840 4841 /// checkBuiltinArgument - Given a call to a builtin function, perform 4842 /// normal type-checking on the given argument, updating the call in 4843 /// place. This is useful when a builtin function requires custom 4844 /// type-checking for some of its arguments but not necessarily all of 4845 /// them. 4846 /// 4847 /// Returns true on error. 4848 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) { 4849 FunctionDecl *Fn = E->getDirectCallee(); 4850 assert(Fn && "builtin call without direct callee!"); 4851 4852 ParmVarDecl *Param = Fn->getParamDecl(ArgIndex); 4853 InitializedEntity Entity = 4854 InitializedEntity::InitializeParameter(S.Context, Param); 4855 4856 ExprResult Arg = E->getArg(0); 4857 Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg); 4858 if (Arg.isInvalid()) 4859 return true; 4860 4861 E->setArg(ArgIndex, Arg.get()); 4862 return false; 4863 } 4864 4865 /// We have a call to a function like __sync_fetch_and_add, which is an 4866 /// overloaded function based on the pointer type of its first argument. 4867 /// The main BuildCallExpr routines have already promoted the types of 4868 /// arguments because all of these calls are prototyped as void(...). 4869 /// 4870 /// This function goes through and does final semantic checking for these 4871 /// builtins, as well as generating any warnings. 4872 ExprResult 4873 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) { 4874 CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get()); 4875 Expr *Callee = TheCall->getCallee(); 4876 DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts()); 4877 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 4878 4879 // Ensure that we have at least one argument to do type inference from. 4880 if (TheCall->getNumArgs() < 1) { 4881 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 4882 << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange(); 4883 return ExprError(); 4884 } 4885 4886 // Inspect the first argument of the atomic builtin. This should always be 4887 // a pointer type, whose element is an integral scalar or pointer type. 4888 // Because it is a pointer type, we don't have to worry about any implicit 4889 // casts here. 4890 // FIXME: We don't allow floating point scalars as input. 4891 Expr *FirstArg = TheCall->getArg(0); 4892 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg); 4893 if (FirstArgResult.isInvalid()) 4894 return ExprError(); 4895 FirstArg = FirstArgResult.get(); 4896 TheCall->setArg(0, FirstArg); 4897 4898 const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>(); 4899 if (!pointerType) { 4900 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer) 4901 << FirstArg->getType() << FirstArg->getSourceRange(); 4902 return ExprError(); 4903 } 4904 4905 QualType ValType = pointerType->getPointeeType(); 4906 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 4907 !ValType->isBlockPointerType()) { 4908 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr) 4909 << FirstArg->getType() << FirstArg->getSourceRange(); 4910 return ExprError(); 4911 } 4912 4913 if (ValType.isConstQualified()) { 4914 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const) 4915 << FirstArg->getType() << FirstArg->getSourceRange(); 4916 return ExprError(); 4917 } 4918 4919 switch (ValType.getObjCLifetime()) { 4920 case Qualifiers::OCL_None: 4921 case Qualifiers::OCL_ExplicitNone: 4922 // okay 4923 break; 4924 4925 case Qualifiers::OCL_Weak: 4926 case Qualifiers::OCL_Strong: 4927 case Qualifiers::OCL_Autoreleasing: 4928 Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership) 4929 << ValType << FirstArg->getSourceRange(); 4930 return ExprError(); 4931 } 4932 4933 // Strip any qualifiers off ValType. 4934 ValType = ValType.getUnqualifiedType(); 4935 4936 // The majority of builtins return a value, but a few have special return 4937 // types, so allow them to override appropriately below. 4938 QualType ResultType = ValType; 4939 4940 // We need to figure out which concrete builtin this maps onto. For example, 4941 // __sync_fetch_and_add with a 2 byte object turns into 4942 // __sync_fetch_and_add_2. 4943 #define BUILTIN_ROW(x) \ 4944 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \ 4945 Builtin::BI##x##_8, Builtin::BI##x##_16 } 4946 4947 static const unsigned BuiltinIndices[][5] = { 4948 BUILTIN_ROW(__sync_fetch_and_add), 4949 BUILTIN_ROW(__sync_fetch_and_sub), 4950 BUILTIN_ROW(__sync_fetch_and_or), 4951 BUILTIN_ROW(__sync_fetch_and_and), 4952 BUILTIN_ROW(__sync_fetch_and_xor), 4953 BUILTIN_ROW(__sync_fetch_and_nand), 4954 4955 BUILTIN_ROW(__sync_add_and_fetch), 4956 BUILTIN_ROW(__sync_sub_and_fetch), 4957 BUILTIN_ROW(__sync_and_and_fetch), 4958 BUILTIN_ROW(__sync_or_and_fetch), 4959 BUILTIN_ROW(__sync_xor_and_fetch), 4960 BUILTIN_ROW(__sync_nand_and_fetch), 4961 4962 BUILTIN_ROW(__sync_val_compare_and_swap), 4963 BUILTIN_ROW(__sync_bool_compare_and_swap), 4964 BUILTIN_ROW(__sync_lock_test_and_set), 4965 BUILTIN_ROW(__sync_lock_release), 4966 BUILTIN_ROW(__sync_swap) 4967 }; 4968 #undef BUILTIN_ROW 4969 4970 // Determine the index of the size. 4971 unsigned SizeIndex; 4972 switch (Context.getTypeSizeInChars(ValType).getQuantity()) { 4973 case 1: SizeIndex = 0; break; 4974 case 2: SizeIndex = 1; break; 4975 case 4: SizeIndex = 2; break; 4976 case 8: SizeIndex = 3; break; 4977 case 16: SizeIndex = 4; break; 4978 default: 4979 Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size) 4980 << FirstArg->getType() << FirstArg->getSourceRange(); 4981 return ExprError(); 4982 } 4983 4984 // Each of these builtins has one pointer argument, followed by some number of 4985 // values (0, 1 or 2) followed by a potentially empty varags list of stuff 4986 // that we ignore. Find out which row of BuiltinIndices to read from as well 4987 // as the number of fixed args. 4988 unsigned BuiltinID = FDecl->getBuiltinID(); 4989 unsigned BuiltinIndex, NumFixed = 1; 4990 bool WarnAboutSemanticsChange = false; 4991 switch (BuiltinID) { 4992 default: llvm_unreachable("Unknown overloaded atomic builtin!"); 4993 case Builtin::BI__sync_fetch_and_add: 4994 case Builtin::BI__sync_fetch_and_add_1: 4995 case Builtin::BI__sync_fetch_and_add_2: 4996 case Builtin::BI__sync_fetch_and_add_4: 4997 case Builtin::BI__sync_fetch_and_add_8: 4998 case Builtin::BI__sync_fetch_and_add_16: 4999 BuiltinIndex = 0; 5000 break; 5001 5002 case Builtin::BI__sync_fetch_and_sub: 5003 case Builtin::BI__sync_fetch_and_sub_1: 5004 case Builtin::BI__sync_fetch_and_sub_2: 5005 case Builtin::BI__sync_fetch_and_sub_4: 5006 case Builtin::BI__sync_fetch_and_sub_8: 5007 case Builtin::BI__sync_fetch_and_sub_16: 5008 BuiltinIndex = 1; 5009 break; 5010 5011 case Builtin::BI__sync_fetch_and_or: 5012 case Builtin::BI__sync_fetch_and_or_1: 5013 case Builtin::BI__sync_fetch_and_or_2: 5014 case Builtin::BI__sync_fetch_and_or_4: 5015 case Builtin::BI__sync_fetch_and_or_8: 5016 case Builtin::BI__sync_fetch_and_or_16: 5017 BuiltinIndex = 2; 5018 break; 5019 5020 case Builtin::BI__sync_fetch_and_and: 5021 case Builtin::BI__sync_fetch_and_and_1: 5022 case Builtin::BI__sync_fetch_and_and_2: 5023 case Builtin::BI__sync_fetch_and_and_4: 5024 case Builtin::BI__sync_fetch_and_and_8: 5025 case Builtin::BI__sync_fetch_and_and_16: 5026 BuiltinIndex = 3; 5027 break; 5028 5029 case Builtin::BI__sync_fetch_and_xor: 5030 case Builtin::BI__sync_fetch_and_xor_1: 5031 case Builtin::BI__sync_fetch_and_xor_2: 5032 case Builtin::BI__sync_fetch_and_xor_4: 5033 case Builtin::BI__sync_fetch_and_xor_8: 5034 case Builtin::BI__sync_fetch_and_xor_16: 5035 BuiltinIndex = 4; 5036 break; 5037 5038 case Builtin::BI__sync_fetch_and_nand: 5039 case Builtin::BI__sync_fetch_and_nand_1: 5040 case Builtin::BI__sync_fetch_and_nand_2: 5041 case Builtin::BI__sync_fetch_and_nand_4: 5042 case Builtin::BI__sync_fetch_and_nand_8: 5043 case Builtin::BI__sync_fetch_and_nand_16: 5044 BuiltinIndex = 5; 5045 WarnAboutSemanticsChange = true; 5046 break; 5047 5048 case Builtin::BI__sync_add_and_fetch: 5049 case Builtin::BI__sync_add_and_fetch_1: 5050 case Builtin::BI__sync_add_and_fetch_2: 5051 case Builtin::BI__sync_add_and_fetch_4: 5052 case Builtin::BI__sync_add_and_fetch_8: 5053 case Builtin::BI__sync_add_and_fetch_16: 5054 BuiltinIndex = 6; 5055 break; 5056 5057 case Builtin::BI__sync_sub_and_fetch: 5058 case Builtin::BI__sync_sub_and_fetch_1: 5059 case Builtin::BI__sync_sub_and_fetch_2: 5060 case Builtin::BI__sync_sub_and_fetch_4: 5061 case Builtin::BI__sync_sub_and_fetch_8: 5062 case Builtin::BI__sync_sub_and_fetch_16: 5063 BuiltinIndex = 7; 5064 break; 5065 5066 case Builtin::BI__sync_and_and_fetch: 5067 case Builtin::BI__sync_and_and_fetch_1: 5068 case Builtin::BI__sync_and_and_fetch_2: 5069 case Builtin::BI__sync_and_and_fetch_4: 5070 case Builtin::BI__sync_and_and_fetch_8: 5071 case Builtin::BI__sync_and_and_fetch_16: 5072 BuiltinIndex = 8; 5073 break; 5074 5075 case Builtin::BI__sync_or_and_fetch: 5076 case Builtin::BI__sync_or_and_fetch_1: 5077 case Builtin::BI__sync_or_and_fetch_2: 5078 case Builtin::BI__sync_or_and_fetch_4: 5079 case Builtin::BI__sync_or_and_fetch_8: 5080 case Builtin::BI__sync_or_and_fetch_16: 5081 BuiltinIndex = 9; 5082 break; 5083 5084 case Builtin::BI__sync_xor_and_fetch: 5085 case Builtin::BI__sync_xor_and_fetch_1: 5086 case Builtin::BI__sync_xor_and_fetch_2: 5087 case Builtin::BI__sync_xor_and_fetch_4: 5088 case Builtin::BI__sync_xor_and_fetch_8: 5089 case Builtin::BI__sync_xor_and_fetch_16: 5090 BuiltinIndex = 10; 5091 break; 5092 5093 case Builtin::BI__sync_nand_and_fetch: 5094 case Builtin::BI__sync_nand_and_fetch_1: 5095 case Builtin::BI__sync_nand_and_fetch_2: 5096 case Builtin::BI__sync_nand_and_fetch_4: 5097 case Builtin::BI__sync_nand_and_fetch_8: 5098 case Builtin::BI__sync_nand_and_fetch_16: 5099 BuiltinIndex = 11; 5100 WarnAboutSemanticsChange = true; 5101 break; 5102 5103 case Builtin::BI__sync_val_compare_and_swap: 5104 case Builtin::BI__sync_val_compare_and_swap_1: 5105 case Builtin::BI__sync_val_compare_and_swap_2: 5106 case Builtin::BI__sync_val_compare_and_swap_4: 5107 case Builtin::BI__sync_val_compare_and_swap_8: 5108 case Builtin::BI__sync_val_compare_and_swap_16: 5109 BuiltinIndex = 12; 5110 NumFixed = 2; 5111 break; 5112 5113 case Builtin::BI__sync_bool_compare_and_swap: 5114 case Builtin::BI__sync_bool_compare_and_swap_1: 5115 case Builtin::BI__sync_bool_compare_and_swap_2: 5116 case Builtin::BI__sync_bool_compare_and_swap_4: 5117 case Builtin::BI__sync_bool_compare_and_swap_8: 5118 case Builtin::BI__sync_bool_compare_and_swap_16: 5119 BuiltinIndex = 13; 5120 NumFixed = 2; 5121 ResultType = Context.BoolTy; 5122 break; 5123 5124 case Builtin::BI__sync_lock_test_and_set: 5125 case Builtin::BI__sync_lock_test_and_set_1: 5126 case Builtin::BI__sync_lock_test_and_set_2: 5127 case Builtin::BI__sync_lock_test_and_set_4: 5128 case Builtin::BI__sync_lock_test_and_set_8: 5129 case Builtin::BI__sync_lock_test_and_set_16: 5130 BuiltinIndex = 14; 5131 break; 5132 5133 case Builtin::BI__sync_lock_release: 5134 case Builtin::BI__sync_lock_release_1: 5135 case Builtin::BI__sync_lock_release_2: 5136 case Builtin::BI__sync_lock_release_4: 5137 case Builtin::BI__sync_lock_release_8: 5138 case Builtin::BI__sync_lock_release_16: 5139 BuiltinIndex = 15; 5140 NumFixed = 0; 5141 ResultType = Context.VoidTy; 5142 break; 5143 5144 case Builtin::BI__sync_swap: 5145 case Builtin::BI__sync_swap_1: 5146 case Builtin::BI__sync_swap_2: 5147 case Builtin::BI__sync_swap_4: 5148 case Builtin::BI__sync_swap_8: 5149 case Builtin::BI__sync_swap_16: 5150 BuiltinIndex = 16; 5151 break; 5152 } 5153 5154 // Now that we know how many fixed arguments we expect, first check that we 5155 // have at least that many. 5156 if (TheCall->getNumArgs() < 1+NumFixed) { 5157 Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least) 5158 << 0 << 1 + NumFixed << TheCall->getNumArgs() 5159 << Callee->getSourceRange(); 5160 return ExprError(); 5161 } 5162 5163 Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst) 5164 << Callee->getSourceRange(); 5165 5166 if (WarnAboutSemanticsChange) { 5167 Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change) 5168 << Callee->getSourceRange(); 5169 } 5170 5171 // Get the decl for the concrete builtin from this, we can tell what the 5172 // concrete integer type we should convert to is. 5173 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex]; 5174 const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID); 5175 FunctionDecl *NewBuiltinDecl; 5176 if (NewBuiltinID == BuiltinID) 5177 NewBuiltinDecl = FDecl; 5178 else { 5179 // Perform builtin lookup to avoid redeclaring it. 5180 DeclarationName DN(&Context.Idents.get(NewBuiltinName)); 5181 LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName); 5182 LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true); 5183 assert(Res.getFoundDecl()); 5184 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl()); 5185 if (!NewBuiltinDecl) 5186 return ExprError(); 5187 } 5188 5189 // The first argument --- the pointer --- has a fixed type; we 5190 // deduce the types of the rest of the arguments accordingly. Walk 5191 // the remaining arguments, converting them to the deduced value type. 5192 for (unsigned i = 0; i != NumFixed; ++i) { 5193 ExprResult Arg = TheCall->getArg(i+1); 5194 5195 // GCC does an implicit conversion to the pointer or integer ValType. This 5196 // can fail in some cases (1i -> int**), check for this error case now. 5197 // Initialize the argument. 5198 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5199 ValType, /*consume*/ false); 5200 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5201 if (Arg.isInvalid()) 5202 return ExprError(); 5203 5204 // Okay, we have something that *can* be converted to the right type. Check 5205 // to see if there is a potentially weird extension going on here. This can 5206 // happen when you do an atomic operation on something like an char* and 5207 // pass in 42. The 42 gets converted to char. This is even more strange 5208 // for things like 45.123 -> char, etc. 5209 // FIXME: Do this check. 5210 TheCall->setArg(i+1, Arg.get()); 5211 } 5212 5213 // Create a new DeclRefExpr to refer to the new decl. 5214 DeclRefExpr *NewDRE = DeclRefExpr::Create( 5215 Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl, 5216 /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy, 5217 DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse()); 5218 5219 // Set the callee in the CallExpr. 5220 // FIXME: This loses syntactic information. 5221 QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType()); 5222 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy, 5223 CK_BuiltinFnToFnPtr); 5224 TheCall->setCallee(PromotedCall.get()); 5225 5226 // Change the result type of the call to match the original value type. This 5227 // is arbitrary, but the codegen for these builtins ins design to handle it 5228 // gracefully. 5229 TheCall->setType(ResultType); 5230 5231 return TheCallResult; 5232 } 5233 5234 /// SemaBuiltinNontemporalOverloaded - We have a call to 5235 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an 5236 /// overloaded function based on the pointer type of its last argument. 5237 /// 5238 /// This function goes through and does final semantic checking for these 5239 /// builtins. 5240 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) { 5241 CallExpr *TheCall = (CallExpr *)TheCallResult.get(); 5242 DeclRefExpr *DRE = 5243 cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 5244 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 5245 unsigned BuiltinID = FDecl->getBuiltinID(); 5246 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store || 5247 BuiltinID == Builtin::BI__builtin_nontemporal_load) && 5248 "Unexpected nontemporal load/store builtin!"); 5249 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store; 5250 unsigned numArgs = isStore ? 2 : 1; 5251 5252 // Ensure that we have the proper number of arguments. 5253 if (checkArgCount(*this, TheCall, numArgs)) 5254 return ExprError(); 5255 5256 // Inspect the last argument of the nontemporal builtin. This should always 5257 // be a pointer type, from which we imply the type of the memory access. 5258 // Because it is a pointer type, we don't have to worry about any implicit 5259 // casts here. 5260 Expr *PointerArg = TheCall->getArg(numArgs - 1); 5261 ExprResult PointerArgResult = 5262 DefaultFunctionArrayLvalueConversion(PointerArg); 5263 5264 if (PointerArgResult.isInvalid()) 5265 return ExprError(); 5266 PointerArg = PointerArgResult.get(); 5267 TheCall->setArg(numArgs - 1, PointerArg); 5268 5269 const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>(); 5270 if (!pointerType) { 5271 Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer) 5272 << PointerArg->getType() << PointerArg->getSourceRange(); 5273 return ExprError(); 5274 } 5275 5276 QualType ValType = pointerType->getPointeeType(); 5277 5278 // Strip any qualifiers off ValType. 5279 ValType = ValType.getUnqualifiedType(); 5280 if (!ValType->isIntegerType() && !ValType->isAnyPointerType() && 5281 !ValType->isBlockPointerType() && !ValType->isFloatingType() && 5282 !ValType->isVectorType()) { 5283 Diag(DRE->getBeginLoc(), 5284 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector) 5285 << PointerArg->getType() << PointerArg->getSourceRange(); 5286 return ExprError(); 5287 } 5288 5289 if (!isStore) { 5290 TheCall->setType(ValType); 5291 return TheCallResult; 5292 } 5293 5294 ExprResult ValArg = TheCall->getArg(0); 5295 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5296 Context, ValType, /*consume*/ false); 5297 ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg); 5298 if (ValArg.isInvalid()) 5299 return ExprError(); 5300 5301 TheCall->setArg(0, ValArg.get()); 5302 TheCall->setType(Context.VoidTy); 5303 return TheCallResult; 5304 } 5305 5306 /// CheckObjCString - Checks that the argument to the builtin 5307 /// CFString constructor is correct 5308 /// Note: It might also make sense to do the UTF-16 conversion here (would 5309 /// simplify the backend). 5310 bool Sema::CheckObjCString(Expr *Arg) { 5311 Arg = Arg->IgnoreParenCasts(); 5312 StringLiteral *Literal = dyn_cast<StringLiteral>(Arg); 5313 5314 if (!Literal || !Literal->isAscii()) { 5315 Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant) 5316 << Arg->getSourceRange(); 5317 return true; 5318 } 5319 5320 if (Literal->containsNonAsciiOrNull()) { 5321 StringRef String = Literal->getString(); 5322 unsigned NumBytes = String.size(); 5323 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes); 5324 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 5325 llvm::UTF16 *ToPtr = &ToBuf[0]; 5326 5327 llvm::ConversionResult Result = 5328 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 5329 ToPtr + NumBytes, llvm::strictConversion); 5330 // Check for conversion failure. 5331 if (Result != llvm::conversionOK) 5332 Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated) 5333 << Arg->getSourceRange(); 5334 } 5335 return false; 5336 } 5337 5338 /// CheckObjCString - Checks that the format string argument to the os_log() 5339 /// and os_trace() functions is correct, and converts it to const char *. 5340 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) { 5341 Arg = Arg->IgnoreParenCasts(); 5342 auto *Literal = dyn_cast<StringLiteral>(Arg); 5343 if (!Literal) { 5344 if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) { 5345 Literal = ObjcLiteral->getString(); 5346 } 5347 } 5348 5349 if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) { 5350 return ExprError( 5351 Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant) 5352 << Arg->getSourceRange()); 5353 } 5354 5355 ExprResult Result(Literal); 5356 QualType ResultTy = Context.getPointerType(Context.CharTy.withConst()); 5357 InitializedEntity Entity = 5358 InitializedEntity::InitializeParameter(Context, ResultTy, false); 5359 Result = PerformCopyInitialization(Entity, SourceLocation(), Result); 5360 return Result; 5361 } 5362 5363 /// Check that the user is calling the appropriate va_start builtin for the 5364 /// target and calling convention. 5365 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) { 5366 const llvm::Triple &TT = S.Context.getTargetInfo().getTriple(); 5367 bool IsX64 = TT.getArch() == llvm::Triple::x86_64; 5368 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 || 5369 TT.getArch() == llvm::Triple::aarch64_32); 5370 bool IsWindows = TT.isOSWindows(); 5371 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start; 5372 if (IsX64 || IsAArch64) { 5373 CallingConv CC = CC_C; 5374 if (const FunctionDecl *FD = S.getCurFunctionDecl()) 5375 CC = FD->getType()->castAs<FunctionType>()->getCallConv(); 5376 if (IsMSVAStart) { 5377 // Don't allow this in System V ABI functions. 5378 if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64)) 5379 return S.Diag(Fn->getBeginLoc(), 5380 diag::err_ms_va_start_used_in_sysv_function); 5381 } else { 5382 // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions. 5383 // On x64 Windows, don't allow this in System V ABI functions. 5384 // (Yes, that means there's no corresponding way to support variadic 5385 // System V ABI functions on Windows.) 5386 if ((IsWindows && CC == CC_X86_64SysV) || 5387 (!IsWindows && CC == CC_Win64)) 5388 return S.Diag(Fn->getBeginLoc(), 5389 diag::err_va_start_used_in_wrong_abi_function) 5390 << !IsWindows; 5391 } 5392 return false; 5393 } 5394 5395 if (IsMSVAStart) 5396 return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only); 5397 return false; 5398 } 5399 5400 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, 5401 ParmVarDecl **LastParam = nullptr) { 5402 // Determine whether the current function, block, or obj-c method is variadic 5403 // and get its parameter list. 5404 bool IsVariadic = false; 5405 ArrayRef<ParmVarDecl *> Params; 5406 DeclContext *Caller = S.CurContext; 5407 if (auto *Block = dyn_cast<BlockDecl>(Caller)) { 5408 IsVariadic = Block->isVariadic(); 5409 Params = Block->parameters(); 5410 } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) { 5411 IsVariadic = FD->isVariadic(); 5412 Params = FD->parameters(); 5413 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) { 5414 IsVariadic = MD->isVariadic(); 5415 // FIXME: This isn't correct for methods (results in bogus warning). 5416 Params = MD->parameters(); 5417 } else if (isa<CapturedDecl>(Caller)) { 5418 // We don't support va_start in a CapturedDecl. 5419 S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt); 5420 return true; 5421 } else { 5422 // This must be some other declcontext that parses exprs. 5423 S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function); 5424 return true; 5425 } 5426 5427 if (!IsVariadic) { 5428 S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function); 5429 return true; 5430 } 5431 5432 if (LastParam) 5433 *LastParam = Params.empty() ? nullptr : Params.back(); 5434 5435 return false; 5436 } 5437 5438 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start' 5439 /// for validity. Emit an error and return true on failure; return false 5440 /// on success. 5441 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) { 5442 Expr *Fn = TheCall->getCallee(); 5443 5444 if (checkVAStartABI(*this, BuiltinID, Fn)) 5445 return true; 5446 5447 if (TheCall->getNumArgs() > 2) { 5448 Diag(TheCall->getArg(2)->getBeginLoc(), 5449 diag::err_typecheck_call_too_many_args) 5450 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5451 << Fn->getSourceRange() 5452 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5453 (*(TheCall->arg_end() - 1))->getEndLoc()); 5454 return true; 5455 } 5456 5457 if (TheCall->getNumArgs() < 2) { 5458 return Diag(TheCall->getEndLoc(), 5459 diag::err_typecheck_call_too_few_args_at_least) 5460 << 0 /*function call*/ << 2 << TheCall->getNumArgs(); 5461 } 5462 5463 // Type-check the first argument normally. 5464 if (checkBuiltinArgument(*this, TheCall, 0)) 5465 return true; 5466 5467 // Check that the current function is variadic, and get its last parameter. 5468 ParmVarDecl *LastParam; 5469 if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam)) 5470 return true; 5471 5472 // Verify that the second argument to the builtin is the last argument of the 5473 // current function or method. 5474 bool SecondArgIsLastNamedArgument = false; 5475 const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts(); 5476 5477 // These are valid if SecondArgIsLastNamedArgument is false after the next 5478 // block. 5479 QualType Type; 5480 SourceLocation ParamLoc; 5481 bool IsCRegister = false; 5482 5483 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) { 5484 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) { 5485 SecondArgIsLastNamedArgument = PV == LastParam; 5486 5487 Type = PV->getType(); 5488 ParamLoc = PV->getLocation(); 5489 IsCRegister = 5490 PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus; 5491 } 5492 } 5493 5494 if (!SecondArgIsLastNamedArgument) 5495 Diag(TheCall->getArg(1)->getBeginLoc(), 5496 diag::warn_second_arg_of_va_start_not_last_named_param); 5497 else if (IsCRegister || Type->isReferenceType() || 5498 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] { 5499 // Promotable integers are UB, but enumerations need a bit of 5500 // extra checking to see what their promotable type actually is. 5501 if (!Type->isPromotableIntegerType()) 5502 return false; 5503 if (!Type->isEnumeralType()) 5504 return true; 5505 const EnumDecl *ED = Type->castAs<EnumType>()->getDecl(); 5506 return !(ED && 5507 Context.typesAreCompatible(ED->getPromotionType(), Type)); 5508 }()) { 5509 unsigned Reason = 0; 5510 if (Type->isReferenceType()) Reason = 1; 5511 else if (IsCRegister) Reason = 2; 5512 Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason; 5513 Diag(ParamLoc, diag::note_parameter_type) << Type; 5514 } 5515 5516 TheCall->setType(Context.VoidTy); 5517 return false; 5518 } 5519 5520 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) { 5521 // void __va_start(va_list *ap, const char *named_addr, size_t slot_size, 5522 // const char *named_addr); 5523 5524 Expr *Func = Call->getCallee(); 5525 5526 if (Call->getNumArgs() < 3) 5527 return Diag(Call->getEndLoc(), 5528 diag::err_typecheck_call_too_few_args_at_least) 5529 << 0 /*function call*/ << 3 << Call->getNumArgs(); 5530 5531 // Type-check the first argument normally. 5532 if (checkBuiltinArgument(*this, Call, 0)) 5533 return true; 5534 5535 // Check that the current function is variadic. 5536 if (checkVAStartIsInVariadicFunction(*this, Func)) 5537 return true; 5538 5539 // __va_start on Windows does not validate the parameter qualifiers 5540 5541 const Expr *Arg1 = Call->getArg(1)->IgnoreParens(); 5542 const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr(); 5543 5544 const Expr *Arg2 = Call->getArg(2)->IgnoreParens(); 5545 const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr(); 5546 5547 const QualType &ConstCharPtrTy = 5548 Context.getPointerType(Context.CharTy.withConst()); 5549 if (!Arg1Ty->isPointerType() || 5550 Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy) 5551 Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5552 << Arg1->getType() << ConstCharPtrTy << 1 /* different class */ 5553 << 0 /* qualifier difference */ 5554 << 3 /* parameter mismatch */ 5555 << 2 << Arg1->getType() << ConstCharPtrTy; 5556 5557 const QualType SizeTy = Context.getSizeType(); 5558 if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy) 5559 Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible) 5560 << Arg2->getType() << SizeTy << 1 /* different class */ 5561 << 0 /* qualifier difference */ 5562 << 3 /* parameter mismatch */ 5563 << 3 << Arg2->getType() << SizeTy; 5564 5565 return false; 5566 } 5567 5568 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and 5569 /// friends. This is declared to take (...), so we have to check everything. 5570 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) { 5571 if (TheCall->getNumArgs() < 2) 5572 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5573 << 0 << 2 << TheCall->getNumArgs() /*function call*/; 5574 if (TheCall->getNumArgs() > 2) 5575 return Diag(TheCall->getArg(2)->getBeginLoc(), 5576 diag::err_typecheck_call_too_many_args) 5577 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5578 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5579 (*(TheCall->arg_end() - 1))->getEndLoc()); 5580 5581 ExprResult OrigArg0 = TheCall->getArg(0); 5582 ExprResult OrigArg1 = TheCall->getArg(1); 5583 5584 // Do standard promotions between the two arguments, returning their common 5585 // type. 5586 QualType Res = UsualArithmeticConversions( 5587 OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison); 5588 if (OrigArg0.isInvalid() || OrigArg1.isInvalid()) 5589 return true; 5590 5591 // Make sure any conversions are pushed back into the call; this is 5592 // type safe since unordered compare builtins are declared as "_Bool 5593 // foo(...)". 5594 TheCall->setArg(0, OrigArg0.get()); 5595 TheCall->setArg(1, OrigArg1.get()); 5596 5597 if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent()) 5598 return false; 5599 5600 // If the common type isn't a real floating type, then the arguments were 5601 // invalid for this operation. 5602 if (Res.isNull() || !Res->isRealFloatingType()) 5603 return Diag(OrigArg0.get()->getBeginLoc(), 5604 diag::err_typecheck_call_invalid_ordered_compare) 5605 << OrigArg0.get()->getType() << OrigArg1.get()->getType() 5606 << SourceRange(OrigArg0.get()->getBeginLoc(), 5607 OrigArg1.get()->getEndLoc()); 5608 5609 return false; 5610 } 5611 5612 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like 5613 /// __builtin_isnan and friends. This is declared to take (...), so we have 5614 /// to check everything. We expect the last argument to be a floating point 5615 /// value. 5616 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) { 5617 if (TheCall->getNumArgs() < NumArgs) 5618 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5619 << 0 << NumArgs << TheCall->getNumArgs() /*function call*/; 5620 if (TheCall->getNumArgs() > NumArgs) 5621 return Diag(TheCall->getArg(NumArgs)->getBeginLoc(), 5622 diag::err_typecheck_call_too_many_args) 5623 << 0 /*function call*/ << NumArgs << TheCall->getNumArgs() 5624 << SourceRange(TheCall->getArg(NumArgs)->getBeginLoc(), 5625 (*(TheCall->arg_end() - 1))->getEndLoc()); 5626 5627 // __builtin_fpclassify is the only case where NumArgs != 1, so we can count 5628 // on all preceding parameters just being int. Try all of those. 5629 for (unsigned i = 0; i < NumArgs - 1; ++i) { 5630 Expr *Arg = TheCall->getArg(i); 5631 5632 if (Arg->isTypeDependent()) 5633 return false; 5634 5635 ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing); 5636 5637 if (Res.isInvalid()) 5638 return true; 5639 TheCall->setArg(i, Res.get()); 5640 } 5641 5642 Expr *OrigArg = TheCall->getArg(NumArgs-1); 5643 5644 if (OrigArg->isTypeDependent()) 5645 return false; 5646 5647 // Usual Unary Conversions will convert half to float, which we want for 5648 // machines that use fp16 conversion intrinsics. Else, we wnat to leave the 5649 // type how it is, but do normal L->Rvalue conversions. 5650 if (Context.getTargetInfo().useFP16ConversionIntrinsics()) 5651 OrigArg = UsualUnaryConversions(OrigArg).get(); 5652 else 5653 OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get(); 5654 TheCall->setArg(NumArgs - 1, OrigArg); 5655 5656 // This operation requires a non-_Complex floating-point number. 5657 if (!OrigArg->getType()->isRealFloatingType()) 5658 return Diag(OrigArg->getBeginLoc(), 5659 diag::err_typecheck_call_invalid_unary_fp) 5660 << OrigArg->getType() << OrigArg->getSourceRange(); 5661 5662 return false; 5663 } 5664 5665 // Customized Sema Checking for VSX builtins that have the following signature: 5666 // vector [...] builtinName(vector [...], vector [...], const int); 5667 // Which takes the same type of vectors (any legal vector type) for the first 5668 // two arguments and takes compile time constant for the third argument. 5669 // Example builtins are : 5670 // vector double vec_xxpermdi(vector double, vector double, int); 5671 // vector short vec_xxsldwi(vector short, vector short, int); 5672 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) { 5673 unsigned ExpectedNumArgs = 3; 5674 if (TheCall->getNumArgs() < ExpectedNumArgs) 5675 return Diag(TheCall->getEndLoc(), 5676 diag::err_typecheck_call_too_few_args_at_least) 5677 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5678 << TheCall->getSourceRange(); 5679 5680 if (TheCall->getNumArgs() > ExpectedNumArgs) 5681 return Diag(TheCall->getEndLoc(), 5682 diag::err_typecheck_call_too_many_args_at_most) 5683 << 0 /*function call*/ << ExpectedNumArgs << TheCall->getNumArgs() 5684 << TheCall->getSourceRange(); 5685 5686 // Check the third argument is a compile time constant 5687 llvm::APSInt Value; 5688 if(!TheCall->getArg(2)->isIntegerConstantExpr(Value, Context)) 5689 return Diag(TheCall->getBeginLoc(), 5690 diag::err_vsx_builtin_nonconstant_argument) 5691 << 3 /* argument index */ << TheCall->getDirectCallee() 5692 << SourceRange(TheCall->getArg(2)->getBeginLoc(), 5693 TheCall->getArg(2)->getEndLoc()); 5694 5695 QualType Arg1Ty = TheCall->getArg(0)->getType(); 5696 QualType Arg2Ty = TheCall->getArg(1)->getType(); 5697 5698 // Check the type of argument 1 and argument 2 are vectors. 5699 SourceLocation BuiltinLoc = TheCall->getBeginLoc(); 5700 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) || 5701 (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) { 5702 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector) 5703 << TheCall->getDirectCallee() 5704 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5705 TheCall->getArg(1)->getEndLoc()); 5706 } 5707 5708 // Check the first two arguments are the same type. 5709 if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) { 5710 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector) 5711 << TheCall->getDirectCallee() 5712 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5713 TheCall->getArg(1)->getEndLoc()); 5714 } 5715 5716 // When default clang type checking is turned off and the customized type 5717 // checking is used, the returning type of the function must be explicitly 5718 // set. Otherwise it is _Bool by default. 5719 TheCall->setType(Arg1Ty); 5720 5721 return false; 5722 } 5723 5724 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector. 5725 // This is declared to take (...), so we have to check everything. 5726 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) { 5727 if (TheCall->getNumArgs() < 2) 5728 return ExprError(Diag(TheCall->getEndLoc(), 5729 diag::err_typecheck_call_too_few_args_at_least) 5730 << 0 /*function call*/ << 2 << TheCall->getNumArgs() 5731 << TheCall->getSourceRange()); 5732 5733 // Determine which of the following types of shufflevector we're checking: 5734 // 1) unary, vector mask: (lhs, mask) 5735 // 2) binary, scalar mask: (lhs, rhs, index, ..., index) 5736 QualType resType = TheCall->getArg(0)->getType(); 5737 unsigned numElements = 0; 5738 5739 if (!TheCall->getArg(0)->isTypeDependent() && 5740 !TheCall->getArg(1)->isTypeDependent()) { 5741 QualType LHSType = TheCall->getArg(0)->getType(); 5742 QualType RHSType = TheCall->getArg(1)->getType(); 5743 5744 if (!LHSType->isVectorType() || !RHSType->isVectorType()) 5745 return ExprError( 5746 Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector) 5747 << TheCall->getDirectCallee() 5748 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5749 TheCall->getArg(1)->getEndLoc())); 5750 5751 numElements = LHSType->castAs<VectorType>()->getNumElements(); 5752 unsigned numResElements = TheCall->getNumArgs() - 2; 5753 5754 // Check to see if we have a call with 2 vector arguments, the unary shuffle 5755 // with mask. If so, verify that RHS is an integer vector type with the 5756 // same number of elts as lhs. 5757 if (TheCall->getNumArgs() == 2) { 5758 if (!RHSType->hasIntegerRepresentation() || 5759 RHSType->castAs<VectorType>()->getNumElements() != numElements) 5760 return ExprError(Diag(TheCall->getBeginLoc(), 5761 diag::err_vec_builtin_incompatible_vector) 5762 << TheCall->getDirectCallee() 5763 << SourceRange(TheCall->getArg(1)->getBeginLoc(), 5764 TheCall->getArg(1)->getEndLoc())); 5765 } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) { 5766 return ExprError(Diag(TheCall->getBeginLoc(), 5767 diag::err_vec_builtin_incompatible_vector) 5768 << TheCall->getDirectCallee() 5769 << SourceRange(TheCall->getArg(0)->getBeginLoc(), 5770 TheCall->getArg(1)->getEndLoc())); 5771 } else if (numElements != numResElements) { 5772 QualType eltType = LHSType->castAs<VectorType>()->getElementType(); 5773 resType = Context.getVectorType(eltType, numResElements, 5774 VectorType::GenericVector); 5775 } 5776 } 5777 5778 for (unsigned i = 2; i < TheCall->getNumArgs(); i++) { 5779 if (TheCall->getArg(i)->isTypeDependent() || 5780 TheCall->getArg(i)->isValueDependent()) 5781 continue; 5782 5783 llvm::APSInt Result(32); 5784 if (!TheCall->getArg(i)->isIntegerConstantExpr(Result, Context)) 5785 return ExprError(Diag(TheCall->getBeginLoc(), 5786 diag::err_shufflevector_nonconstant_argument) 5787 << TheCall->getArg(i)->getSourceRange()); 5788 5789 // Allow -1 which will be translated to undef in the IR. 5790 if (Result.isSigned() && Result.isAllOnesValue()) 5791 continue; 5792 5793 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2) 5794 return ExprError(Diag(TheCall->getBeginLoc(), 5795 diag::err_shufflevector_argument_too_large) 5796 << TheCall->getArg(i)->getSourceRange()); 5797 } 5798 5799 SmallVector<Expr*, 32> exprs; 5800 5801 for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) { 5802 exprs.push_back(TheCall->getArg(i)); 5803 TheCall->setArg(i, nullptr); 5804 } 5805 5806 return new (Context) ShuffleVectorExpr(Context, exprs, resType, 5807 TheCall->getCallee()->getBeginLoc(), 5808 TheCall->getRParenLoc()); 5809 } 5810 5811 /// SemaConvertVectorExpr - Handle __builtin_convertvector 5812 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, 5813 SourceLocation BuiltinLoc, 5814 SourceLocation RParenLoc) { 5815 ExprValueKind VK = VK_RValue; 5816 ExprObjectKind OK = OK_Ordinary; 5817 QualType DstTy = TInfo->getType(); 5818 QualType SrcTy = E->getType(); 5819 5820 if (!SrcTy->isVectorType() && !SrcTy->isDependentType()) 5821 return ExprError(Diag(BuiltinLoc, 5822 diag::err_convertvector_non_vector) 5823 << E->getSourceRange()); 5824 if (!DstTy->isVectorType() && !DstTy->isDependentType()) 5825 return ExprError(Diag(BuiltinLoc, 5826 diag::err_convertvector_non_vector_type)); 5827 5828 if (!SrcTy->isDependentType() && !DstTy->isDependentType()) { 5829 unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements(); 5830 unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements(); 5831 if (SrcElts != DstElts) 5832 return ExprError(Diag(BuiltinLoc, 5833 diag::err_convertvector_incompatible_vector) 5834 << E->getSourceRange()); 5835 } 5836 5837 return new (Context) 5838 ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc); 5839 } 5840 5841 /// SemaBuiltinPrefetch - Handle __builtin_prefetch. 5842 // This is declared to take (const void*, ...) and can take two 5843 // optional constant int args. 5844 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) { 5845 unsigned NumArgs = TheCall->getNumArgs(); 5846 5847 if (NumArgs > 3) 5848 return Diag(TheCall->getEndLoc(), 5849 diag::err_typecheck_call_too_many_args_at_most) 5850 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5851 5852 // Argument 0 is checked for us and the remaining arguments must be 5853 // constant integers. 5854 for (unsigned i = 1; i != NumArgs; ++i) 5855 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3)) 5856 return true; 5857 5858 return false; 5859 } 5860 5861 /// SemaBuiltinAssume - Handle __assume (MS Extension). 5862 // __assume does not evaluate its arguments, and should warn if its argument 5863 // has side effects. 5864 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) { 5865 Expr *Arg = TheCall->getArg(0); 5866 if (Arg->isInstantiationDependent()) return false; 5867 5868 if (Arg->HasSideEffects(Context)) 5869 Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects) 5870 << Arg->getSourceRange() 5871 << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier(); 5872 5873 return false; 5874 } 5875 5876 /// Handle __builtin_alloca_with_align. This is declared 5877 /// as (size_t, size_t) where the second size_t must be a power of 2 greater 5878 /// than 8. 5879 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) { 5880 // The alignment must be a constant integer. 5881 Expr *Arg = TheCall->getArg(1); 5882 5883 // We can't check the value of a dependent argument. 5884 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5885 if (const auto *UE = 5886 dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts())) 5887 if (UE->getKind() == UETT_AlignOf || 5888 UE->getKind() == UETT_PreferredAlignOf) 5889 Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof) 5890 << Arg->getSourceRange(); 5891 5892 llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context); 5893 5894 if (!Result.isPowerOf2()) 5895 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5896 << Arg->getSourceRange(); 5897 5898 if (Result < Context.getCharWidth()) 5899 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small) 5900 << (unsigned)Context.getCharWidth() << Arg->getSourceRange(); 5901 5902 if (Result > std::numeric_limits<int32_t>::max()) 5903 return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big) 5904 << std::numeric_limits<int32_t>::max() << Arg->getSourceRange(); 5905 } 5906 5907 return false; 5908 } 5909 5910 /// Handle __builtin_assume_aligned. This is declared 5911 /// as (const void*, size_t, ...) and can take one optional constant int arg. 5912 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) { 5913 unsigned NumArgs = TheCall->getNumArgs(); 5914 5915 if (NumArgs > 3) 5916 return Diag(TheCall->getEndLoc(), 5917 diag::err_typecheck_call_too_many_args_at_most) 5918 << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange(); 5919 5920 // The alignment must be a constant integer. 5921 Expr *Arg = TheCall->getArg(1); 5922 5923 // We can't check the value of a dependent argument. 5924 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 5925 llvm::APSInt Result; 5926 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 5927 return true; 5928 5929 if (!Result.isPowerOf2()) 5930 return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two) 5931 << Arg->getSourceRange(); 5932 5933 if (Result > Sema::MaximumAlignment) 5934 Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great) 5935 << Arg->getSourceRange() << Sema::MaximumAlignment; 5936 } 5937 5938 if (NumArgs > 2) { 5939 ExprResult Arg(TheCall->getArg(2)); 5940 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, 5941 Context.getSizeType(), false); 5942 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5943 if (Arg.isInvalid()) return true; 5944 TheCall->setArg(2, Arg.get()); 5945 } 5946 5947 return false; 5948 } 5949 5950 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) { 5951 unsigned BuiltinID = 5952 cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID(); 5953 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size; 5954 5955 unsigned NumArgs = TheCall->getNumArgs(); 5956 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2; 5957 if (NumArgs < NumRequiredArgs) { 5958 return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args) 5959 << 0 /* function call */ << NumRequiredArgs << NumArgs 5960 << TheCall->getSourceRange(); 5961 } 5962 if (NumArgs >= NumRequiredArgs + 0x100) { 5963 return Diag(TheCall->getEndLoc(), 5964 diag::err_typecheck_call_too_many_args_at_most) 5965 << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs 5966 << TheCall->getSourceRange(); 5967 } 5968 unsigned i = 0; 5969 5970 // For formatting call, check buffer arg. 5971 if (!IsSizeCall) { 5972 ExprResult Arg(TheCall->getArg(i)); 5973 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5974 Context, Context.VoidPtrTy, false); 5975 Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg); 5976 if (Arg.isInvalid()) 5977 return true; 5978 TheCall->setArg(i, Arg.get()); 5979 i++; 5980 } 5981 5982 // Check string literal arg. 5983 unsigned FormatIdx = i; 5984 { 5985 ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i)); 5986 if (Arg.isInvalid()) 5987 return true; 5988 TheCall->setArg(i, Arg.get()); 5989 i++; 5990 } 5991 5992 // Make sure variadic args are scalar. 5993 unsigned FirstDataArg = i; 5994 while (i < NumArgs) { 5995 ExprResult Arg = DefaultVariadicArgumentPromotion( 5996 TheCall->getArg(i), VariadicFunction, nullptr); 5997 if (Arg.isInvalid()) 5998 return true; 5999 CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType()); 6000 if (ArgSize.getQuantity() >= 0x100) { 6001 return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big) 6002 << i << (int)ArgSize.getQuantity() << 0xff 6003 << TheCall->getSourceRange(); 6004 } 6005 TheCall->setArg(i, Arg.get()); 6006 i++; 6007 } 6008 6009 // Check formatting specifiers. NOTE: We're only doing this for the non-size 6010 // call to avoid duplicate diagnostics. 6011 if (!IsSizeCall) { 6012 llvm::SmallBitVector CheckedVarArgs(NumArgs, false); 6013 ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs()); 6014 bool Success = CheckFormatArguments( 6015 Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog, 6016 VariadicFunction, TheCall->getBeginLoc(), SourceRange(), 6017 CheckedVarArgs); 6018 if (!Success) 6019 return true; 6020 } 6021 6022 if (IsSizeCall) { 6023 TheCall->setType(Context.getSizeType()); 6024 } else { 6025 TheCall->setType(Context.VoidPtrTy); 6026 } 6027 return false; 6028 } 6029 6030 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr 6031 /// TheCall is a constant expression. 6032 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, 6033 llvm::APSInt &Result) { 6034 Expr *Arg = TheCall->getArg(ArgNum); 6035 DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts()); 6036 FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl()); 6037 6038 if (Arg->isTypeDependent() || Arg->isValueDependent()) return false; 6039 6040 if (!Arg->isIntegerConstantExpr(Result, Context)) 6041 return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type) 6042 << FDecl->getDeclName() << Arg->getSourceRange(); 6043 6044 return false; 6045 } 6046 6047 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr 6048 /// TheCall is a constant expression in the range [Low, High]. 6049 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, 6050 int Low, int High, bool RangeIsError) { 6051 if (isConstantEvaluated()) 6052 return false; 6053 llvm::APSInt Result; 6054 6055 // We can't check the value of a dependent argument. 6056 Expr *Arg = TheCall->getArg(ArgNum); 6057 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6058 return false; 6059 6060 // Check constant-ness first. 6061 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6062 return true; 6063 6064 if (Result.getSExtValue() < Low || Result.getSExtValue() > High) { 6065 if (RangeIsError) 6066 return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range) 6067 << Result.toString(10) << Low << High << Arg->getSourceRange(); 6068 else 6069 // Defer the warning until we know if the code will be emitted so that 6070 // dead code can ignore this. 6071 DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall, 6072 PDiag(diag::warn_argument_invalid_range) 6073 << Result.toString(10) << Low << High 6074 << Arg->getSourceRange()); 6075 } 6076 6077 return false; 6078 } 6079 6080 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr 6081 /// TheCall is a constant expression is a multiple of Num.. 6082 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, 6083 unsigned Num) { 6084 llvm::APSInt Result; 6085 6086 // We can't check the value of a dependent argument. 6087 Expr *Arg = TheCall->getArg(ArgNum); 6088 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6089 return false; 6090 6091 // Check constant-ness first. 6092 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6093 return true; 6094 6095 if (Result.getSExtValue() % Num != 0) 6096 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple) 6097 << Num << Arg->getSourceRange(); 6098 6099 return false; 6100 } 6101 6102 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a 6103 /// constant expression representing a power of 2. 6104 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) { 6105 llvm::APSInt Result; 6106 6107 // We can't check the value of a dependent argument. 6108 Expr *Arg = TheCall->getArg(ArgNum); 6109 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6110 return false; 6111 6112 // Check constant-ness first. 6113 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6114 return true; 6115 6116 // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if 6117 // and only if x is a power of 2. 6118 if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0) 6119 return false; 6120 6121 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2) 6122 << Arg->getSourceRange(); 6123 } 6124 6125 static bool IsShiftedByte(llvm::APSInt Value) { 6126 if (Value.isNegative()) 6127 return false; 6128 6129 // Check if it's a shifted byte, by shifting it down 6130 while (true) { 6131 // If the value fits in the bottom byte, the check passes. 6132 if (Value < 0x100) 6133 return true; 6134 6135 // Otherwise, if the value has _any_ bits in the bottom byte, the check 6136 // fails. 6137 if ((Value & 0xFF) != 0) 6138 return false; 6139 6140 // If the bottom 8 bits are all 0, but something above that is nonzero, 6141 // then shifting the value right by 8 bits won't affect whether it's a 6142 // shifted byte or not. So do that, and go round again. 6143 Value >>= 8; 6144 } 6145 } 6146 6147 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is 6148 /// a constant expression representing an arbitrary byte value shifted left by 6149 /// a multiple of 8 bits. 6150 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, 6151 unsigned ArgBits) { 6152 llvm::APSInt Result; 6153 6154 // We can't check the value of a dependent argument. 6155 Expr *Arg = TheCall->getArg(ArgNum); 6156 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6157 return false; 6158 6159 // Check constant-ness first. 6160 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6161 return true; 6162 6163 // Truncate to the given size. 6164 Result = Result.getLoBits(ArgBits); 6165 Result.setIsUnsigned(true); 6166 6167 if (IsShiftedByte(Result)) 6168 return false; 6169 6170 return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte) 6171 << Arg->getSourceRange(); 6172 } 6173 6174 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of 6175 /// TheCall is a constant expression representing either a shifted byte value, 6176 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression 6177 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some 6178 /// Arm MVE intrinsics. 6179 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, 6180 int ArgNum, 6181 unsigned ArgBits) { 6182 llvm::APSInt Result; 6183 6184 // We can't check the value of a dependent argument. 6185 Expr *Arg = TheCall->getArg(ArgNum); 6186 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6187 return false; 6188 6189 // Check constant-ness first. 6190 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result)) 6191 return true; 6192 6193 // Truncate to the given size. 6194 Result = Result.getLoBits(ArgBits); 6195 Result.setIsUnsigned(true); 6196 6197 // Check to see if it's in either of the required forms. 6198 if (IsShiftedByte(Result) || 6199 (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF)) 6200 return false; 6201 6202 return Diag(TheCall->getBeginLoc(), 6203 diag::err_argument_not_shifted_byte_or_xxff) 6204 << Arg->getSourceRange(); 6205 } 6206 6207 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions 6208 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) { 6209 if (BuiltinID == AArch64::BI__builtin_arm_irg) { 6210 if (checkArgCount(*this, TheCall, 2)) 6211 return true; 6212 Expr *Arg0 = TheCall->getArg(0); 6213 Expr *Arg1 = TheCall->getArg(1); 6214 6215 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6216 if (FirstArg.isInvalid()) 6217 return true; 6218 QualType FirstArgType = FirstArg.get()->getType(); 6219 if (!FirstArgType->isAnyPointerType()) 6220 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6221 << "first" << FirstArgType << Arg0->getSourceRange(); 6222 TheCall->setArg(0, FirstArg.get()); 6223 6224 ExprResult SecArg = DefaultLvalueConversion(Arg1); 6225 if (SecArg.isInvalid()) 6226 return true; 6227 QualType SecArgType = SecArg.get()->getType(); 6228 if (!SecArgType->isIntegerType()) 6229 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6230 << "second" << SecArgType << Arg1->getSourceRange(); 6231 6232 // Derive the return type from the pointer argument. 6233 TheCall->setType(FirstArgType); 6234 return false; 6235 } 6236 6237 if (BuiltinID == AArch64::BI__builtin_arm_addg) { 6238 if (checkArgCount(*this, TheCall, 2)) 6239 return true; 6240 6241 Expr *Arg0 = TheCall->getArg(0); 6242 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6243 if (FirstArg.isInvalid()) 6244 return true; 6245 QualType FirstArgType = FirstArg.get()->getType(); 6246 if (!FirstArgType->isAnyPointerType()) 6247 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6248 << "first" << FirstArgType << Arg0->getSourceRange(); 6249 TheCall->setArg(0, FirstArg.get()); 6250 6251 // Derive the return type from the pointer argument. 6252 TheCall->setType(FirstArgType); 6253 6254 // Second arg must be an constant in range [0,15] 6255 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6256 } 6257 6258 if (BuiltinID == AArch64::BI__builtin_arm_gmi) { 6259 if (checkArgCount(*this, TheCall, 2)) 6260 return true; 6261 Expr *Arg0 = TheCall->getArg(0); 6262 Expr *Arg1 = TheCall->getArg(1); 6263 6264 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6265 if (FirstArg.isInvalid()) 6266 return true; 6267 QualType FirstArgType = FirstArg.get()->getType(); 6268 if (!FirstArgType->isAnyPointerType()) 6269 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6270 << "first" << FirstArgType << Arg0->getSourceRange(); 6271 6272 QualType SecArgType = Arg1->getType(); 6273 if (!SecArgType->isIntegerType()) 6274 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer) 6275 << "second" << SecArgType << Arg1->getSourceRange(); 6276 TheCall->setType(Context.IntTy); 6277 return false; 6278 } 6279 6280 if (BuiltinID == AArch64::BI__builtin_arm_ldg || 6281 BuiltinID == AArch64::BI__builtin_arm_stg) { 6282 if (checkArgCount(*this, TheCall, 1)) 6283 return true; 6284 Expr *Arg0 = TheCall->getArg(0); 6285 ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0); 6286 if (FirstArg.isInvalid()) 6287 return true; 6288 6289 QualType FirstArgType = FirstArg.get()->getType(); 6290 if (!FirstArgType->isAnyPointerType()) 6291 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer) 6292 << "first" << FirstArgType << Arg0->getSourceRange(); 6293 TheCall->setArg(0, FirstArg.get()); 6294 6295 // Derive the return type from the pointer argument. 6296 if (BuiltinID == AArch64::BI__builtin_arm_ldg) 6297 TheCall->setType(FirstArgType); 6298 return false; 6299 } 6300 6301 if (BuiltinID == AArch64::BI__builtin_arm_subp) { 6302 Expr *ArgA = TheCall->getArg(0); 6303 Expr *ArgB = TheCall->getArg(1); 6304 6305 ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA); 6306 ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB); 6307 6308 if (ArgExprA.isInvalid() || ArgExprB.isInvalid()) 6309 return true; 6310 6311 QualType ArgTypeA = ArgExprA.get()->getType(); 6312 QualType ArgTypeB = ArgExprB.get()->getType(); 6313 6314 auto isNull = [&] (Expr *E) -> bool { 6315 return E->isNullPointerConstant( 6316 Context, Expr::NPC_ValueDependentIsNotNull); }; 6317 6318 // argument should be either a pointer or null 6319 if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA)) 6320 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6321 << "first" << ArgTypeA << ArgA->getSourceRange(); 6322 6323 if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB)) 6324 return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer) 6325 << "second" << ArgTypeB << ArgB->getSourceRange(); 6326 6327 // Ensure Pointee types are compatible 6328 if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) && 6329 ArgTypeB->isAnyPointerType() && !isNull(ArgB)) { 6330 QualType pointeeA = ArgTypeA->getPointeeType(); 6331 QualType pointeeB = ArgTypeB->getPointeeType(); 6332 if (!Context.typesAreCompatible( 6333 Context.getCanonicalType(pointeeA).getUnqualifiedType(), 6334 Context.getCanonicalType(pointeeB).getUnqualifiedType())) { 6335 return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible) 6336 << ArgTypeA << ArgTypeB << ArgA->getSourceRange() 6337 << ArgB->getSourceRange(); 6338 } 6339 } 6340 6341 // at least one argument should be pointer type 6342 if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType()) 6343 return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer) 6344 << ArgTypeA << ArgTypeB << ArgA->getSourceRange(); 6345 6346 if (isNull(ArgA)) // adopt type of the other pointer 6347 ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer); 6348 6349 if (isNull(ArgB)) 6350 ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer); 6351 6352 TheCall->setArg(0, ArgExprA.get()); 6353 TheCall->setArg(1, ArgExprB.get()); 6354 TheCall->setType(Context.LongLongTy); 6355 return false; 6356 } 6357 assert(false && "Unhandled ARM MTE intrinsic"); 6358 return true; 6359 } 6360 6361 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr 6362 /// TheCall is an ARM/AArch64 special register string literal. 6363 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, 6364 int ArgNum, unsigned ExpectedFieldNum, 6365 bool AllowName) { 6366 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 || 6367 BuiltinID == ARM::BI__builtin_arm_wsr64 || 6368 BuiltinID == ARM::BI__builtin_arm_rsr || 6369 BuiltinID == ARM::BI__builtin_arm_rsrp || 6370 BuiltinID == ARM::BI__builtin_arm_wsr || 6371 BuiltinID == ARM::BI__builtin_arm_wsrp; 6372 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 || 6373 BuiltinID == AArch64::BI__builtin_arm_wsr64 || 6374 BuiltinID == AArch64::BI__builtin_arm_rsr || 6375 BuiltinID == AArch64::BI__builtin_arm_rsrp || 6376 BuiltinID == AArch64::BI__builtin_arm_wsr || 6377 BuiltinID == AArch64::BI__builtin_arm_wsrp; 6378 assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin."); 6379 6380 // We can't check the value of a dependent argument. 6381 Expr *Arg = TheCall->getArg(ArgNum); 6382 if (Arg->isTypeDependent() || Arg->isValueDependent()) 6383 return false; 6384 6385 // Check if the argument is a string literal. 6386 if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts())) 6387 return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal) 6388 << Arg->getSourceRange(); 6389 6390 // Check the type of special register given. 6391 StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString(); 6392 SmallVector<StringRef, 6> Fields; 6393 Reg.split(Fields, ":"); 6394 6395 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1)) 6396 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6397 << Arg->getSourceRange(); 6398 6399 // If the string is the name of a register then we cannot check that it is 6400 // valid here but if the string is of one the forms described in ACLE then we 6401 // can check that the supplied fields are integers and within the valid 6402 // ranges. 6403 if (Fields.size() > 1) { 6404 bool FiveFields = Fields.size() == 5; 6405 6406 bool ValidString = true; 6407 if (IsARMBuiltin) { 6408 ValidString &= Fields[0].startswith_lower("cp") || 6409 Fields[0].startswith_lower("p"); 6410 if (ValidString) 6411 Fields[0] = 6412 Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1); 6413 6414 ValidString &= Fields[2].startswith_lower("c"); 6415 if (ValidString) 6416 Fields[2] = Fields[2].drop_front(1); 6417 6418 if (FiveFields) { 6419 ValidString &= Fields[3].startswith_lower("c"); 6420 if (ValidString) 6421 Fields[3] = Fields[3].drop_front(1); 6422 } 6423 } 6424 6425 SmallVector<int, 5> Ranges; 6426 if (FiveFields) 6427 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7}); 6428 else 6429 Ranges.append({15, 7, 15}); 6430 6431 for (unsigned i=0; i<Fields.size(); ++i) { 6432 int IntField; 6433 ValidString &= !Fields[i].getAsInteger(10, IntField); 6434 ValidString &= (IntField >= 0 && IntField <= Ranges[i]); 6435 } 6436 6437 if (!ValidString) 6438 return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg) 6439 << Arg->getSourceRange(); 6440 } else if (IsAArch64Builtin && Fields.size() == 1) { 6441 // If the register name is one of those that appear in the condition below 6442 // and the special register builtin being used is one of the write builtins, 6443 // then we require that the argument provided for writing to the register 6444 // is an integer constant expression. This is because it will be lowered to 6445 // an MSR (immediate) instruction, so we need to know the immediate at 6446 // compile time. 6447 if (TheCall->getNumArgs() != 2) 6448 return false; 6449 6450 std::string RegLower = Reg.lower(); 6451 if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" && 6452 RegLower != "pan" && RegLower != "uao") 6453 return false; 6454 6455 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15); 6456 } 6457 6458 return false; 6459 } 6460 6461 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val). 6462 /// This checks that the target supports __builtin_longjmp and 6463 /// that val is a constant 1. 6464 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) { 6465 if (!Context.getTargetInfo().hasSjLjLowering()) 6466 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported) 6467 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6468 6469 Expr *Arg = TheCall->getArg(1); 6470 llvm::APSInt Result; 6471 6472 // TODO: This is less than ideal. Overload this to take a value. 6473 if (SemaBuiltinConstantArg(TheCall, 1, Result)) 6474 return true; 6475 6476 if (Result != 1) 6477 return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val) 6478 << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc()); 6479 6480 return false; 6481 } 6482 6483 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]). 6484 /// This checks that the target supports __builtin_setjmp. 6485 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) { 6486 if (!Context.getTargetInfo().hasSjLjLowering()) 6487 return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported) 6488 << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc()); 6489 return false; 6490 } 6491 6492 namespace { 6493 6494 class UncoveredArgHandler { 6495 enum { Unknown = -1, AllCovered = -2 }; 6496 6497 signed FirstUncoveredArg = Unknown; 6498 SmallVector<const Expr *, 4> DiagnosticExprs; 6499 6500 public: 6501 UncoveredArgHandler() = default; 6502 6503 bool hasUncoveredArg() const { 6504 return (FirstUncoveredArg >= 0); 6505 } 6506 6507 unsigned getUncoveredArg() const { 6508 assert(hasUncoveredArg() && "no uncovered argument"); 6509 return FirstUncoveredArg; 6510 } 6511 6512 void setAllCovered() { 6513 // A string has been found with all arguments covered, so clear out 6514 // the diagnostics. 6515 DiagnosticExprs.clear(); 6516 FirstUncoveredArg = AllCovered; 6517 } 6518 6519 void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) { 6520 assert(NewFirstUncoveredArg >= 0 && "Outside range"); 6521 6522 // Don't update if a previous string covers all arguments. 6523 if (FirstUncoveredArg == AllCovered) 6524 return; 6525 6526 // UncoveredArgHandler tracks the highest uncovered argument index 6527 // and with it all the strings that match this index. 6528 if (NewFirstUncoveredArg == FirstUncoveredArg) 6529 DiagnosticExprs.push_back(StrExpr); 6530 else if (NewFirstUncoveredArg > FirstUncoveredArg) { 6531 DiagnosticExprs.clear(); 6532 DiagnosticExprs.push_back(StrExpr); 6533 FirstUncoveredArg = NewFirstUncoveredArg; 6534 } 6535 } 6536 6537 void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr); 6538 }; 6539 6540 enum StringLiteralCheckType { 6541 SLCT_NotALiteral, 6542 SLCT_UncheckedLiteral, 6543 SLCT_CheckedLiteral 6544 }; 6545 6546 } // namespace 6547 6548 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, 6549 BinaryOperatorKind BinOpKind, 6550 bool AddendIsRight) { 6551 unsigned BitWidth = Offset.getBitWidth(); 6552 unsigned AddendBitWidth = Addend.getBitWidth(); 6553 // There might be negative interim results. 6554 if (Addend.isUnsigned()) { 6555 Addend = Addend.zext(++AddendBitWidth); 6556 Addend.setIsSigned(true); 6557 } 6558 // Adjust the bit width of the APSInts. 6559 if (AddendBitWidth > BitWidth) { 6560 Offset = Offset.sext(AddendBitWidth); 6561 BitWidth = AddendBitWidth; 6562 } else if (BitWidth > AddendBitWidth) { 6563 Addend = Addend.sext(BitWidth); 6564 } 6565 6566 bool Ov = false; 6567 llvm::APSInt ResOffset = Offset; 6568 if (BinOpKind == BO_Add) 6569 ResOffset = Offset.sadd_ov(Addend, Ov); 6570 else { 6571 assert(AddendIsRight && BinOpKind == BO_Sub && 6572 "operator must be add or sub with addend on the right"); 6573 ResOffset = Offset.ssub_ov(Addend, Ov); 6574 } 6575 6576 // We add an offset to a pointer here so we should support an offset as big as 6577 // possible. 6578 if (Ov) { 6579 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 && 6580 "index (intermediate) result too big"); 6581 Offset = Offset.sext(2 * BitWidth); 6582 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight); 6583 return; 6584 } 6585 6586 Offset = ResOffset; 6587 } 6588 6589 namespace { 6590 6591 // This is a wrapper class around StringLiteral to support offsetted string 6592 // literals as format strings. It takes the offset into account when returning 6593 // the string and its length or the source locations to display notes correctly. 6594 class FormatStringLiteral { 6595 const StringLiteral *FExpr; 6596 int64_t Offset; 6597 6598 public: 6599 FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0) 6600 : FExpr(fexpr), Offset(Offset) {} 6601 6602 StringRef getString() const { 6603 return FExpr->getString().drop_front(Offset); 6604 } 6605 6606 unsigned getByteLength() const { 6607 return FExpr->getByteLength() - getCharByteWidth() * Offset; 6608 } 6609 6610 unsigned getLength() const { return FExpr->getLength() - Offset; } 6611 unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); } 6612 6613 StringLiteral::StringKind getKind() const { return FExpr->getKind(); } 6614 6615 QualType getType() const { return FExpr->getType(); } 6616 6617 bool isAscii() const { return FExpr->isAscii(); } 6618 bool isWide() const { return FExpr->isWide(); } 6619 bool isUTF8() const { return FExpr->isUTF8(); } 6620 bool isUTF16() const { return FExpr->isUTF16(); } 6621 bool isUTF32() const { return FExpr->isUTF32(); } 6622 bool isPascal() const { return FExpr->isPascal(); } 6623 6624 SourceLocation getLocationOfByte( 6625 unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, 6626 const TargetInfo &Target, unsigned *StartToken = nullptr, 6627 unsigned *StartTokenByteOffset = nullptr) const { 6628 return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target, 6629 StartToken, StartTokenByteOffset); 6630 } 6631 6632 SourceLocation getBeginLoc() const LLVM_READONLY { 6633 return FExpr->getBeginLoc().getLocWithOffset(Offset); 6634 } 6635 6636 SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); } 6637 }; 6638 6639 } // namespace 6640 6641 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 6642 const Expr *OrigFormatExpr, 6643 ArrayRef<const Expr *> Args, 6644 bool HasVAListArg, unsigned format_idx, 6645 unsigned firstDataArg, 6646 Sema::FormatStringType Type, 6647 bool inFunctionCall, 6648 Sema::VariadicCallType CallType, 6649 llvm::SmallBitVector &CheckedVarArgs, 6650 UncoveredArgHandler &UncoveredArg, 6651 bool IgnoreStringsWithoutSpecifiers); 6652 6653 // Determine if an expression is a string literal or constant string. 6654 // If this function returns false on the arguments to a function expecting a 6655 // format string, we will usually need to emit a warning. 6656 // True string literals are then checked by CheckFormatString. 6657 static StringLiteralCheckType 6658 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args, 6659 bool HasVAListArg, unsigned format_idx, 6660 unsigned firstDataArg, Sema::FormatStringType Type, 6661 Sema::VariadicCallType CallType, bool InFunctionCall, 6662 llvm::SmallBitVector &CheckedVarArgs, 6663 UncoveredArgHandler &UncoveredArg, 6664 llvm::APSInt Offset, 6665 bool IgnoreStringsWithoutSpecifiers = false) { 6666 if (S.isConstantEvaluated()) 6667 return SLCT_NotALiteral; 6668 tryAgain: 6669 assert(Offset.isSigned() && "invalid offset"); 6670 6671 if (E->isTypeDependent() || E->isValueDependent()) 6672 return SLCT_NotALiteral; 6673 6674 E = E->IgnoreParenCasts(); 6675 6676 if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull)) 6677 // Technically -Wformat-nonliteral does not warn about this case. 6678 // The behavior of printf and friends in this case is implementation 6679 // dependent. Ideally if the format string cannot be null then 6680 // it should have a 'nonnull' attribute in the function prototype. 6681 return SLCT_UncheckedLiteral; 6682 6683 switch (E->getStmtClass()) { 6684 case Stmt::BinaryConditionalOperatorClass: 6685 case Stmt::ConditionalOperatorClass: { 6686 // The expression is a literal if both sub-expressions were, and it was 6687 // completely checked only if both sub-expressions were checked. 6688 const AbstractConditionalOperator *C = 6689 cast<AbstractConditionalOperator>(E); 6690 6691 // Determine whether it is necessary to check both sub-expressions, for 6692 // example, because the condition expression is a constant that can be 6693 // evaluated at compile time. 6694 bool CheckLeft = true, CheckRight = true; 6695 6696 bool Cond; 6697 if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(), 6698 S.isConstantEvaluated())) { 6699 if (Cond) 6700 CheckRight = false; 6701 else 6702 CheckLeft = false; 6703 } 6704 6705 // We need to maintain the offsets for the right and the left hand side 6706 // separately to check if every possible indexed expression is a valid 6707 // string literal. They might have different offsets for different string 6708 // literals in the end. 6709 StringLiteralCheckType Left; 6710 if (!CheckLeft) 6711 Left = SLCT_UncheckedLiteral; 6712 else { 6713 Left = checkFormatStringExpr(S, C->getTrueExpr(), Args, 6714 HasVAListArg, format_idx, firstDataArg, 6715 Type, CallType, InFunctionCall, 6716 CheckedVarArgs, UncoveredArg, Offset, 6717 IgnoreStringsWithoutSpecifiers); 6718 if (Left == SLCT_NotALiteral || !CheckRight) { 6719 return Left; 6720 } 6721 } 6722 6723 StringLiteralCheckType Right = checkFormatStringExpr( 6724 S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg, 6725 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6726 IgnoreStringsWithoutSpecifiers); 6727 6728 return (CheckLeft && Left < Right) ? Left : Right; 6729 } 6730 6731 case Stmt::ImplicitCastExprClass: 6732 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 6733 goto tryAgain; 6734 6735 case Stmt::OpaqueValueExprClass: 6736 if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) { 6737 E = src; 6738 goto tryAgain; 6739 } 6740 return SLCT_NotALiteral; 6741 6742 case Stmt::PredefinedExprClass: 6743 // While __func__, etc., are technically not string literals, they 6744 // cannot contain format specifiers and thus are not a security 6745 // liability. 6746 return SLCT_UncheckedLiteral; 6747 6748 case Stmt::DeclRefExprClass: { 6749 const DeclRefExpr *DR = cast<DeclRefExpr>(E); 6750 6751 // As an exception, do not flag errors for variables binding to 6752 // const string literals. 6753 if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) { 6754 bool isConstant = false; 6755 QualType T = DR->getType(); 6756 6757 if (const ArrayType *AT = S.Context.getAsArrayType(T)) { 6758 isConstant = AT->getElementType().isConstant(S.Context); 6759 } else if (const PointerType *PT = T->getAs<PointerType>()) { 6760 isConstant = T.isConstant(S.Context) && 6761 PT->getPointeeType().isConstant(S.Context); 6762 } else if (T->isObjCObjectPointerType()) { 6763 // In ObjC, there is usually no "const ObjectPointer" type, 6764 // so don't check if the pointee type is constant. 6765 isConstant = T.isConstant(S.Context); 6766 } 6767 6768 if (isConstant) { 6769 if (const Expr *Init = VD->getAnyInitializer()) { 6770 // Look through initializers like const char c[] = { "foo" } 6771 if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) { 6772 if (InitList->isStringLiteralInit()) 6773 Init = InitList->getInit(0)->IgnoreParenImpCasts(); 6774 } 6775 return checkFormatStringExpr(S, Init, Args, 6776 HasVAListArg, format_idx, 6777 firstDataArg, Type, CallType, 6778 /*InFunctionCall*/ false, CheckedVarArgs, 6779 UncoveredArg, Offset); 6780 } 6781 } 6782 6783 // For vprintf* functions (i.e., HasVAListArg==true), we add a 6784 // special check to see if the format string is a function parameter 6785 // of the function calling the printf function. If the function 6786 // has an attribute indicating it is a printf-like function, then we 6787 // should suppress warnings concerning non-literals being used in a call 6788 // to a vprintf function. For example: 6789 // 6790 // void 6791 // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){ 6792 // va_list ap; 6793 // va_start(ap, fmt); 6794 // vprintf(fmt, ap); // Do NOT emit a warning about "fmt". 6795 // ... 6796 // } 6797 if (HasVAListArg) { 6798 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) { 6799 if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) { 6800 int PVIndex = PV->getFunctionScopeIndex() + 1; 6801 for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) { 6802 // adjust for implicit parameter 6803 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND)) 6804 if (MD->isInstance()) 6805 ++PVIndex; 6806 // We also check if the formats are compatible. 6807 // We can't pass a 'scanf' string to a 'printf' function. 6808 if (PVIndex == PVFormat->getFormatIdx() && 6809 Type == S.GetFormatStringType(PVFormat)) 6810 return SLCT_UncheckedLiteral; 6811 } 6812 } 6813 } 6814 } 6815 } 6816 6817 return SLCT_NotALiteral; 6818 } 6819 6820 case Stmt::CallExprClass: 6821 case Stmt::CXXMemberCallExprClass: { 6822 const CallExpr *CE = cast<CallExpr>(E); 6823 if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) { 6824 bool IsFirst = true; 6825 StringLiteralCheckType CommonResult; 6826 for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) { 6827 const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex()); 6828 StringLiteralCheckType Result = checkFormatStringExpr( 6829 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6830 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6831 IgnoreStringsWithoutSpecifiers); 6832 if (IsFirst) { 6833 CommonResult = Result; 6834 IsFirst = false; 6835 } 6836 } 6837 if (!IsFirst) 6838 return CommonResult; 6839 6840 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) { 6841 unsigned BuiltinID = FD->getBuiltinID(); 6842 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString || 6843 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) { 6844 const Expr *Arg = CE->getArg(0); 6845 return checkFormatStringExpr(S, Arg, Args, 6846 HasVAListArg, format_idx, 6847 firstDataArg, Type, CallType, 6848 InFunctionCall, CheckedVarArgs, 6849 UncoveredArg, Offset, 6850 IgnoreStringsWithoutSpecifiers); 6851 } 6852 } 6853 } 6854 6855 return SLCT_NotALiteral; 6856 } 6857 case Stmt::ObjCMessageExprClass: { 6858 const auto *ME = cast<ObjCMessageExpr>(E); 6859 if (const auto *MD = ME->getMethodDecl()) { 6860 if (const auto *FA = MD->getAttr<FormatArgAttr>()) { 6861 // As a special case heuristic, if we're using the method -[NSBundle 6862 // localizedStringForKey:value:table:], ignore any key strings that lack 6863 // format specifiers. The idea is that if the key doesn't have any 6864 // format specifiers then its probably just a key to map to the 6865 // localized strings. If it does have format specifiers though, then its 6866 // likely that the text of the key is the format string in the 6867 // programmer's language, and should be checked. 6868 const ObjCInterfaceDecl *IFace; 6869 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) && 6870 IFace->getIdentifier()->isStr("NSBundle") && 6871 MD->getSelector().isKeywordSelector( 6872 {"localizedStringForKey", "value", "table"})) { 6873 IgnoreStringsWithoutSpecifiers = true; 6874 } 6875 6876 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex()); 6877 return checkFormatStringExpr( 6878 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type, 6879 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset, 6880 IgnoreStringsWithoutSpecifiers); 6881 } 6882 } 6883 6884 return SLCT_NotALiteral; 6885 } 6886 case Stmt::ObjCStringLiteralClass: 6887 case Stmt::StringLiteralClass: { 6888 const StringLiteral *StrE = nullptr; 6889 6890 if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E)) 6891 StrE = ObjCFExpr->getString(); 6892 else 6893 StrE = cast<StringLiteral>(E); 6894 6895 if (StrE) { 6896 if (Offset.isNegative() || Offset > StrE->getLength()) { 6897 // TODO: It would be better to have an explicit warning for out of 6898 // bounds literals. 6899 return SLCT_NotALiteral; 6900 } 6901 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue()); 6902 CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx, 6903 firstDataArg, Type, InFunctionCall, CallType, 6904 CheckedVarArgs, UncoveredArg, 6905 IgnoreStringsWithoutSpecifiers); 6906 return SLCT_CheckedLiteral; 6907 } 6908 6909 return SLCT_NotALiteral; 6910 } 6911 case Stmt::BinaryOperatorClass: { 6912 const BinaryOperator *BinOp = cast<BinaryOperator>(E); 6913 6914 // A string literal + an int offset is still a string literal. 6915 if (BinOp->isAdditiveOp()) { 6916 Expr::EvalResult LResult, RResult; 6917 6918 bool LIsInt = BinOp->getLHS()->EvaluateAsInt( 6919 LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6920 bool RIsInt = BinOp->getRHS()->EvaluateAsInt( 6921 RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated()); 6922 6923 if (LIsInt != RIsInt) { 6924 BinaryOperatorKind BinOpKind = BinOp->getOpcode(); 6925 6926 if (LIsInt) { 6927 if (BinOpKind == BO_Add) { 6928 sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt); 6929 E = BinOp->getRHS(); 6930 goto tryAgain; 6931 } 6932 } else { 6933 sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt); 6934 E = BinOp->getLHS(); 6935 goto tryAgain; 6936 } 6937 } 6938 } 6939 6940 return SLCT_NotALiteral; 6941 } 6942 case Stmt::UnaryOperatorClass: { 6943 const UnaryOperator *UnaOp = cast<UnaryOperator>(E); 6944 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr()); 6945 if (UnaOp->getOpcode() == UO_AddrOf && ASE) { 6946 Expr::EvalResult IndexResult; 6947 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context, 6948 Expr::SE_NoSideEffects, 6949 S.isConstantEvaluated())) { 6950 sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add, 6951 /*RHS is int*/ true); 6952 E = ASE->getBase(); 6953 goto tryAgain; 6954 } 6955 } 6956 6957 return SLCT_NotALiteral; 6958 } 6959 6960 default: 6961 return SLCT_NotALiteral; 6962 } 6963 } 6964 6965 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) { 6966 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName()) 6967 .Case("scanf", FST_Scanf) 6968 .Cases("printf", "printf0", FST_Printf) 6969 .Cases("NSString", "CFString", FST_NSString) 6970 .Case("strftime", FST_Strftime) 6971 .Case("strfmon", FST_Strfmon) 6972 .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf) 6973 .Case("freebsd_kprintf", FST_FreeBSDKPrintf) 6974 .Case("os_trace", FST_OSLog) 6975 .Case("os_log", FST_OSLog) 6976 .Default(FST_Unknown); 6977 } 6978 6979 /// CheckFormatArguments - Check calls to printf and scanf (and similar 6980 /// functions) for correct use of format strings. 6981 /// Returns true if a format string has been fully checked. 6982 bool Sema::CheckFormatArguments(const FormatAttr *Format, 6983 ArrayRef<const Expr *> Args, 6984 bool IsCXXMember, 6985 VariadicCallType CallType, 6986 SourceLocation Loc, SourceRange Range, 6987 llvm::SmallBitVector &CheckedVarArgs) { 6988 FormatStringInfo FSI; 6989 if (getFormatStringInfo(Format, IsCXXMember, &FSI)) 6990 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx, 6991 FSI.FirstDataArg, GetFormatStringType(Format), 6992 CallType, Loc, Range, CheckedVarArgs); 6993 return false; 6994 } 6995 6996 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args, 6997 bool HasVAListArg, unsigned format_idx, 6998 unsigned firstDataArg, FormatStringType Type, 6999 VariadicCallType CallType, 7000 SourceLocation Loc, SourceRange Range, 7001 llvm::SmallBitVector &CheckedVarArgs) { 7002 // CHECK: printf/scanf-like function is called with no format string. 7003 if (format_idx >= Args.size()) { 7004 Diag(Loc, diag::warn_missing_format_string) << Range; 7005 return false; 7006 } 7007 7008 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts(); 7009 7010 // CHECK: format string is not a string literal. 7011 // 7012 // Dynamically generated format strings are difficult to 7013 // automatically vet at compile time. Requiring that format strings 7014 // are string literals: (1) permits the checking of format strings by 7015 // the compiler and thereby (2) can practically remove the source of 7016 // many format string exploits. 7017 7018 // Format string can be either ObjC string (e.g. @"%d") or 7019 // C string (e.g. "%d") 7020 // ObjC string uses the same format specifiers as C string, so we can use 7021 // the same format string checking logic for both ObjC and C strings. 7022 UncoveredArgHandler UncoveredArg; 7023 StringLiteralCheckType CT = 7024 checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg, 7025 format_idx, firstDataArg, Type, CallType, 7026 /*IsFunctionCall*/ true, CheckedVarArgs, 7027 UncoveredArg, 7028 /*no string offset*/ llvm::APSInt(64, false) = 0); 7029 7030 // Generate a diagnostic where an uncovered argument is detected. 7031 if (UncoveredArg.hasUncoveredArg()) { 7032 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg; 7033 assert(ArgIdx < Args.size() && "ArgIdx outside bounds"); 7034 UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]); 7035 } 7036 7037 if (CT != SLCT_NotALiteral) 7038 // Literal format string found, check done! 7039 return CT == SLCT_CheckedLiteral; 7040 7041 // Strftime is particular as it always uses a single 'time' argument, 7042 // so it is safe to pass a non-literal string. 7043 if (Type == FST_Strftime) 7044 return false; 7045 7046 // Do not emit diag when the string param is a macro expansion and the 7047 // format is either NSString or CFString. This is a hack to prevent 7048 // diag when using the NSLocalizedString and CFCopyLocalizedString macros 7049 // which are usually used in place of NS and CF string literals. 7050 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc(); 7051 if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc)) 7052 return false; 7053 7054 // If there are no arguments specified, warn with -Wformat-security, otherwise 7055 // warn only with -Wformat-nonliteral. 7056 if (Args.size() == firstDataArg) { 7057 Diag(FormatLoc, diag::warn_format_nonliteral_noargs) 7058 << OrigFormatExpr->getSourceRange(); 7059 switch (Type) { 7060 default: 7061 break; 7062 case FST_Kprintf: 7063 case FST_FreeBSDKPrintf: 7064 case FST_Printf: 7065 Diag(FormatLoc, diag::note_format_security_fixit) 7066 << FixItHint::CreateInsertion(FormatLoc, "\"%s\", "); 7067 break; 7068 case FST_NSString: 7069 Diag(FormatLoc, diag::note_format_security_fixit) 7070 << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", "); 7071 break; 7072 } 7073 } else { 7074 Diag(FormatLoc, diag::warn_format_nonliteral) 7075 << OrigFormatExpr->getSourceRange(); 7076 } 7077 return false; 7078 } 7079 7080 namespace { 7081 7082 class CheckFormatHandler : public analyze_format_string::FormatStringHandler { 7083 protected: 7084 Sema &S; 7085 const FormatStringLiteral *FExpr; 7086 const Expr *OrigFormatExpr; 7087 const Sema::FormatStringType FSType; 7088 const unsigned FirstDataArg; 7089 const unsigned NumDataArgs; 7090 const char *Beg; // Start of format string. 7091 const bool HasVAListArg; 7092 ArrayRef<const Expr *> Args; 7093 unsigned FormatIdx; 7094 llvm::SmallBitVector CoveredArgs; 7095 bool usesPositionalArgs = false; 7096 bool atFirstArg = true; 7097 bool inFunctionCall; 7098 Sema::VariadicCallType CallType; 7099 llvm::SmallBitVector &CheckedVarArgs; 7100 UncoveredArgHandler &UncoveredArg; 7101 7102 public: 7103 CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr, 7104 const Expr *origFormatExpr, 7105 const Sema::FormatStringType type, unsigned firstDataArg, 7106 unsigned numDataArgs, const char *beg, bool hasVAListArg, 7107 ArrayRef<const Expr *> Args, unsigned formatIdx, 7108 bool inFunctionCall, Sema::VariadicCallType callType, 7109 llvm::SmallBitVector &CheckedVarArgs, 7110 UncoveredArgHandler &UncoveredArg) 7111 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type), 7112 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg), 7113 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx), 7114 inFunctionCall(inFunctionCall), CallType(callType), 7115 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) { 7116 CoveredArgs.resize(numDataArgs); 7117 CoveredArgs.reset(); 7118 } 7119 7120 void DoneProcessing(); 7121 7122 void HandleIncompleteSpecifier(const char *startSpecifier, 7123 unsigned specifierLen) override; 7124 7125 void HandleInvalidLengthModifier( 7126 const analyze_format_string::FormatSpecifier &FS, 7127 const analyze_format_string::ConversionSpecifier &CS, 7128 const char *startSpecifier, unsigned specifierLen, 7129 unsigned DiagID); 7130 7131 void HandleNonStandardLengthModifier( 7132 const analyze_format_string::FormatSpecifier &FS, 7133 const char *startSpecifier, unsigned specifierLen); 7134 7135 void HandleNonStandardConversionSpecifier( 7136 const analyze_format_string::ConversionSpecifier &CS, 7137 const char *startSpecifier, unsigned specifierLen); 7138 7139 void HandlePosition(const char *startPos, unsigned posLen) override; 7140 7141 void HandleInvalidPosition(const char *startSpecifier, 7142 unsigned specifierLen, 7143 analyze_format_string::PositionContext p) override; 7144 7145 void HandleZeroPosition(const char *startPos, unsigned posLen) override; 7146 7147 void HandleNullChar(const char *nullCharacter) override; 7148 7149 template <typename Range> 7150 static void 7151 EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr, 7152 const PartialDiagnostic &PDiag, SourceLocation StringLoc, 7153 bool IsStringLocation, Range StringRange, 7154 ArrayRef<FixItHint> Fixit = None); 7155 7156 protected: 7157 bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc, 7158 const char *startSpec, 7159 unsigned specifierLen, 7160 const char *csStart, unsigned csLen); 7161 7162 void HandlePositionalNonpositionalArgs(SourceLocation Loc, 7163 const char *startSpec, 7164 unsigned specifierLen); 7165 7166 SourceRange getFormatStringRange(); 7167 CharSourceRange getSpecifierRange(const char *startSpecifier, 7168 unsigned specifierLen); 7169 SourceLocation getLocationOfByte(const char *x); 7170 7171 const Expr *getDataArg(unsigned i) const; 7172 7173 bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS, 7174 const analyze_format_string::ConversionSpecifier &CS, 7175 const char *startSpecifier, unsigned specifierLen, 7176 unsigned argIndex); 7177 7178 template <typename Range> 7179 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc, 7180 bool IsStringLocation, Range StringRange, 7181 ArrayRef<FixItHint> Fixit = None); 7182 }; 7183 7184 } // namespace 7185 7186 SourceRange CheckFormatHandler::getFormatStringRange() { 7187 return OrigFormatExpr->getSourceRange(); 7188 } 7189 7190 CharSourceRange CheckFormatHandler:: 7191 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) { 7192 SourceLocation Start = getLocationOfByte(startSpecifier); 7193 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1); 7194 7195 // Advance the end SourceLocation by one due to half-open ranges. 7196 End = End.getLocWithOffset(1); 7197 7198 return CharSourceRange::getCharRange(Start, End); 7199 } 7200 7201 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) { 7202 return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(), 7203 S.getLangOpts(), S.Context.getTargetInfo()); 7204 } 7205 7206 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier, 7207 unsigned specifierLen){ 7208 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier), 7209 getLocationOfByte(startSpecifier), 7210 /*IsStringLocation*/true, 7211 getSpecifierRange(startSpecifier, specifierLen)); 7212 } 7213 7214 void CheckFormatHandler::HandleInvalidLengthModifier( 7215 const analyze_format_string::FormatSpecifier &FS, 7216 const analyze_format_string::ConversionSpecifier &CS, 7217 const char *startSpecifier, unsigned specifierLen, unsigned DiagID) { 7218 using namespace analyze_format_string; 7219 7220 const LengthModifier &LM = FS.getLengthModifier(); 7221 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7222 7223 // See if we know how to fix this length modifier. 7224 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7225 if (FixedLM) { 7226 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7227 getLocationOfByte(LM.getStart()), 7228 /*IsStringLocation*/true, 7229 getSpecifierRange(startSpecifier, specifierLen)); 7230 7231 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7232 << FixedLM->toString() 7233 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7234 7235 } else { 7236 FixItHint Hint; 7237 if (DiagID == diag::warn_format_nonsensical_length) 7238 Hint = FixItHint::CreateRemoval(LMRange); 7239 7240 EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(), 7241 getLocationOfByte(LM.getStart()), 7242 /*IsStringLocation*/true, 7243 getSpecifierRange(startSpecifier, specifierLen), 7244 Hint); 7245 } 7246 } 7247 7248 void CheckFormatHandler::HandleNonStandardLengthModifier( 7249 const analyze_format_string::FormatSpecifier &FS, 7250 const char *startSpecifier, unsigned specifierLen) { 7251 using namespace analyze_format_string; 7252 7253 const LengthModifier &LM = FS.getLengthModifier(); 7254 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength()); 7255 7256 // See if we know how to fix this length modifier. 7257 Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier(); 7258 if (FixedLM) { 7259 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7260 << LM.toString() << 0, 7261 getLocationOfByte(LM.getStart()), 7262 /*IsStringLocation*/true, 7263 getSpecifierRange(startSpecifier, specifierLen)); 7264 7265 S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier) 7266 << FixedLM->toString() 7267 << FixItHint::CreateReplacement(LMRange, FixedLM->toString()); 7268 7269 } else { 7270 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7271 << LM.toString() << 0, 7272 getLocationOfByte(LM.getStart()), 7273 /*IsStringLocation*/true, 7274 getSpecifierRange(startSpecifier, specifierLen)); 7275 } 7276 } 7277 7278 void CheckFormatHandler::HandleNonStandardConversionSpecifier( 7279 const analyze_format_string::ConversionSpecifier &CS, 7280 const char *startSpecifier, unsigned specifierLen) { 7281 using namespace analyze_format_string; 7282 7283 // See if we know how to fix this conversion specifier. 7284 Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier(); 7285 if (FixedCS) { 7286 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7287 << CS.toString() << /*conversion specifier*/1, 7288 getLocationOfByte(CS.getStart()), 7289 /*IsStringLocation*/true, 7290 getSpecifierRange(startSpecifier, specifierLen)); 7291 7292 CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength()); 7293 S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier) 7294 << FixedCS->toString() 7295 << FixItHint::CreateReplacement(CSRange, FixedCS->toString()); 7296 } else { 7297 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard) 7298 << CS.toString() << /*conversion specifier*/1, 7299 getLocationOfByte(CS.getStart()), 7300 /*IsStringLocation*/true, 7301 getSpecifierRange(startSpecifier, specifierLen)); 7302 } 7303 } 7304 7305 void CheckFormatHandler::HandlePosition(const char *startPos, 7306 unsigned posLen) { 7307 EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg), 7308 getLocationOfByte(startPos), 7309 /*IsStringLocation*/true, 7310 getSpecifierRange(startPos, posLen)); 7311 } 7312 7313 void 7314 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen, 7315 analyze_format_string::PositionContext p) { 7316 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier) 7317 << (unsigned) p, 7318 getLocationOfByte(startPos), /*IsStringLocation*/true, 7319 getSpecifierRange(startPos, posLen)); 7320 } 7321 7322 void CheckFormatHandler::HandleZeroPosition(const char *startPos, 7323 unsigned posLen) { 7324 EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier), 7325 getLocationOfByte(startPos), 7326 /*IsStringLocation*/true, 7327 getSpecifierRange(startPos, posLen)); 7328 } 7329 7330 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) { 7331 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) { 7332 // The presence of a null character is likely an error. 7333 EmitFormatDiagnostic( 7334 S.PDiag(diag::warn_printf_format_string_contains_null_char), 7335 getLocationOfByte(nullCharacter), /*IsStringLocation*/true, 7336 getFormatStringRange()); 7337 } 7338 } 7339 7340 // Note that this may return NULL if there was an error parsing or building 7341 // one of the argument expressions. 7342 const Expr *CheckFormatHandler::getDataArg(unsigned i) const { 7343 return Args[FirstDataArg + i]; 7344 } 7345 7346 void CheckFormatHandler::DoneProcessing() { 7347 // Does the number of data arguments exceed the number of 7348 // format conversions in the format string? 7349 if (!HasVAListArg) { 7350 // Find any arguments that weren't covered. 7351 CoveredArgs.flip(); 7352 signed notCoveredArg = CoveredArgs.find_first(); 7353 if (notCoveredArg >= 0) { 7354 assert((unsigned)notCoveredArg < NumDataArgs); 7355 UncoveredArg.Update(notCoveredArg, OrigFormatExpr); 7356 } else { 7357 UncoveredArg.setAllCovered(); 7358 } 7359 } 7360 } 7361 7362 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall, 7363 const Expr *ArgExpr) { 7364 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 && 7365 "Invalid state"); 7366 7367 if (!ArgExpr) 7368 return; 7369 7370 SourceLocation Loc = ArgExpr->getBeginLoc(); 7371 7372 if (S.getSourceManager().isInSystemMacro(Loc)) 7373 return; 7374 7375 PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used); 7376 for (auto E : DiagnosticExprs) 7377 PDiag << E->getSourceRange(); 7378 7379 CheckFormatHandler::EmitFormatDiagnostic( 7380 S, IsFunctionCall, DiagnosticExprs[0], 7381 PDiag, Loc, /*IsStringLocation*/false, 7382 DiagnosticExprs[0]->getSourceRange()); 7383 } 7384 7385 bool 7386 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex, 7387 SourceLocation Loc, 7388 const char *startSpec, 7389 unsigned specifierLen, 7390 const char *csStart, 7391 unsigned csLen) { 7392 bool keepGoing = true; 7393 if (argIndex < NumDataArgs) { 7394 // Consider the argument coverered, even though the specifier doesn't 7395 // make sense. 7396 CoveredArgs.set(argIndex); 7397 } 7398 else { 7399 // If argIndex exceeds the number of data arguments we 7400 // don't issue a warning because that is just a cascade of warnings (and 7401 // they may have intended '%%' anyway). We don't want to continue processing 7402 // the format string after this point, however, as we will like just get 7403 // gibberish when trying to match arguments. 7404 keepGoing = false; 7405 } 7406 7407 StringRef Specifier(csStart, csLen); 7408 7409 // If the specifier in non-printable, it could be the first byte of a UTF-8 7410 // sequence. In that case, print the UTF-8 code point. If not, print the byte 7411 // hex value. 7412 std::string CodePointStr; 7413 if (!llvm::sys::locale::isPrint(*csStart)) { 7414 llvm::UTF32 CodePoint; 7415 const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart); 7416 const llvm::UTF8 *E = 7417 reinterpret_cast<const llvm::UTF8 *>(csStart + csLen); 7418 llvm::ConversionResult Result = 7419 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion); 7420 7421 if (Result != llvm::conversionOK) { 7422 unsigned char FirstChar = *csStart; 7423 CodePoint = (llvm::UTF32)FirstChar; 7424 } 7425 7426 llvm::raw_string_ostream OS(CodePointStr); 7427 if (CodePoint < 256) 7428 OS << "\\x" << llvm::format("%02x", CodePoint); 7429 else if (CodePoint <= 0xFFFF) 7430 OS << "\\u" << llvm::format("%04x", CodePoint); 7431 else 7432 OS << "\\U" << llvm::format("%08x", CodePoint); 7433 OS.flush(); 7434 Specifier = CodePointStr; 7435 } 7436 7437 EmitFormatDiagnostic( 7438 S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc, 7439 /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen)); 7440 7441 return keepGoing; 7442 } 7443 7444 void 7445 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc, 7446 const char *startSpec, 7447 unsigned specifierLen) { 7448 EmitFormatDiagnostic( 7449 S.PDiag(diag::warn_format_mix_positional_nonpositional_args), 7450 Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen)); 7451 } 7452 7453 bool 7454 CheckFormatHandler::CheckNumArgs( 7455 const analyze_format_string::FormatSpecifier &FS, 7456 const analyze_format_string::ConversionSpecifier &CS, 7457 const char *startSpecifier, unsigned specifierLen, unsigned argIndex) { 7458 7459 if (argIndex >= NumDataArgs) { 7460 PartialDiagnostic PDiag = FS.usesPositionalArg() 7461 ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args) 7462 << (argIndex+1) << NumDataArgs) 7463 : S.PDiag(diag::warn_printf_insufficient_data_args); 7464 EmitFormatDiagnostic( 7465 PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true, 7466 getSpecifierRange(startSpecifier, specifierLen)); 7467 7468 // Since more arguments than conversion tokens are given, by extension 7469 // all arguments are covered, so mark this as so. 7470 UncoveredArg.setAllCovered(); 7471 return false; 7472 } 7473 return true; 7474 } 7475 7476 template<typename Range> 7477 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag, 7478 SourceLocation Loc, 7479 bool IsStringLocation, 7480 Range StringRange, 7481 ArrayRef<FixItHint> FixIt) { 7482 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, 7483 Loc, IsStringLocation, StringRange, FixIt); 7484 } 7485 7486 /// If the format string is not within the function call, emit a note 7487 /// so that the function call and string are in diagnostic messages. 7488 /// 7489 /// \param InFunctionCall if true, the format string is within the function 7490 /// call and only one diagnostic message will be produced. Otherwise, an 7491 /// extra note will be emitted pointing to location of the format string. 7492 /// 7493 /// \param ArgumentExpr the expression that is passed as the format string 7494 /// argument in the function call. Used for getting locations when two 7495 /// diagnostics are emitted. 7496 /// 7497 /// \param PDiag the callee should already have provided any strings for the 7498 /// diagnostic message. This function only adds locations and fixits 7499 /// to diagnostics. 7500 /// 7501 /// \param Loc primary location for diagnostic. If two diagnostics are 7502 /// required, one will be at Loc and a new SourceLocation will be created for 7503 /// the other one. 7504 /// 7505 /// \param IsStringLocation if true, Loc points to the format string should be 7506 /// used for the note. Otherwise, Loc points to the argument list and will 7507 /// be used with PDiag. 7508 /// 7509 /// \param StringRange some or all of the string to highlight. This is 7510 /// templated so it can accept either a CharSourceRange or a SourceRange. 7511 /// 7512 /// \param FixIt optional fix it hint for the format string. 7513 template <typename Range> 7514 void CheckFormatHandler::EmitFormatDiagnostic( 7515 Sema &S, bool InFunctionCall, const Expr *ArgumentExpr, 7516 const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation, 7517 Range StringRange, ArrayRef<FixItHint> FixIt) { 7518 if (InFunctionCall) { 7519 const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag); 7520 D << StringRange; 7521 D << FixIt; 7522 } else { 7523 S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag) 7524 << ArgumentExpr->getSourceRange(); 7525 7526 const Sema::SemaDiagnosticBuilder &Note = 7527 S.Diag(IsStringLocation ? Loc : StringRange.getBegin(), 7528 diag::note_format_string_defined); 7529 7530 Note << StringRange; 7531 Note << FixIt; 7532 } 7533 } 7534 7535 //===--- CHECK: Printf format string checking ------------------------------===// 7536 7537 namespace { 7538 7539 class CheckPrintfHandler : public CheckFormatHandler { 7540 public: 7541 CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr, 7542 const Expr *origFormatExpr, 7543 const Sema::FormatStringType type, unsigned firstDataArg, 7544 unsigned numDataArgs, bool isObjC, const char *beg, 7545 bool hasVAListArg, ArrayRef<const Expr *> Args, 7546 unsigned formatIdx, bool inFunctionCall, 7547 Sema::VariadicCallType CallType, 7548 llvm::SmallBitVector &CheckedVarArgs, 7549 UncoveredArgHandler &UncoveredArg) 7550 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 7551 numDataArgs, beg, hasVAListArg, Args, formatIdx, 7552 inFunctionCall, CallType, CheckedVarArgs, 7553 UncoveredArg) {} 7554 7555 bool isObjCContext() const { return FSType == Sema::FST_NSString; } 7556 7557 /// Returns true if '%@' specifiers are allowed in the format string. 7558 bool allowsObjCArg() const { 7559 return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog || 7560 FSType == Sema::FST_OSTrace; 7561 } 7562 7563 bool HandleInvalidPrintfConversionSpecifier( 7564 const analyze_printf::PrintfSpecifier &FS, 7565 const char *startSpecifier, 7566 unsigned specifierLen) override; 7567 7568 void handleInvalidMaskType(StringRef MaskType) override; 7569 7570 bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS, 7571 const char *startSpecifier, 7572 unsigned specifierLen) override; 7573 bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 7574 const char *StartSpecifier, 7575 unsigned SpecifierLen, 7576 const Expr *E); 7577 7578 bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k, 7579 const char *startSpecifier, unsigned specifierLen); 7580 void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS, 7581 const analyze_printf::OptionalAmount &Amt, 7582 unsigned type, 7583 const char *startSpecifier, unsigned specifierLen); 7584 void HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7585 const analyze_printf::OptionalFlag &flag, 7586 const char *startSpecifier, unsigned specifierLen); 7587 void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS, 7588 const analyze_printf::OptionalFlag &ignoredFlag, 7589 const analyze_printf::OptionalFlag &flag, 7590 const char *startSpecifier, unsigned specifierLen); 7591 bool checkForCStrMembers(const analyze_printf::ArgType &AT, 7592 const Expr *E); 7593 7594 void HandleEmptyObjCModifierFlag(const char *startFlag, 7595 unsigned flagLen) override; 7596 7597 void HandleInvalidObjCModifierFlag(const char *startFlag, 7598 unsigned flagLen) override; 7599 7600 void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart, 7601 const char *flagsEnd, 7602 const char *conversionPosition) 7603 override; 7604 }; 7605 7606 } // namespace 7607 7608 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier( 7609 const analyze_printf::PrintfSpecifier &FS, 7610 const char *startSpecifier, 7611 unsigned specifierLen) { 7612 const analyze_printf::PrintfConversionSpecifier &CS = 7613 FS.getConversionSpecifier(); 7614 7615 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 7616 getLocationOfByte(CS.getStart()), 7617 startSpecifier, specifierLen, 7618 CS.getStart(), CS.getLength()); 7619 } 7620 7621 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) { 7622 S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size); 7623 } 7624 7625 bool CheckPrintfHandler::HandleAmount( 7626 const analyze_format_string::OptionalAmount &Amt, 7627 unsigned k, const char *startSpecifier, 7628 unsigned specifierLen) { 7629 if (Amt.hasDataArgument()) { 7630 if (!HasVAListArg) { 7631 unsigned argIndex = Amt.getArgIndex(); 7632 if (argIndex >= NumDataArgs) { 7633 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg) 7634 << k, 7635 getLocationOfByte(Amt.getStart()), 7636 /*IsStringLocation*/true, 7637 getSpecifierRange(startSpecifier, specifierLen)); 7638 // Don't do any more checking. We will just emit 7639 // spurious errors. 7640 return false; 7641 } 7642 7643 // Type check the data argument. It should be an 'int'. 7644 // Although not in conformance with C99, we also allow the argument to be 7645 // an 'unsigned int' as that is a reasonably safe case. GCC also 7646 // doesn't emit a warning for that case. 7647 CoveredArgs.set(argIndex); 7648 const Expr *Arg = getDataArg(argIndex); 7649 if (!Arg) 7650 return false; 7651 7652 QualType T = Arg->getType(); 7653 7654 const analyze_printf::ArgType &AT = Amt.getArgType(S.Context); 7655 assert(AT.isValid()); 7656 7657 if (!AT.matchesType(S.Context, T)) { 7658 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type) 7659 << k << AT.getRepresentativeTypeName(S.Context) 7660 << T << Arg->getSourceRange(), 7661 getLocationOfByte(Amt.getStart()), 7662 /*IsStringLocation*/true, 7663 getSpecifierRange(startSpecifier, specifierLen)); 7664 // Don't do any more checking. We will just emit 7665 // spurious errors. 7666 return false; 7667 } 7668 } 7669 } 7670 return true; 7671 } 7672 7673 void CheckPrintfHandler::HandleInvalidAmount( 7674 const analyze_printf::PrintfSpecifier &FS, 7675 const analyze_printf::OptionalAmount &Amt, 7676 unsigned type, 7677 const char *startSpecifier, 7678 unsigned specifierLen) { 7679 const analyze_printf::PrintfConversionSpecifier &CS = 7680 FS.getConversionSpecifier(); 7681 7682 FixItHint fixit = 7683 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant 7684 ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(), 7685 Amt.getConstantLength())) 7686 : FixItHint(); 7687 7688 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount) 7689 << type << CS.toString(), 7690 getLocationOfByte(Amt.getStart()), 7691 /*IsStringLocation*/true, 7692 getSpecifierRange(startSpecifier, specifierLen), 7693 fixit); 7694 } 7695 7696 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS, 7697 const analyze_printf::OptionalFlag &flag, 7698 const char *startSpecifier, 7699 unsigned specifierLen) { 7700 // Warn about pointless flag with a fixit removal. 7701 const analyze_printf::PrintfConversionSpecifier &CS = 7702 FS.getConversionSpecifier(); 7703 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag) 7704 << flag.toString() << CS.toString(), 7705 getLocationOfByte(flag.getPosition()), 7706 /*IsStringLocation*/true, 7707 getSpecifierRange(startSpecifier, specifierLen), 7708 FixItHint::CreateRemoval( 7709 getSpecifierRange(flag.getPosition(), 1))); 7710 } 7711 7712 void CheckPrintfHandler::HandleIgnoredFlag( 7713 const analyze_printf::PrintfSpecifier &FS, 7714 const analyze_printf::OptionalFlag &ignoredFlag, 7715 const analyze_printf::OptionalFlag &flag, 7716 const char *startSpecifier, 7717 unsigned specifierLen) { 7718 // Warn about ignored flag with a fixit removal. 7719 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag) 7720 << ignoredFlag.toString() << flag.toString(), 7721 getLocationOfByte(ignoredFlag.getPosition()), 7722 /*IsStringLocation*/true, 7723 getSpecifierRange(startSpecifier, specifierLen), 7724 FixItHint::CreateRemoval( 7725 getSpecifierRange(ignoredFlag.getPosition(), 1))); 7726 } 7727 7728 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag, 7729 unsigned flagLen) { 7730 // Warn about an empty flag. 7731 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag), 7732 getLocationOfByte(startFlag), 7733 /*IsStringLocation*/true, 7734 getSpecifierRange(startFlag, flagLen)); 7735 } 7736 7737 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag, 7738 unsigned flagLen) { 7739 // Warn about an invalid flag. 7740 auto Range = getSpecifierRange(startFlag, flagLen); 7741 StringRef flag(startFlag, flagLen); 7742 EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag, 7743 getLocationOfByte(startFlag), 7744 /*IsStringLocation*/true, 7745 Range, FixItHint::CreateRemoval(Range)); 7746 } 7747 7748 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion( 7749 const char *flagsStart, const char *flagsEnd, const char *conversionPosition) { 7750 // Warn about using '[...]' without a '@' conversion. 7751 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1); 7752 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion; 7753 EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1), 7754 getLocationOfByte(conversionPosition), 7755 /*IsStringLocation*/true, 7756 Range, FixItHint::CreateRemoval(Range)); 7757 } 7758 7759 // Determines if the specified is a C++ class or struct containing 7760 // a member with the specified name and kind (e.g. a CXXMethodDecl named 7761 // "c_str()"). 7762 template<typename MemberKind> 7763 static llvm::SmallPtrSet<MemberKind*, 1> 7764 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) { 7765 const RecordType *RT = Ty->getAs<RecordType>(); 7766 llvm::SmallPtrSet<MemberKind*, 1> Results; 7767 7768 if (!RT) 7769 return Results; 7770 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()); 7771 if (!RD || !RD->getDefinition()) 7772 return Results; 7773 7774 LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(), 7775 Sema::LookupMemberName); 7776 R.suppressDiagnostics(); 7777 7778 // We just need to include all members of the right kind turned up by the 7779 // filter, at this point. 7780 if (S.LookupQualifiedName(R, RT->getDecl())) 7781 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 7782 NamedDecl *decl = (*I)->getUnderlyingDecl(); 7783 if (MemberKind *FK = dyn_cast<MemberKind>(decl)) 7784 Results.insert(FK); 7785 } 7786 return Results; 7787 } 7788 7789 /// Check if we could call '.c_str()' on an object. 7790 /// 7791 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't 7792 /// allow the call, or if it would be ambiguous). 7793 bool Sema::hasCStrMethod(const Expr *E) { 7794 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7795 7796 MethodSet Results = 7797 CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType()); 7798 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7799 MI != ME; ++MI) 7800 if ((*MI)->getMinRequiredArguments() == 0) 7801 return true; 7802 return false; 7803 } 7804 7805 // Check if a (w)string was passed when a (w)char* was needed, and offer a 7806 // better diagnostic if so. AT is assumed to be valid. 7807 // Returns true when a c_str() conversion method is found. 7808 bool CheckPrintfHandler::checkForCStrMembers( 7809 const analyze_printf::ArgType &AT, const Expr *E) { 7810 using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>; 7811 7812 MethodSet Results = 7813 CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType()); 7814 7815 for (MethodSet::iterator MI = Results.begin(), ME = Results.end(); 7816 MI != ME; ++MI) { 7817 const CXXMethodDecl *Method = *MI; 7818 if (Method->getMinRequiredArguments() == 0 && 7819 AT.matchesType(S.Context, Method->getReturnType())) { 7820 // FIXME: Suggest parens if the expression needs them. 7821 SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc()); 7822 S.Diag(E->getBeginLoc(), diag::note_printf_c_str) 7823 << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()"); 7824 return true; 7825 } 7826 } 7827 7828 return false; 7829 } 7830 7831 bool 7832 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier 7833 &FS, 7834 const char *startSpecifier, 7835 unsigned specifierLen) { 7836 using namespace analyze_format_string; 7837 using namespace analyze_printf; 7838 7839 const PrintfConversionSpecifier &CS = FS.getConversionSpecifier(); 7840 7841 if (FS.consumesDataArgument()) { 7842 if (atFirstArg) { 7843 atFirstArg = false; 7844 usesPositionalArgs = FS.usesPositionalArg(); 7845 } 7846 else if (usesPositionalArgs != FS.usesPositionalArg()) { 7847 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 7848 startSpecifier, specifierLen); 7849 return false; 7850 } 7851 } 7852 7853 // First check if the field width, precision, and conversion specifier 7854 // have matching data arguments. 7855 if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0, 7856 startSpecifier, specifierLen)) { 7857 return false; 7858 } 7859 7860 if (!HandleAmount(FS.getPrecision(), /* precision */ 1, 7861 startSpecifier, specifierLen)) { 7862 return false; 7863 } 7864 7865 if (!CS.consumesDataArgument()) { 7866 // FIXME: Technically specifying a precision or field width here 7867 // makes no sense. Worth issuing a warning at some point. 7868 return true; 7869 } 7870 7871 // Consume the argument. 7872 unsigned argIndex = FS.getArgIndex(); 7873 if (argIndex < NumDataArgs) { 7874 // The check to see if the argIndex is valid will come later. 7875 // We set the bit here because we may exit early from this 7876 // function if we encounter some other error. 7877 CoveredArgs.set(argIndex); 7878 } 7879 7880 // FreeBSD kernel extensions. 7881 if (CS.getKind() == ConversionSpecifier::FreeBSDbArg || 7882 CS.getKind() == ConversionSpecifier::FreeBSDDArg) { 7883 // We need at least two arguments. 7884 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1)) 7885 return false; 7886 7887 // Claim the second argument. 7888 CoveredArgs.set(argIndex + 1); 7889 7890 // Type check the first argument (int for %b, pointer for %D) 7891 const Expr *Ex = getDataArg(argIndex); 7892 const analyze_printf::ArgType &AT = 7893 (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ? 7894 ArgType(S.Context.IntTy) : ArgType::CPointerTy; 7895 if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType())) 7896 EmitFormatDiagnostic( 7897 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7898 << AT.getRepresentativeTypeName(S.Context) << Ex->getType() 7899 << false << Ex->getSourceRange(), 7900 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7901 getSpecifierRange(startSpecifier, specifierLen)); 7902 7903 // Type check the second argument (char * for both %b and %D) 7904 Ex = getDataArg(argIndex + 1); 7905 const analyze_printf::ArgType &AT2 = ArgType::CStrTy; 7906 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType())) 7907 EmitFormatDiagnostic( 7908 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 7909 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType() 7910 << false << Ex->getSourceRange(), 7911 Ex->getBeginLoc(), /*IsStringLocation*/ false, 7912 getSpecifierRange(startSpecifier, specifierLen)); 7913 7914 return true; 7915 } 7916 7917 // Check for using an Objective-C specific conversion specifier 7918 // in a non-ObjC literal. 7919 if (!allowsObjCArg() && CS.isObjCArg()) { 7920 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7921 specifierLen); 7922 } 7923 7924 // %P can only be used with os_log. 7925 if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) { 7926 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7927 specifierLen); 7928 } 7929 7930 // %n is not allowed with os_log. 7931 if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) { 7932 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg), 7933 getLocationOfByte(CS.getStart()), 7934 /*IsStringLocation*/ false, 7935 getSpecifierRange(startSpecifier, specifierLen)); 7936 7937 return true; 7938 } 7939 7940 // Only scalars are allowed for os_trace. 7941 if (FSType == Sema::FST_OSTrace && 7942 (CS.getKind() == ConversionSpecifier::PArg || 7943 CS.getKind() == ConversionSpecifier::sArg || 7944 CS.getKind() == ConversionSpecifier::ObjCObjArg)) { 7945 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier, 7946 specifierLen); 7947 } 7948 7949 // Check for use of public/private annotation outside of os_log(). 7950 if (FSType != Sema::FST_OSLog) { 7951 if (FS.isPublic().isSet()) { 7952 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7953 << "public", 7954 getLocationOfByte(FS.isPublic().getPosition()), 7955 /*IsStringLocation*/ false, 7956 getSpecifierRange(startSpecifier, specifierLen)); 7957 } 7958 if (FS.isPrivate().isSet()) { 7959 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation) 7960 << "private", 7961 getLocationOfByte(FS.isPrivate().getPosition()), 7962 /*IsStringLocation*/ false, 7963 getSpecifierRange(startSpecifier, specifierLen)); 7964 } 7965 } 7966 7967 // Check for invalid use of field width 7968 if (!FS.hasValidFieldWidth()) { 7969 HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0, 7970 startSpecifier, specifierLen); 7971 } 7972 7973 // Check for invalid use of precision 7974 if (!FS.hasValidPrecision()) { 7975 HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1, 7976 startSpecifier, specifierLen); 7977 } 7978 7979 // Precision is mandatory for %P specifier. 7980 if (CS.getKind() == ConversionSpecifier::PArg && 7981 FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) { 7982 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision), 7983 getLocationOfByte(startSpecifier), 7984 /*IsStringLocation*/ false, 7985 getSpecifierRange(startSpecifier, specifierLen)); 7986 } 7987 7988 // Check each flag does not conflict with any other component. 7989 if (!FS.hasValidThousandsGroupingPrefix()) 7990 HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen); 7991 if (!FS.hasValidLeadingZeros()) 7992 HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen); 7993 if (!FS.hasValidPlusPrefix()) 7994 HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen); 7995 if (!FS.hasValidSpacePrefix()) 7996 HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen); 7997 if (!FS.hasValidAlternativeForm()) 7998 HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen); 7999 if (!FS.hasValidLeftJustified()) 8000 HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen); 8001 8002 // Check that flags are not ignored by another flag 8003 if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+' 8004 HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(), 8005 startSpecifier, specifierLen); 8006 if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-' 8007 HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(), 8008 startSpecifier, specifierLen); 8009 8010 // Check the length modifier is valid with the given conversion specifier. 8011 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8012 S.getLangOpts())) 8013 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8014 diag::warn_format_nonsensical_length); 8015 else if (!FS.hasStandardLengthModifier()) 8016 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8017 else if (!FS.hasStandardLengthConversionCombination()) 8018 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8019 diag::warn_format_non_standard_conversion_spec); 8020 8021 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8022 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8023 8024 // The remaining checks depend on the data arguments. 8025 if (HasVAListArg) 8026 return true; 8027 8028 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8029 return false; 8030 8031 const Expr *Arg = getDataArg(argIndex); 8032 if (!Arg) 8033 return true; 8034 8035 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg); 8036 } 8037 8038 static bool requiresParensToAddCast(const Expr *E) { 8039 // FIXME: We should have a general way to reason about operator 8040 // precedence and whether parens are actually needed here. 8041 // Take care of a few common cases where they aren't. 8042 const Expr *Inside = E->IgnoreImpCasts(); 8043 if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside)) 8044 Inside = POE->getSyntacticForm()->IgnoreImpCasts(); 8045 8046 switch (Inside->getStmtClass()) { 8047 case Stmt::ArraySubscriptExprClass: 8048 case Stmt::CallExprClass: 8049 case Stmt::CharacterLiteralClass: 8050 case Stmt::CXXBoolLiteralExprClass: 8051 case Stmt::DeclRefExprClass: 8052 case Stmt::FloatingLiteralClass: 8053 case Stmt::IntegerLiteralClass: 8054 case Stmt::MemberExprClass: 8055 case Stmt::ObjCArrayLiteralClass: 8056 case Stmt::ObjCBoolLiteralExprClass: 8057 case Stmt::ObjCBoxedExprClass: 8058 case Stmt::ObjCDictionaryLiteralClass: 8059 case Stmt::ObjCEncodeExprClass: 8060 case Stmt::ObjCIvarRefExprClass: 8061 case Stmt::ObjCMessageExprClass: 8062 case Stmt::ObjCPropertyRefExprClass: 8063 case Stmt::ObjCStringLiteralClass: 8064 case Stmt::ObjCSubscriptRefExprClass: 8065 case Stmt::ParenExprClass: 8066 case Stmt::StringLiteralClass: 8067 case Stmt::UnaryOperatorClass: 8068 return false; 8069 default: 8070 return true; 8071 } 8072 } 8073 8074 static std::pair<QualType, StringRef> 8075 shouldNotPrintDirectly(const ASTContext &Context, 8076 QualType IntendedTy, 8077 const Expr *E) { 8078 // Use a 'while' to peel off layers of typedefs. 8079 QualType TyTy = IntendedTy; 8080 while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) { 8081 StringRef Name = UserTy->getDecl()->getName(); 8082 QualType CastTy = llvm::StringSwitch<QualType>(Name) 8083 .Case("CFIndex", Context.getNSIntegerType()) 8084 .Case("NSInteger", Context.getNSIntegerType()) 8085 .Case("NSUInteger", Context.getNSUIntegerType()) 8086 .Case("SInt32", Context.IntTy) 8087 .Case("UInt32", Context.UnsignedIntTy) 8088 .Default(QualType()); 8089 8090 if (!CastTy.isNull()) 8091 return std::make_pair(CastTy, Name); 8092 8093 TyTy = UserTy->desugar(); 8094 } 8095 8096 // Strip parens if necessary. 8097 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) 8098 return shouldNotPrintDirectly(Context, 8099 PE->getSubExpr()->getType(), 8100 PE->getSubExpr()); 8101 8102 // If this is a conditional expression, then its result type is constructed 8103 // via usual arithmetic conversions and thus there might be no necessary 8104 // typedef sugar there. Recurse to operands to check for NSInteger & 8105 // Co. usage condition. 8106 if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { 8107 QualType TrueTy, FalseTy; 8108 StringRef TrueName, FalseName; 8109 8110 std::tie(TrueTy, TrueName) = 8111 shouldNotPrintDirectly(Context, 8112 CO->getTrueExpr()->getType(), 8113 CO->getTrueExpr()); 8114 std::tie(FalseTy, FalseName) = 8115 shouldNotPrintDirectly(Context, 8116 CO->getFalseExpr()->getType(), 8117 CO->getFalseExpr()); 8118 8119 if (TrueTy == FalseTy) 8120 return std::make_pair(TrueTy, TrueName); 8121 else if (TrueTy.isNull()) 8122 return std::make_pair(FalseTy, FalseName); 8123 else if (FalseTy.isNull()) 8124 return std::make_pair(TrueTy, TrueName); 8125 } 8126 8127 return std::make_pair(QualType(), StringRef()); 8128 } 8129 8130 /// Return true if \p ICE is an implicit argument promotion of an arithmetic 8131 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked 8132 /// type do not count. 8133 static bool 8134 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) { 8135 QualType From = ICE->getSubExpr()->getType(); 8136 QualType To = ICE->getType(); 8137 // It's an integer promotion if the destination type is the promoted 8138 // source type. 8139 if (ICE->getCastKind() == CK_IntegralCast && 8140 From->isPromotableIntegerType() && 8141 S.Context.getPromotedIntegerType(From) == To) 8142 return true; 8143 // Look through vector types, since we do default argument promotion for 8144 // those in OpenCL. 8145 if (const auto *VecTy = From->getAs<ExtVectorType>()) 8146 From = VecTy->getElementType(); 8147 if (const auto *VecTy = To->getAs<ExtVectorType>()) 8148 To = VecTy->getElementType(); 8149 // It's a floating promotion if the source type is a lower rank. 8150 return ICE->getCastKind() == CK_FloatingCast && 8151 S.Context.getFloatingTypeOrder(From, To) < 0; 8152 } 8153 8154 bool 8155 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS, 8156 const char *StartSpecifier, 8157 unsigned SpecifierLen, 8158 const Expr *E) { 8159 using namespace analyze_format_string; 8160 using namespace analyze_printf; 8161 8162 // Now type check the data expression that matches the 8163 // format specifier. 8164 const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext()); 8165 if (!AT.isValid()) 8166 return true; 8167 8168 QualType ExprTy = E->getType(); 8169 while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) { 8170 ExprTy = TET->getUnderlyingExpr()->getType(); 8171 } 8172 8173 // Diagnose attempts to print a boolean value as a character. Unlike other 8174 // -Wformat diagnostics, this is fine from a type perspective, but it still 8175 // doesn't make sense. 8176 if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg && 8177 E->isKnownToHaveBooleanValue()) { 8178 const CharSourceRange &CSR = 8179 getSpecifierRange(StartSpecifier, SpecifierLen); 8180 SmallString<4> FSString; 8181 llvm::raw_svector_ostream os(FSString); 8182 FS.toString(os); 8183 EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character) 8184 << FSString, 8185 E->getExprLoc(), false, CSR); 8186 return true; 8187 } 8188 8189 analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy); 8190 if (Match == analyze_printf::ArgType::Match) 8191 return true; 8192 8193 // Look through argument promotions for our error message's reported type. 8194 // This includes the integral and floating promotions, but excludes array 8195 // and function pointer decay (seeing that an argument intended to be a 8196 // string has type 'char [6]' is probably more confusing than 'char *') and 8197 // certain bitfield promotions (bitfields can be 'demoted' to a lesser type). 8198 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 8199 if (isArithmeticArgumentPromotion(S, ICE)) { 8200 E = ICE->getSubExpr(); 8201 ExprTy = E->getType(); 8202 8203 // Check if we didn't match because of an implicit cast from a 'char' 8204 // or 'short' to an 'int'. This is done because printf is a varargs 8205 // function. 8206 if (ICE->getType() == S.Context.IntTy || 8207 ICE->getType() == S.Context.UnsignedIntTy) { 8208 // All further checking is done on the subexpression 8209 const analyze_printf::ArgType::MatchKind ImplicitMatch = 8210 AT.matchesType(S.Context, ExprTy); 8211 if (ImplicitMatch == analyze_printf::ArgType::Match) 8212 return true; 8213 if (ImplicitMatch == ArgType::NoMatchPedantic || 8214 ImplicitMatch == ArgType::NoMatchTypeConfusion) 8215 Match = ImplicitMatch; 8216 } 8217 } 8218 } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) { 8219 // Special case for 'a', which has type 'int' in C. 8220 // Note, however, that we do /not/ want to treat multibyte constants like 8221 // 'MooV' as characters! This form is deprecated but still exists. 8222 if (ExprTy == S.Context.IntTy) 8223 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue())) 8224 ExprTy = S.Context.CharTy; 8225 } 8226 8227 // Look through enums to their underlying type. 8228 bool IsEnum = false; 8229 if (auto EnumTy = ExprTy->getAs<EnumType>()) { 8230 ExprTy = EnumTy->getDecl()->getIntegerType(); 8231 IsEnum = true; 8232 } 8233 8234 // %C in an Objective-C context prints a unichar, not a wchar_t. 8235 // If the argument is an integer of some kind, believe the %C and suggest 8236 // a cast instead of changing the conversion specifier. 8237 QualType IntendedTy = ExprTy; 8238 if (isObjCContext() && 8239 FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) { 8240 if (ExprTy->isIntegralOrUnscopedEnumerationType() && 8241 !ExprTy->isCharType()) { 8242 // 'unichar' is defined as a typedef of unsigned short, but we should 8243 // prefer using the typedef if it is visible. 8244 IntendedTy = S.Context.UnsignedShortTy; 8245 8246 // While we are here, check if the value is an IntegerLiteral that happens 8247 // to be within the valid range. 8248 if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) { 8249 const llvm::APInt &V = IL->getValue(); 8250 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy)) 8251 return true; 8252 } 8253 8254 LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(), 8255 Sema::LookupOrdinaryName); 8256 if (S.LookupName(Result, S.getCurScope())) { 8257 NamedDecl *ND = Result.getFoundDecl(); 8258 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND)) 8259 if (TD->getUnderlyingType() == IntendedTy) 8260 IntendedTy = S.Context.getTypedefType(TD); 8261 } 8262 } 8263 } 8264 8265 // Special-case some of Darwin's platform-independence types by suggesting 8266 // casts to primitive types that are known to be large enough. 8267 bool ShouldNotPrintDirectly = false; StringRef CastTyName; 8268 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 8269 QualType CastTy; 8270 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E); 8271 if (!CastTy.isNull()) { 8272 // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int 8273 // (long in ASTContext). Only complain to pedants. 8274 if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") && 8275 (AT.isSizeT() || AT.isPtrdiffT()) && 8276 AT.matchesType(S.Context, CastTy)) 8277 Match = ArgType::NoMatchPedantic; 8278 IntendedTy = CastTy; 8279 ShouldNotPrintDirectly = true; 8280 } 8281 } 8282 8283 // We may be able to offer a FixItHint if it is a supported type. 8284 PrintfSpecifier fixedFS = FS; 8285 bool Success = 8286 fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext()); 8287 8288 if (Success) { 8289 // Get the fix string from the fixed format specifier 8290 SmallString<16> buf; 8291 llvm::raw_svector_ostream os(buf); 8292 fixedFS.toString(os); 8293 8294 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen); 8295 8296 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) { 8297 unsigned Diag; 8298 switch (Match) { 8299 case ArgType::Match: llvm_unreachable("expected non-matching"); 8300 case ArgType::NoMatchPedantic: 8301 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8302 break; 8303 case ArgType::NoMatchTypeConfusion: 8304 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8305 break; 8306 case ArgType::NoMatch: 8307 Diag = diag::warn_format_conversion_argument_type_mismatch; 8308 break; 8309 } 8310 8311 // In this case, the specifier is wrong and should be changed to match 8312 // the argument. 8313 EmitFormatDiagnostic(S.PDiag(Diag) 8314 << AT.getRepresentativeTypeName(S.Context) 8315 << IntendedTy << IsEnum << E->getSourceRange(), 8316 E->getBeginLoc(), 8317 /*IsStringLocation*/ false, SpecRange, 8318 FixItHint::CreateReplacement(SpecRange, os.str())); 8319 } else { 8320 // The canonical type for formatting this value is different from the 8321 // actual type of the expression. (This occurs, for example, with Darwin's 8322 // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but 8323 // should be printed as 'long' for 64-bit compatibility.) 8324 // Rather than emitting a normal format/argument mismatch, we want to 8325 // add a cast to the recommended type (and correct the format string 8326 // if necessary). 8327 SmallString<16> CastBuf; 8328 llvm::raw_svector_ostream CastFix(CastBuf); 8329 CastFix << "("; 8330 IntendedTy.print(CastFix, S.Context.getPrintingPolicy()); 8331 CastFix << ")"; 8332 8333 SmallVector<FixItHint,4> Hints; 8334 if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly) 8335 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str())); 8336 8337 if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) { 8338 // If there's already a cast present, just replace it. 8339 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc()); 8340 Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str())); 8341 8342 } else if (!requiresParensToAddCast(E)) { 8343 // If the expression has high enough precedence, 8344 // just write the C-style cast. 8345 Hints.push_back( 8346 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8347 } else { 8348 // Otherwise, add parens around the expression as well as the cast. 8349 CastFix << "("; 8350 Hints.push_back( 8351 FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str())); 8352 8353 SourceLocation After = S.getLocForEndOfToken(E->getEndLoc()); 8354 Hints.push_back(FixItHint::CreateInsertion(After, ")")); 8355 } 8356 8357 if (ShouldNotPrintDirectly) { 8358 // The expression has a type that should not be printed directly. 8359 // We extract the name from the typedef because we don't want to show 8360 // the underlying type in the diagnostic. 8361 StringRef Name; 8362 if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy)) 8363 Name = TypedefTy->getDecl()->getName(); 8364 else 8365 Name = CastTyName; 8366 unsigned Diag = Match == ArgType::NoMatchPedantic 8367 ? diag::warn_format_argument_needs_cast_pedantic 8368 : diag::warn_format_argument_needs_cast; 8369 EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum 8370 << E->getSourceRange(), 8371 E->getBeginLoc(), /*IsStringLocation=*/false, 8372 SpecRange, Hints); 8373 } else { 8374 // In this case, the expression could be printed using a different 8375 // specifier, but we've decided that the specifier is probably correct 8376 // and we should cast instead. Just use the normal warning message. 8377 EmitFormatDiagnostic( 8378 S.PDiag(diag::warn_format_conversion_argument_type_mismatch) 8379 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum 8380 << E->getSourceRange(), 8381 E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints); 8382 } 8383 } 8384 } else { 8385 const CharSourceRange &CSR = getSpecifierRange(StartSpecifier, 8386 SpecifierLen); 8387 // Since the warning for passing non-POD types to variadic functions 8388 // was deferred until now, we emit a warning for non-POD 8389 // arguments here. 8390 switch (S.isValidVarArgType(ExprTy)) { 8391 case Sema::VAK_Valid: 8392 case Sema::VAK_ValidInCXX11: { 8393 unsigned Diag; 8394 switch (Match) { 8395 case ArgType::Match: llvm_unreachable("expected non-matching"); 8396 case ArgType::NoMatchPedantic: 8397 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic; 8398 break; 8399 case ArgType::NoMatchTypeConfusion: 8400 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion; 8401 break; 8402 case ArgType::NoMatch: 8403 Diag = diag::warn_format_conversion_argument_type_mismatch; 8404 break; 8405 } 8406 8407 EmitFormatDiagnostic( 8408 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy 8409 << IsEnum << CSR << E->getSourceRange(), 8410 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8411 break; 8412 } 8413 case Sema::VAK_Undefined: 8414 case Sema::VAK_MSVCUndefined: 8415 EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string) 8416 << S.getLangOpts().CPlusPlus11 << ExprTy 8417 << CallType 8418 << AT.getRepresentativeTypeName(S.Context) << CSR 8419 << E->getSourceRange(), 8420 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8421 checkForCStrMembers(AT, E); 8422 break; 8423 8424 case Sema::VAK_Invalid: 8425 if (ExprTy->isObjCObjectType()) 8426 EmitFormatDiagnostic( 8427 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format) 8428 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType 8429 << AT.getRepresentativeTypeName(S.Context) << CSR 8430 << E->getSourceRange(), 8431 E->getBeginLoc(), /*IsStringLocation*/ false, CSR); 8432 else 8433 // FIXME: If this is an initializer list, suggest removing the braces 8434 // or inserting a cast to the target type. 8435 S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format) 8436 << isa<InitListExpr>(E) << ExprTy << CallType 8437 << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange(); 8438 break; 8439 } 8440 8441 assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() && 8442 "format string specifier index out of range"); 8443 CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true; 8444 } 8445 8446 return true; 8447 } 8448 8449 //===--- CHECK: Scanf format string checking ------------------------------===// 8450 8451 namespace { 8452 8453 class CheckScanfHandler : public CheckFormatHandler { 8454 public: 8455 CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr, 8456 const Expr *origFormatExpr, Sema::FormatStringType type, 8457 unsigned firstDataArg, unsigned numDataArgs, 8458 const char *beg, bool hasVAListArg, 8459 ArrayRef<const Expr *> Args, unsigned formatIdx, 8460 bool inFunctionCall, Sema::VariadicCallType CallType, 8461 llvm::SmallBitVector &CheckedVarArgs, 8462 UncoveredArgHandler &UncoveredArg) 8463 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg, 8464 numDataArgs, beg, hasVAListArg, Args, formatIdx, 8465 inFunctionCall, CallType, CheckedVarArgs, 8466 UncoveredArg) {} 8467 8468 bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS, 8469 const char *startSpecifier, 8470 unsigned specifierLen) override; 8471 8472 bool HandleInvalidScanfConversionSpecifier( 8473 const analyze_scanf::ScanfSpecifier &FS, 8474 const char *startSpecifier, 8475 unsigned specifierLen) override; 8476 8477 void HandleIncompleteScanList(const char *start, const char *end) override; 8478 }; 8479 8480 } // namespace 8481 8482 void CheckScanfHandler::HandleIncompleteScanList(const char *start, 8483 const char *end) { 8484 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete), 8485 getLocationOfByte(end), /*IsStringLocation*/true, 8486 getSpecifierRange(start, end - start)); 8487 } 8488 8489 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier( 8490 const analyze_scanf::ScanfSpecifier &FS, 8491 const char *startSpecifier, 8492 unsigned specifierLen) { 8493 const analyze_scanf::ScanfConversionSpecifier &CS = 8494 FS.getConversionSpecifier(); 8495 8496 return HandleInvalidConversionSpecifier(FS.getArgIndex(), 8497 getLocationOfByte(CS.getStart()), 8498 startSpecifier, specifierLen, 8499 CS.getStart(), CS.getLength()); 8500 } 8501 8502 bool CheckScanfHandler::HandleScanfSpecifier( 8503 const analyze_scanf::ScanfSpecifier &FS, 8504 const char *startSpecifier, 8505 unsigned specifierLen) { 8506 using namespace analyze_scanf; 8507 using namespace analyze_format_string; 8508 8509 const ScanfConversionSpecifier &CS = FS.getConversionSpecifier(); 8510 8511 // Handle case where '%' and '*' don't consume an argument. These shouldn't 8512 // be used to decide if we are using positional arguments consistently. 8513 if (FS.consumesDataArgument()) { 8514 if (atFirstArg) { 8515 atFirstArg = false; 8516 usesPositionalArgs = FS.usesPositionalArg(); 8517 } 8518 else if (usesPositionalArgs != FS.usesPositionalArg()) { 8519 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()), 8520 startSpecifier, specifierLen); 8521 return false; 8522 } 8523 } 8524 8525 // Check if the field with is non-zero. 8526 const OptionalAmount &Amt = FS.getFieldWidth(); 8527 if (Amt.getHowSpecified() == OptionalAmount::Constant) { 8528 if (Amt.getConstantAmount() == 0) { 8529 const CharSourceRange &R = getSpecifierRange(Amt.getStart(), 8530 Amt.getConstantLength()); 8531 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width), 8532 getLocationOfByte(Amt.getStart()), 8533 /*IsStringLocation*/true, R, 8534 FixItHint::CreateRemoval(R)); 8535 } 8536 } 8537 8538 if (!FS.consumesDataArgument()) { 8539 // FIXME: Technically specifying a precision or field width here 8540 // makes no sense. Worth issuing a warning at some point. 8541 return true; 8542 } 8543 8544 // Consume the argument. 8545 unsigned argIndex = FS.getArgIndex(); 8546 if (argIndex < NumDataArgs) { 8547 // The check to see if the argIndex is valid will come later. 8548 // We set the bit here because we may exit early from this 8549 // function if we encounter some other error. 8550 CoveredArgs.set(argIndex); 8551 } 8552 8553 // Check the length modifier is valid with the given conversion specifier. 8554 if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(), 8555 S.getLangOpts())) 8556 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8557 diag::warn_format_nonsensical_length); 8558 else if (!FS.hasStandardLengthModifier()) 8559 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen); 8560 else if (!FS.hasStandardLengthConversionCombination()) 8561 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen, 8562 diag::warn_format_non_standard_conversion_spec); 8563 8564 if (!FS.hasStandardConversionSpecifier(S.getLangOpts())) 8565 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen); 8566 8567 // The remaining checks depend on the data arguments. 8568 if (HasVAListArg) 8569 return true; 8570 8571 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex)) 8572 return false; 8573 8574 // Check that the argument type matches the format specifier. 8575 const Expr *Ex = getDataArg(argIndex); 8576 if (!Ex) 8577 return true; 8578 8579 const analyze_format_string::ArgType &AT = FS.getArgType(S.Context); 8580 8581 if (!AT.isValid()) { 8582 return true; 8583 } 8584 8585 analyze_format_string::ArgType::MatchKind Match = 8586 AT.matchesType(S.Context, Ex->getType()); 8587 bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic; 8588 if (Match == analyze_format_string::ArgType::Match) 8589 return true; 8590 8591 ScanfSpecifier fixedFS = FS; 8592 bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(), 8593 S.getLangOpts(), S.Context); 8594 8595 unsigned Diag = 8596 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic 8597 : diag::warn_format_conversion_argument_type_mismatch; 8598 8599 if (Success) { 8600 // Get the fix string from the fixed format specifier. 8601 SmallString<128> buf; 8602 llvm::raw_svector_ostream os(buf); 8603 fixedFS.toString(os); 8604 8605 EmitFormatDiagnostic( 8606 S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) 8607 << Ex->getType() << false << Ex->getSourceRange(), 8608 Ex->getBeginLoc(), 8609 /*IsStringLocation*/ false, 8610 getSpecifierRange(startSpecifier, specifierLen), 8611 FixItHint::CreateReplacement( 8612 getSpecifierRange(startSpecifier, specifierLen), os.str())); 8613 } else { 8614 EmitFormatDiagnostic(S.PDiag(Diag) 8615 << AT.getRepresentativeTypeName(S.Context) 8616 << Ex->getType() << false << Ex->getSourceRange(), 8617 Ex->getBeginLoc(), 8618 /*IsStringLocation*/ false, 8619 getSpecifierRange(startSpecifier, specifierLen)); 8620 } 8621 8622 return true; 8623 } 8624 8625 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, 8626 const Expr *OrigFormatExpr, 8627 ArrayRef<const Expr *> Args, 8628 bool HasVAListArg, unsigned format_idx, 8629 unsigned firstDataArg, 8630 Sema::FormatStringType Type, 8631 bool inFunctionCall, 8632 Sema::VariadicCallType CallType, 8633 llvm::SmallBitVector &CheckedVarArgs, 8634 UncoveredArgHandler &UncoveredArg, 8635 bool IgnoreStringsWithoutSpecifiers) { 8636 // CHECK: is the format string a wide literal? 8637 if (!FExpr->isAscii() && !FExpr->isUTF8()) { 8638 CheckFormatHandler::EmitFormatDiagnostic( 8639 S, inFunctionCall, Args[format_idx], 8640 S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(), 8641 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8642 return; 8643 } 8644 8645 // Str - The format string. NOTE: this is NOT null-terminated! 8646 StringRef StrRef = FExpr->getString(); 8647 const char *Str = StrRef.data(); 8648 // Account for cases where the string literal is truncated in a declaration. 8649 const ConstantArrayType *T = 8650 S.Context.getAsConstantArrayType(FExpr->getType()); 8651 assert(T && "String literal not of constant array type!"); 8652 size_t TypeSize = T->getSize().getZExtValue(); 8653 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8654 const unsigned numDataArgs = Args.size() - firstDataArg; 8655 8656 if (IgnoreStringsWithoutSpecifiers && 8657 !analyze_format_string::parseFormatStringHasFormattingSpecifiers( 8658 Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo())) 8659 return; 8660 8661 // Emit a warning if the string literal is truncated and does not contain an 8662 // embedded null character. 8663 if (TypeSize <= StrRef.size() && 8664 StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) { 8665 CheckFormatHandler::EmitFormatDiagnostic( 8666 S, inFunctionCall, Args[format_idx], 8667 S.PDiag(diag::warn_printf_format_string_not_null_terminated), 8668 FExpr->getBeginLoc(), 8669 /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange()); 8670 return; 8671 } 8672 8673 // CHECK: empty format string? 8674 if (StrLen == 0 && numDataArgs > 0) { 8675 CheckFormatHandler::EmitFormatDiagnostic( 8676 S, inFunctionCall, Args[format_idx], 8677 S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(), 8678 /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange()); 8679 return; 8680 } 8681 8682 if (Type == Sema::FST_Printf || Type == Sema::FST_NSString || 8683 Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog || 8684 Type == Sema::FST_OSTrace) { 8685 CheckPrintfHandler H( 8686 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs, 8687 (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str, 8688 HasVAListArg, Args, format_idx, inFunctionCall, CallType, 8689 CheckedVarArgs, UncoveredArg); 8690 8691 if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen, 8692 S.getLangOpts(), 8693 S.Context.getTargetInfo(), 8694 Type == Sema::FST_FreeBSDKPrintf)) 8695 H.DoneProcessing(); 8696 } else if (Type == Sema::FST_Scanf) { 8697 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg, 8698 numDataArgs, Str, HasVAListArg, Args, format_idx, 8699 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg); 8700 8701 if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen, 8702 S.getLangOpts(), 8703 S.Context.getTargetInfo())) 8704 H.DoneProcessing(); 8705 } // TODO: handle other formats 8706 } 8707 8708 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) { 8709 // Str - The format string. NOTE: this is NOT null-terminated! 8710 StringRef StrRef = FExpr->getString(); 8711 const char *Str = StrRef.data(); 8712 // Account for cases where the string literal is truncated in a declaration. 8713 const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType()); 8714 assert(T && "String literal not of constant array type!"); 8715 size_t TypeSize = T->getSize().getZExtValue(); 8716 size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size()); 8717 return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen, 8718 getLangOpts(), 8719 Context.getTargetInfo()); 8720 } 8721 8722 //===--- CHECK: Warn on use of wrong absolute value function. -------------===// 8723 8724 // Returns the related absolute value function that is larger, of 0 if one 8725 // does not exist. 8726 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) { 8727 switch (AbsFunction) { 8728 default: 8729 return 0; 8730 8731 case Builtin::BI__builtin_abs: 8732 return Builtin::BI__builtin_labs; 8733 case Builtin::BI__builtin_labs: 8734 return Builtin::BI__builtin_llabs; 8735 case Builtin::BI__builtin_llabs: 8736 return 0; 8737 8738 case Builtin::BI__builtin_fabsf: 8739 return Builtin::BI__builtin_fabs; 8740 case Builtin::BI__builtin_fabs: 8741 return Builtin::BI__builtin_fabsl; 8742 case Builtin::BI__builtin_fabsl: 8743 return 0; 8744 8745 case Builtin::BI__builtin_cabsf: 8746 return Builtin::BI__builtin_cabs; 8747 case Builtin::BI__builtin_cabs: 8748 return Builtin::BI__builtin_cabsl; 8749 case Builtin::BI__builtin_cabsl: 8750 return 0; 8751 8752 case Builtin::BIabs: 8753 return Builtin::BIlabs; 8754 case Builtin::BIlabs: 8755 return Builtin::BIllabs; 8756 case Builtin::BIllabs: 8757 return 0; 8758 8759 case Builtin::BIfabsf: 8760 return Builtin::BIfabs; 8761 case Builtin::BIfabs: 8762 return Builtin::BIfabsl; 8763 case Builtin::BIfabsl: 8764 return 0; 8765 8766 case Builtin::BIcabsf: 8767 return Builtin::BIcabs; 8768 case Builtin::BIcabs: 8769 return Builtin::BIcabsl; 8770 case Builtin::BIcabsl: 8771 return 0; 8772 } 8773 } 8774 8775 // Returns the argument type of the absolute value function. 8776 static QualType getAbsoluteValueArgumentType(ASTContext &Context, 8777 unsigned AbsType) { 8778 if (AbsType == 0) 8779 return QualType(); 8780 8781 ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None; 8782 QualType BuiltinType = Context.GetBuiltinType(AbsType, Error); 8783 if (Error != ASTContext::GE_None) 8784 return QualType(); 8785 8786 const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>(); 8787 if (!FT) 8788 return QualType(); 8789 8790 if (FT->getNumParams() != 1) 8791 return QualType(); 8792 8793 return FT->getParamType(0); 8794 } 8795 8796 // Returns the best absolute value function, or zero, based on type and 8797 // current absolute value function. 8798 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, 8799 unsigned AbsFunctionKind) { 8800 unsigned BestKind = 0; 8801 uint64_t ArgSize = Context.getTypeSize(ArgType); 8802 for (unsigned Kind = AbsFunctionKind; Kind != 0; 8803 Kind = getLargerAbsoluteValueFunction(Kind)) { 8804 QualType ParamType = getAbsoluteValueArgumentType(Context, Kind); 8805 if (Context.getTypeSize(ParamType) >= ArgSize) { 8806 if (BestKind == 0) 8807 BestKind = Kind; 8808 else if (Context.hasSameType(ParamType, ArgType)) { 8809 BestKind = Kind; 8810 break; 8811 } 8812 } 8813 } 8814 return BestKind; 8815 } 8816 8817 enum AbsoluteValueKind { 8818 AVK_Integer, 8819 AVK_Floating, 8820 AVK_Complex 8821 }; 8822 8823 static AbsoluteValueKind getAbsoluteValueKind(QualType T) { 8824 if (T->isIntegralOrEnumerationType()) 8825 return AVK_Integer; 8826 if (T->isRealFloatingType()) 8827 return AVK_Floating; 8828 if (T->isAnyComplexType()) 8829 return AVK_Complex; 8830 8831 llvm_unreachable("Type not integer, floating, or complex"); 8832 } 8833 8834 // Changes the absolute value function to a different type. Preserves whether 8835 // the function is a builtin. 8836 static unsigned changeAbsFunction(unsigned AbsKind, 8837 AbsoluteValueKind ValueKind) { 8838 switch (ValueKind) { 8839 case AVK_Integer: 8840 switch (AbsKind) { 8841 default: 8842 return 0; 8843 case Builtin::BI__builtin_fabsf: 8844 case Builtin::BI__builtin_fabs: 8845 case Builtin::BI__builtin_fabsl: 8846 case Builtin::BI__builtin_cabsf: 8847 case Builtin::BI__builtin_cabs: 8848 case Builtin::BI__builtin_cabsl: 8849 return Builtin::BI__builtin_abs; 8850 case Builtin::BIfabsf: 8851 case Builtin::BIfabs: 8852 case Builtin::BIfabsl: 8853 case Builtin::BIcabsf: 8854 case Builtin::BIcabs: 8855 case Builtin::BIcabsl: 8856 return Builtin::BIabs; 8857 } 8858 case AVK_Floating: 8859 switch (AbsKind) { 8860 default: 8861 return 0; 8862 case Builtin::BI__builtin_abs: 8863 case Builtin::BI__builtin_labs: 8864 case Builtin::BI__builtin_llabs: 8865 case Builtin::BI__builtin_cabsf: 8866 case Builtin::BI__builtin_cabs: 8867 case Builtin::BI__builtin_cabsl: 8868 return Builtin::BI__builtin_fabsf; 8869 case Builtin::BIabs: 8870 case Builtin::BIlabs: 8871 case Builtin::BIllabs: 8872 case Builtin::BIcabsf: 8873 case Builtin::BIcabs: 8874 case Builtin::BIcabsl: 8875 return Builtin::BIfabsf; 8876 } 8877 case AVK_Complex: 8878 switch (AbsKind) { 8879 default: 8880 return 0; 8881 case Builtin::BI__builtin_abs: 8882 case Builtin::BI__builtin_labs: 8883 case Builtin::BI__builtin_llabs: 8884 case Builtin::BI__builtin_fabsf: 8885 case Builtin::BI__builtin_fabs: 8886 case Builtin::BI__builtin_fabsl: 8887 return Builtin::BI__builtin_cabsf; 8888 case Builtin::BIabs: 8889 case Builtin::BIlabs: 8890 case Builtin::BIllabs: 8891 case Builtin::BIfabsf: 8892 case Builtin::BIfabs: 8893 case Builtin::BIfabsl: 8894 return Builtin::BIcabsf; 8895 } 8896 } 8897 llvm_unreachable("Unable to convert function"); 8898 } 8899 8900 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) { 8901 const IdentifierInfo *FnInfo = FDecl->getIdentifier(); 8902 if (!FnInfo) 8903 return 0; 8904 8905 switch (FDecl->getBuiltinID()) { 8906 default: 8907 return 0; 8908 case Builtin::BI__builtin_abs: 8909 case Builtin::BI__builtin_fabs: 8910 case Builtin::BI__builtin_fabsf: 8911 case Builtin::BI__builtin_fabsl: 8912 case Builtin::BI__builtin_labs: 8913 case Builtin::BI__builtin_llabs: 8914 case Builtin::BI__builtin_cabs: 8915 case Builtin::BI__builtin_cabsf: 8916 case Builtin::BI__builtin_cabsl: 8917 case Builtin::BIabs: 8918 case Builtin::BIlabs: 8919 case Builtin::BIllabs: 8920 case Builtin::BIfabs: 8921 case Builtin::BIfabsf: 8922 case Builtin::BIfabsl: 8923 case Builtin::BIcabs: 8924 case Builtin::BIcabsf: 8925 case Builtin::BIcabsl: 8926 return FDecl->getBuiltinID(); 8927 } 8928 llvm_unreachable("Unknown Builtin type"); 8929 } 8930 8931 // If the replacement is valid, emit a note with replacement function. 8932 // Additionally, suggest including the proper header if not already included. 8933 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, 8934 unsigned AbsKind, QualType ArgType) { 8935 bool EmitHeaderHint = true; 8936 const char *HeaderName = nullptr; 8937 const char *FunctionName = nullptr; 8938 if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) { 8939 FunctionName = "std::abs"; 8940 if (ArgType->isIntegralOrEnumerationType()) { 8941 HeaderName = "cstdlib"; 8942 } else if (ArgType->isRealFloatingType()) { 8943 HeaderName = "cmath"; 8944 } else { 8945 llvm_unreachable("Invalid Type"); 8946 } 8947 8948 // Lookup all std::abs 8949 if (NamespaceDecl *Std = S.getStdNamespace()) { 8950 LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName); 8951 R.suppressDiagnostics(); 8952 S.LookupQualifiedName(R, Std); 8953 8954 for (const auto *I : R) { 8955 const FunctionDecl *FDecl = nullptr; 8956 if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) { 8957 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl()); 8958 } else { 8959 FDecl = dyn_cast<FunctionDecl>(I); 8960 } 8961 if (!FDecl) 8962 continue; 8963 8964 // Found std::abs(), check that they are the right ones. 8965 if (FDecl->getNumParams() != 1) 8966 continue; 8967 8968 // Check that the parameter type can handle the argument. 8969 QualType ParamType = FDecl->getParamDecl(0)->getType(); 8970 if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) && 8971 S.Context.getTypeSize(ArgType) <= 8972 S.Context.getTypeSize(ParamType)) { 8973 // Found a function, don't need the header hint. 8974 EmitHeaderHint = false; 8975 break; 8976 } 8977 } 8978 } 8979 } else { 8980 FunctionName = S.Context.BuiltinInfo.getName(AbsKind); 8981 HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind); 8982 8983 if (HeaderName) { 8984 DeclarationName DN(&S.Context.Idents.get(FunctionName)); 8985 LookupResult R(S, DN, Loc, Sema::LookupAnyName); 8986 R.suppressDiagnostics(); 8987 S.LookupName(R, S.getCurScope()); 8988 8989 if (R.isSingleResult()) { 8990 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl()); 8991 if (FD && FD->getBuiltinID() == AbsKind) { 8992 EmitHeaderHint = false; 8993 } else { 8994 return; 8995 } 8996 } else if (!R.empty()) { 8997 return; 8998 } 8999 } 9000 } 9001 9002 S.Diag(Loc, diag::note_replace_abs_function) 9003 << FunctionName << FixItHint::CreateReplacement(Range, FunctionName); 9004 9005 if (!HeaderName) 9006 return; 9007 9008 if (!EmitHeaderHint) 9009 return; 9010 9011 S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName 9012 << FunctionName; 9013 } 9014 9015 template <std::size_t StrLen> 9016 static bool IsStdFunction(const FunctionDecl *FDecl, 9017 const char (&Str)[StrLen]) { 9018 if (!FDecl) 9019 return false; 9020 if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str)) 9021 return false; 9022 if (!FDecl->isInStdNamespace()) 9023 return false; 9024 9025 return true; 9026 } 9027 9028 // Warn when using the wrong abs() function. 9029 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call, 9030 const FunctionDecl *FDecl) { 9031 if (Call->getNumArgs() != 1) 9032 return; 9033 9034 unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl); 9035 bool IsStdAbs = IsStdFunction(FDecl, "abs"); 9036 if (AbsKind == 0 && !IsStdAbs) 9037 return; 9038 9039 QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9040 QualType ParamType = Call->getArg(0)->getType(); 9041 9042 // Unsigned types cannot be negative. Suggest removing the absolute value 9043 // function call. 9044 if (ArgType->isUnsignedIntegerType()) { 9045 const char *FunctionName = 9046 IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind); 9047 Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType; 9048 Diag(Call->getExprLoc(), diag::note_remove_abs) 9049 << FunctionName 9050 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()); 9051 return; 9052 } 9053 9054 // Taking the absolute value of a pointer is very suspicious, they probably 9055 // wanted to index into an array, dereference a pointer, call a function, etc. 9056 if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) { 9057 unsigned DiagType = 0; 9058 if (ArgType->isFunctionType()) 9059 DiagType = 1; 9060 else if (ArgType->isArrayType()) 9061 DiagType = 2; 9062 9063 Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType; 9064 return; 9065 } 9066 9067 // std::abs has overloads which prevent most of the absolute value problems 9068 // from occurring. 9069 if (IsStdAbs) 9070 return; 9071 9072 AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType); 9073 AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType); 9074 9075 // The argument and parameter are the same kind. Check if they are the right 9076 // size. 9077 if (ArgValueKind == ParamValueKind) { 9078 if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType)) 9079 return; 9080 9081 unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind); 9082 Diag(Call->getExprLoc(), diag::warn_abs_too_small) 9083 << FDecl << ArgType << ParamType; 9084 9085 if (NewAbsKind == 0) 9086 return; 9087 9088 emitReplacement(*this, Call->getExprLoc(), 9089 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9090 return; 9091 } 9092 9093 // ArgValueKind != ParamValueKind 9094 // The wrong type of absolute value function was used. Attempt to find the 9095 // proper one. 9096 unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind); 9097 NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind); 9098 if (NewAbsKind == 0) 9099 return; 9100 9101 Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type) 9102 << FDecl << ParamValueKind << ArgValueKind; 9103 9104 emitReplacement(*this, Call->getExprLoc(), 9105 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType); 9106 } 9107 9108 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===// 9109 void Sema::CheckMaxUnsignedZero(const CallExpr *Call, 9110 const FunctionDecl *FDecl) { 9111 if (!Call || !FDecl) return; 9112 9113 // Ignore template specializations and macros. 9114 if (inTemplateInstantiation()) return; 9115 if (Call->getExprLoc().isMacroID()) return; 9116 9117 // Only care about the one template argument, two function parameter std::max 9118 if (Call->getNumArgs() != 2) return; 9119 if (!IsStdFunction(FDecl, "max")) return; 9120 const auto * ArgList = FDecl->getTemplateSpecializationArgs(); 9121 if (!ArgList) return; 9122 if (ArgList->size() != 1) return; 9123 9124 // Check that template type argument is unsigned integer. 9125 const auto& TA = ArgList->get(0); 9126 if (TA.getKind() != TemplateArgument::Type) return; 9127 QualType ArgType = TA.getAsType(); 9128 if (!ArgType->isUnsignedIntegerType()) return; 9129 9130 // See if either argument is a literal zero. 9131 auto IsLiteralZeroArg = [](const Expr* E) -> bool { 9132 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E); 9133 if (!MTE) return false; 9134 const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr()); 9135 if (!Num) return false; 9136 if (Num->getValue() != 0) return false; 9137 return true; 9138 }; 9139 9140 const Expr *FirstArg = Call->getArg(0); 9141 const Expr *SecondArg = Call->getArg(1); 9142 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg); 9143 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg); 9144 9145 // Only warn when exactly one argument is zero. 9146 if (IsFirstArgZero == IsSecondArgZero) return; 9147 9148 SourceRange FirstRange = FirstArg->getSourceRange(); 9149 SourceRange SecondRange = SecondArg->getSourceRange(); 9150 9151 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange; 9152 9153 Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero) 9154 << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange; 9155 9156 // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)". 9157 SourceRange RemovalRange; 9158 if (IsFirstArgZero) { 9159 RemovalRange = SourceRange(FirstRange.getBegin(), 9160 SecondRange.getBegin().getLocWithOffset(-1)); 9161 } else { 9162 RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()), 9163 SecondRange.getEnd()); 9164 } 9165 9166 Diag(Call->getExprLoc(), diag::note_remove_max_call) 9167 << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange()) 9168 << FixItHint::CreateRemoval(RemovalRange); 9169 } 9170 9171 //===--- CHECK: Standard memory functions ---------------------------------===// 9172 9173 /// Takes the expression passed to the size_t parameter of functions 9174 /// such as memcmp, strncat, etc and warns if it's a comparison. 9175 /// 9176 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`. 9177 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, 9178 IdentifierInfo *FnName, 9179 SourceLocation FnLoc, 9180 SourceLocation RParenLoc) { 9181 const BinaryOperator *Size = dyn_cast<BinaryOperator>(E); 9182 if (!Size) 9183 return false; 9184 9185 // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||: 9186 if (!Size->isComparisonOp() && !Size->isLogicalOp()) 9187 return false; 9188 9189 SourceRange SizeRange = Size->getSourceRange(); 9190 S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison) 9191 << SizeRange << FnName; 9192 S.Diag(FnLoc, diag::note_memsize_comparison_paren) 9193 << FnName 9194 << FixItHint::CreateInsertion( 9195 S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")") 9196 << FixItHint::CreateRemoval(RParenLoc); 9197 S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence) 9198 << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(") 9199 << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()), 9200 ")"); 9201 9202 return true; 9203 } 9204 9205 /// Determine whether the given type is or contains a dynamic class type 9206 /// (e.g., whether it has a vtable). 9207 static const CXXRecordDecl *getContainedDynamicClass(QualType T, 9208 bool &IsContained) { 9209 // Look through array types while ignoring qualifiers. 9210 const Type *Ty = T->getBaseElementTypeUnsafe(); 9211 IsContained = false; 9212 9213 const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl(); 9214 RD = RD ? RD->getDefinition() : nullptr; 9215 if (!RD || RD->isInvalidDecl()) 9216 return nullptr; 9217 9218 if (RD->isDynamicClass()) 9219 return RD; 9220 9221 // Check all the fields. If any bases were dynamic, the class is dynamic. 9222 // It's impossible for a class to transitively contain itself by value, so 9223 // infinite recursion is impossible. 9224 for (auto *FD : RD->fields()) { 9225 bool SubContained; 9226 if (const CXXRecordDecl *ContainedRD = 9227 getContainedDynamicClass(FD->getType(), SubContained)) { 9228 IsContained = true; 9229 return ContainedRD; 9230 } 9231 } 9232 9233 return nullptr; 9234 } 9235 9236 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) { 9237 if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E)) 9238 if (Unary->getKind() == UETT_SizeOf) 9239 return Unary; 9240 return nullptr; 9241 } 9242 9243 /// If E is a sizeof expression, returns its argument expression, 9244 /// otherwise returns NULL. 9245 static const Expr *getSizeOfExprArg(const Expr *E) { 9246 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9247 if (!SizeOf->isArgumentType()) 9248 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts(); 9249 return nullptr; 9250 } 9251 9252 /// If E is a sizeof expression, returns its argument type. 9253 static QualType getSizeOfArgType(const Expr *E) { 9254 if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E)) 9255 return SizeOf->getTypeOfArgument(); 9256 return QualType(); 9257 } 9258 9259 namespace { 9260 9261 struct SearchNonTrivialToInitializeField 9262 : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> { 9263 using Super = 9264 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>; 9265 9266 SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {} 9267 9268 void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT, 9269 SourceLocation SL) { 9270 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9271 asDerived().visitArray(PDIK, AT, SL); 9272 return; 9273 } 9274 9275 Super::visitWithKind(PDIK, FT, SL); 9276 } 9277 9278 void visitARCStrong(QualType FT, SourceLocation SL) { 9279 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9280 } 9281 void visitARCWeak(QualType FT, SourceLocation SL) { 9282 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1); 9283 } 9284 void visitStruct(QualType FT, SourceLocation SL) { 9285 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9286 visit(FD->getType(), FD->getLocation()); 9287 } 9288 void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK, 9289 const ArrayType *AT, SourceLocation SL) { 9290 visit(getContext().getBaseElementType(AT), SL); 9291 } 9292 void visitTrivial(QualType FT, SourceLocation SL) {} 9293 9294 static void diag(QualType RT, const Expr *E, Sema &S) { 9295 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation()); 9296 } 9297 9298 ASTContext &getContext() { return S.getASTContext(); } 9299 9300 const Expr *E; 9301 Sema &S; 9302 }; 9303 9304 struct SearchNonTrivialToCopyField 9305 : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> { 9306 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>; 9307 9308 SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {} 9309 9310 void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT, 9311 SourceLocation SL) { 9312 if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) { 9313 asDerived().visitArray(PCK, AT, SL); 9314 return; 9315 } 9316 9317 Super::visitWithKind(PCK, FT, SL); 9318 } 9319 9320 void visitARCStrong(QualType FT, SourceLocation SL) { 9321 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9322 } 9323 void visitARCWeak(QualType FT, SourceLocation SL) { 9324 S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0); 9325 } 9326 void visitStruct(QualType FT, SourceLocation SL) { 9327 for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields()) 9328 visit(FD->getType(), FD->getLocation()); 9329 } 9330 void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT, 9331 SourceLocation SL) { 9332 visit(getContext().getBaseElementType(AT), SL); 9333 } 9334 void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT, 9335 SourceLocation SL) {} 9336 void visitTrivial(QualType FT, SourceLocation SL) {} 9337 void visitVolatileTrivial(QualType FT, SourceLocation SL) {} 9338 9339 static void diag(QualType RT, const Expr *E, Sema &S) { 9340 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation()); 9341 } 9342 9343 ASTContext &getContext() { return S.getASTContext(); } 9344 9345 const Expr *E; 9346 Sema &S; 9347 }; 9348 9349 } 9350 9351 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object. 9352 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) { 9353 SizeofExpr = SizeofExpr->IgnoreParenImpCasts(); 9354 9355 if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) { 9356 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add) 9357 return false; 9358 9359 return doesExprLikelyComputeSize(BO->getLHS()) || 9360 doesExprLikelyComputeSize(BO->getRHS()); 9361 } 9362 9363 return getAsSizeOfExpr(SizeofExpr) != nullptr; 9364 } 9365 9366 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc. 9367 /// 9368 /// \code 9369 /// #define MACRO 0 9370 /// foo(MACRO); 9371 /// foo(0); 9372 /// \endcode 9373 /// 9374 /// This should return true for the first call to foo, but not for the second 9375 /// (regardless of whether foo is a macro or function). 9376 static bool isArgumentExpandedFromMacro(SourceManager &SM, 9377 SourceLocation CallLoc, 9378 SourceLocation ArgLoc) { 9379 if (!CallLoc.isMacroID()) 9380 return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc); 9381 9382 return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) != 9383 SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc)); 9384 } 9385 9386 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the 9387 /// last two arguments transposed. 9388 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) { 9389 if (BId != Builtin::BImemset && BId != Builtin::BIbzero) 9390 return; 9391 9392 const Expr *SizeArg = 9393 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts(); 9394 9395 auto isLiteralZero = [](const Expr *E) { 9396 return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0; 9397 }; 9398 9399 // If we're memsetting or bzeroing 0 bytes, then this is likely an error. 9400 SourceLocation CallLoc = Call->getRParenLoc(); 9401 SourceManager &SM = S.getSourceManager(); 9402 if (isLiteralZero(SizeArg) && 9403 !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) { 9404 9405 SourceLocation DiagLoc = SizeArg->getExprLoc(); 9406 9407 // Some platforms #define bzero to __builtin_memset. See if this is the 9408 // case, and if so, emit a better diagnostic. 9409 if (BId == Builtin::BIbzero || 9410 (CallLoc.isMacroID() && Lexer::getImmediateMacroName( 9411 CallLoc, SM, S.getLangOpts()) == "bzero")) { 9412 S.Diag(DiagLoc, diag::warn_suspicious_bzero_size); 9413 S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence); 9414 } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) { 9415 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0; 9416 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0; 9417 } 9418 return; 9419 } 9420 9421 // If the second argument to a memset is a sizeof expression and the third 9422 // isn't, this is also likely an error. This should catch 9423 // 'memset(buf, sizeof(buf), 0xff)'. 9424 if (BId == Builtin::BImemset && 9425 doesExprLikelyComputeSize(Call->getArg(1)) && 9426 !doesExprLikelyComputeSize(Call->getArg(2))) { 9427 SourceLocation DiagLoc = Call->getArg(1)->getExprLoc(); 9428 S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1; 9429 S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1; 9430 return; 9431 } 9432 } 9433 9434 /// Check for dangerous or invalid arguments to memset(). 9435 /// 9436 /// This issues warnings on known problematic, dangerous or unspecified 9437 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp' 9438 /// function calls. 9439 /// 9440 /// \param Call The call expression to diagnose. 9441 void Sema::CheckMemaccessArguments(const CallExpr *Call, 9442 unsigned BId, 9443 IdentifierInfo *FnName) { 9444 assert(BId != 0); 9445 9446 // It is possible to have a non-standard definition of memset. Validate 9447 // we have enough arguments, and if not, abort further checking. 9448 unsigned ExpectedNumArgs = 9449 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3); 9450 if (Call->getNumArgs() < ExpectedNumArgs) 9451 return; 9452 9453 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero || 9454 BId == Builtin::BIstrndup ? 1 : 2); 9455 unsigned LenArg = 9456 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2); 9457 const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts(); 9458 9459 if (CheckMemorySizeofForComparison(*this, LenExpr, FnName, 9460 Call->getBeginLoc(), Call->getRParenLoc())) 9461 return; 9462 9463 // Catch cases like 'memset(buf, sizeof(buf), 0)'. 9464 CheckMemaccessSize(*this, BId, Call); 9465 9466 // We have special checking when the length is a sizeof expression. 9467 QualType SizeOfArgTy = getSizeOfArgType(LenExpr); 9468 const Expr *SizeOfArg = getSizeOfExprArg(LenExpr); 9469 llvm::FoldingSetNodeID SizeOfArgID; 9470 9471 // Although widely used, 'bzero' is not a standard function. Be more strict 9472 // with the argument types before allowing diagnostics and only allow the 9473 // form bzero(ptr, sizeof(...)). 9474 QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType(); 9475 if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>()) 9476 return; 9477 9478 for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) { 9479 const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts(); 9480 SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange(); 9481 9482 QualType DestTy = Dest->getType(); 9483 QualType PointeeTy; 9484 if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) { 9485 PointeeTy = DestPtrTy->getPointeeType(); 9486 9487 // Never warn about void type pointers. This can be used to suppress 9488 // false positives. 9489 if (PointeeTy->isVoidType()) 9490 continue; 9491 9492 // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by 9493 // actually comparing the expressions for equality. Because computing the 9494 // expression IDs can be expensive, we only do this if the diagnostic is 9495 // enabled. 9496 if (SizeOfArg && 9497 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, 9498 SizeOfArg->getExprLoc())) { 9499 // We only compute IDs for expressions if the warning is enabled, and 9500 // cache the sizeof arg's ID. 9501 if (SizeOfArgID == llvm::FoldingSetNodeID()) 9502 SizeOfArg->Profile(SizeOfArgID, Context, true); 9503 llvm::FoldingSetNodeID DestID; 9504 Dest->Profile(DestID, Context, true); 9505 if (DestID == SizeOfArgID) { 9506 // TODO: For strncpy() and friends, this could suggest sizeof(dst) 9507 // over sizeof(src) as well. 9508 unsigned ActionIdx = 0; // Default is to suggest dereferencing. 9509 StringRef ReadableName = FnName->getName(); 9510 9511 if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest)) 9512 if (UnaryOp->getOpcode() == UO_AddrOf) 9513 ActionIdx = 1; // If its an address-of operator, just remove it. 9514 if (!PointeeTy->isIncompleteType() && 9515 (Context.getTypeSize(PointeeTy) == Context.getCharWidth())) 9516 ActionIdx = 2; // If the pointee's size is sizeof(char), 9517 // suggest an explicit length. 9518 9519 // If the function is defined as a builtin macro, do not show macro 9520 // expansion. 9521 SourceLocation SL = SizeOfArg->getExprLoc(); 9522 SourceRange DSR = Dest->getSourceRange(); 9523 SourceRange SSR = SizeOfArg->getSourceRange(); 9524 SourceManager &SM = getSourceManager(); 9525 9526 if (SM.isMacroArgExpansion(SL)) { 9527 ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts); 9528 SL = SM.getSpellingLoc(SL); 9529 DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()), 9530 SM.getSpellingLoc(DSR.getEnd())); 9531 SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()), 9532 SM.getSpellingLoc(SSR.getEnd())); 9533 } 9534 9535 DiagRuntimeBehavior(SL, SizeOfArg, 9536 PDiag(diag::warn_sizeof_pointer_expr_memaccess) 9537 << ReadableName 9538 << PointeeTy 9539 << DestTy 9540 << DSR 9541 << SSR); 9542 DiagRuntimeBehavior(SL, SizeOfArg, 9543 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note) 9544 << ActionIdx 9545 << SSR); 9546 9547 break; 9548 } 9549 } 9550 9551 // Also check for cases where the sizeof argument is the exact same 9552 // type as the memory argument, and where it points to a user-defined 9553 // record type. 9554 if (SizeOfArgTy != QualType()) { 9555 if (PointeeTy->isRecordType() && 9556 Context.typesAreCompatible(SizeOfArgTy, DestTy)) { 9557 DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest, 9558 PDiag(diag::warn_sizeof_pointer_type_memaccess) 9559 << FnName << SizeOfArgTy << ArgIdx 9560 << PointeeTy << Dest->getSourceRange() 9561 << LenExpr->getSourceRange()); 9562 break; 9563 } 9564 } 9565 } else if (DestTy->isArrayType()) { 9566 PointeeTy = DestTy; 9567 } 9568 9569 if (PointeeTy == QualType()) 9570 continue; 9571 9572 // Always complain about dynamic classes. 9573 bool IsContained; 9574 if (const CXXRecordDecl *ContainedRD = 9575 getContainedDynamicClass(PointeeTy, IsContained)) { 9576 9577 unsigned OperationType = 0; 9578 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp; 9579 // "overwritten" if we're warning about the destination for any call 9580 // but memcmp; otherwise a verb appropriate to the call. 9581 if (ArgIdx != 0 || IsCmp) { 9582 if (BId == Builtin::BImemcpy) 9583 OperationType = 1; 9584 else if(BId == Builtin::BImemmove) 9585 OperationType = 2; 9586 else if (IsCmp) 9587 OperationType = 3; 9588 } 9589 9590 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9591 PDiag(diag::warn_dyn_class_memaccess) 9592 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName 9593 << IsContained << ContainedRD << OperationType 9594 << Call->getCallee()->getSourceRange()); 9595 } else if (PointeeTy.hasNonTrivialObjCLifetime() && 9596 BId != Builtin::BImemset) 9597 DiagRuntimeBehavior( 9598 Dest->getExprLoc(), Dest, 9599 PDiag(diag::warn_arc_object_memaccess) 9600 << ArgIdx << FnName << PointeeTy 9601 << Call->getCallee()->getSourceRange()); 9602 else if (const auto *RT = PointeeTy->getAs<RecordType>()) { 9603 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) && 9604 RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) { 9605 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9606 PDiag(diag::warn_cstruct_memaccess) 9607 << ArgIdx << FnName << PointeeTy << 0); 9608 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this); 9609 } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) && 9610 RT->getDecl()->isNonTrivialToPrimitiveCopy()) { 9611 DiagRuntimeBehavior(Dest->getExprLoc(), Dest, 9612 PDiag(diag::warn_cstruct_memaccess) 9613 << ArgIdx << FnName << PointeeTy << 1); 9614 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this); 9615 } else { 9616 continue; 9617 } 9618 } else 9619 continue; 9620 9621 DiagRuntimeBehavior( 9622 Dest->getExprLoc(), Dest, 9623 PDiag(diag::note_bad_memaccess_silence) 9624 << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)")); 9625 break; 9626 } 9627 } 9628 9629 // A little helper routine: ignore addition and subtraction of integer literals. 9630 // This intentionally does not ignore all integer constant expressions because 9631 // we don't want to remove sizeof(). 9632 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) { 9633 Ex = Ex->IgnoreParenCasts(); 9634 9635 while (true) { 9636 const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex); 9637 if (!BO || !BO->isAdditiveOp()) 9638 break; 9639 9640 const Expr *RHS = BO->getRHS()->IgnoreParenCasts(); 9641 const Expr *LHS = BO->getLHS()->IgnoreParenCasts(); 9642 9643 if (isa<IntegerLiteral>(RHS)) 9644 Ex = LHS; 9645 else if (isa<IntegerLiteral>(LHS)) 9646 Ex = RHS; 9647 else 9648 break; 9649 } 9650 9651 return Ex; 9652 } 9653 9654 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, 9655 ASTContext &Context) { 9656 // Only handle constant-sized or VLAs, but not flexible members. 9657 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) { 9658 // Only issue the FIXIT for arrays of size > 1. 9659 if (CAT->getSize().getSExtValue() <= 1) 9660 return false; 9661 } else if (!Ty->isVariableArrayType()) { 9662 return false; 9663 } 9664 return true; 9665 } 9666 9667 // Warn if the user has made the 'size' argument to strlcpy or strlcat 9668 // be the size of the source, instead of the destination. 9669 void Sema::CheckStrlcpycatArguments(const CallExpr *Call, 9670 IdentifierInfo *FnName) { 9671 9672 // Don't crash if the user has the wrong number of arguments 9673 unsigned NumArgs = Call->getNumArgs(); 9674 if ((NumArgs != 3) && (NumArgs != 4)) 9675 return; 9676 9677 const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context); 9678 const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context); 9679 const Expr *CompareWithSrc = nullptr; 9680 9681 if (CheckMemorySizeofForComparison(*this, SizeArg, FnName, 9682 Call->getBeginLoc(), Call->getRParenLoc())) 9683 return; 9684 9685 // Look for 'strlcpy(dst, x, sizeof(x))' 9686 if (const Expr *Ex = getSizeOfExprArg(SizeArg)) 9687 CompareWithSrc = Ex; 9688 else { 9689 // Look for 'strlcpy(dst, x, strlen(x))' 9690 if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) { 9691 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen && 9692 SizeCall->getNumArgs() == 1) 9693 CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context); 9694 } 9695 } 9696 9697 if (!CompareWithSrc) 9698 return; 9699 9700 // Determine if the argument to sizeof/strlen is equal to the source 9701 // argument. In principle there's all kinds of things you could do 9702 // here, for instance creating an == expression and evaluating it with 9703 // EvaluateAsBooleanCondition, but this uses a more direct technique: 9704 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg); 9705 if (!SrcArgDRE) 9706 return; 9707 9708 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc); 9709 if (!CompareWithSrcDRE || 9710 SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl()) 9711 return; 9712 9713 const Expr *OriginalSizeArg = Call->getArg(2); 9714 Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size) 9715 << OriginalSizeArg->getSourceRange() << FnName; 9716 9717 // Output a FIXIT hint if the destination is an array (rather than a 9718 // pointer to an array). This could be enhanced to handle some 9719 // pointers if we know the actual size, like if DstArg is 'array+2' 9720 // we could say 'sizeof(array)-2'. 9721 const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts(); 9722 if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context)) 9723 return; 9724 9725 SmallString<128> sizeString; 9726 llvm::raw_svector_ostream OS(sizeString); 9727 OS << "sizeof("; 9728 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9729 OS << ")"; 9730 9731 Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size) 9732 << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(), 9733 OS.str()); 9734 } 9735 9736 /// Check if two expressions refer to the same declaration. 9737 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) { 9738 if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1)) 9739 if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2)) 9740 return D1->getDecl() == D2->getDecl(); 9741 return false; 9742 } 9743 9744 static const Expr *getStrlenExprArg(const Expr *E) { 9745 if (const CallExpr *CE = dyn_cast<CallExpr>(E)) { 9746 const FunctionDecl *FD = CE->getDirectCallee(); 9747 if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen) 9748 return nullptr; 9749 return CE->getArg(0)->IgnoreParenCasts(); 9750 } 9751 return nullptr; 9752 } 9753 9754 // Warn on anti-patterns as the 'size' argument to strncat. 9755 // The correct size argument should look like following: 9756 // strncat(dst, src, sizeof(dst) - strlen(dest) - 1); 9757 void Sema::CheckStrncatArguments(const CallExpr *CE, 9758 IdentifierInfo *FnName) { 9759 // Don't crash if the user has the wrong number of arguments. 9760 if (CE->getNumArgs() < 3) 9761 return; 9762 const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts(); 9763 const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts(); 9764 const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts(); 9765 9766 if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(), 9767 CE->getRParenLoc())) 9768 return; 9769 9770 // Identify common expressions, which are wrongly used as the size argument 9771 // to strncat and may lead to buffer overflows. 9772 unsigned PatternType = 0; 9773 if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) { 9774 // - sizeof(dst) 9775 if (referToTheSameDecl(SizeOfArg, DstArg)) 9776 PatternType = 1; 9777 // - sizeof(src) 9778 else if (referToTheSameDecl(SizeOfArg, SrcArg)) 9779 PatternType = 2; 9780 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) { 9781 if (BE->getOpcode() == BO_Sub) { 9782 const Expr *L = BE->getLHS()->IgnoreParenCasts(); 9783 const Expr *R = BE->getRHS()->IgnoreParenCasts(); 9784 // - sizeof(dst) - strlen(dst) 9785 if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) && 9786 referToTheSameDecl(DstArg, getStrlenExprArg(R))) 9787 PatternType = 1; 9788 // - sizeof(src) - (anything) 9789 else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L))) 9790 PatternType = 2; 9791 } 9792 } 9793 9794 if (PatternType == 0) 9795 return; 9796 9797 // Generate the diagnostic. 9798 SourceLocation SL = LenArg->getBeginLoc(); 9799 SourceRange SR = LenArg->getSourceRange(); 9800 SourceManager &SM = getSourceManager(); 9801 9802 // If the function is defined as a builtin macro, do not show macro expansion. 9803 if (SM.isMacroArgExpansion(SL)) { 9804 SL = SM.getSpellingLoc(SL); 9805 SR = SourceRange(SM.getSpellingLoc(SR.getBegin()), 9806 SM.getSpellingLoc(SR.getEnd())); 9807 } 9808 9809 // Check if the destination is an array (rather than a pointer to an array). 9810 QualType DstTy = DstArg->getType(); 9811 bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy, 9812 Context); 9813 if (!isKnownSizeArray) { 9814 if (PatternType == 1) 9815 Diag(SL, diag::warn_strncat_wrong_size) << SR; 9816 else 9817 Diag(SL, diag::warn_strncat_src_size) << SR; 9818 return; 9819 } 9820 9821 if (PatternType == 1) 9822 Diag(SL, diag::warn_strncat_large_size) << SR; 9823 else 9824 Diag(SL, diag::warn_strncat_src_size) << SR; 9825 9826 SmallString<128> sizeString; 9827 llvm::raw_svector_ostream OS(sizeString); 9828 OS << "sizeof("; 9829 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9830 OS << ") - "; 9831 OS << "strlen("; 9832 DstArg->printPretty(OS, nullptr, getPrintingPolicy()); 9833 OS << ") - 1"; 9834 9835 Diag(SL, diag::note_strncat_wrong_size) 9836 << FixItHint::CreateReplacement(SR, OS.str()); 9837 } 9838 9839 void 9840 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType, 9841 SourceLocation ReturnLoc, 9842 bool isObjCMethod, 9843 const AttrVec *Attrs, 9844 const FunctionDecl *FD) { 9845 // Check if the return value is null but should not be. 9846 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) || 9847 (!isObjCMethod && isNonNullType(Context, lhsType))) && 9848 CheckNonNullExpr(*this, RetValExp)) 9849 Diag(ReturnLoc, diag::warn_null_ret) 9850 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange(); 9851 9852 // C++11 [basic.stc.dynamic.allocation]p4: 9853 // If an allocation function declared with a non-throwing 9854 // exception-specification fails to allocate storage, it shall return 9855 // a null pointer. Any other allocation function that fails to allocate 9856 // storage shall indicate failure only by throwing an exception [...] 9857 if (FD) { 9858 OverloadedOperatorKind Op = FD->getOverloadedOperator(); 9859 if (Op == OO_New || Op == OO_Array_New) { 9860 const FunctionProtoType *Proto 9861 = FD->getType()->castAs<FunctionProtoType>(); 9862 if (!Proto->isNothrow(/*ResultIfDependent*/true) && 9863 CheckNonNullExpr(*this, RetValExp)) 9864 Diag(ReturnLoc, diag::warn_operator_new_returns_null) 9865 << FD << getLangOpts().CPlusPlus11; 9866 } 9867 } 9868 } 9869 9870 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===// 9871 9872 /// Check for comparisons of floating point operands using != and ==. 9873 /// Issue a warning if these are no self-comparisons, as they are not likely 9874 /// to do what the programmer intended. 9875 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) { 9876 Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts(); 9877 Expr* RightExprSansParen = RHS->IgnoreParenImpCasts(); 9878 9879 // Special case: check for x == x (which is OK). 9880 // Do not emit warnings for such cases. 9881 if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen)) 9882 if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen)) 9883 if (DRL->getDecl() == DRR->getDecl()) 9884 return; 9885 9886 // Special case: check for comparisons against literals that can be exactly 9887 // represented by APFloat. In such cases, do not emit a warning. This 9888 // is a heuristic: often comparison against such literals are used to 9889 // detect if a value in a variable has not changed. This clearly can 9890 // lead to false negatives. 9891 if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) { 9892 if (FLL->isExact()) 9893 return; 9894 } else 9895 if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen)) 9896 if (FLR->isExact()) 9897 return; 9898 9899 // Check for comparisons with builtin types. 9900 if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen)) 9901 if (CL->getBuiltinCallee()) 9902 return; 9903 9904 if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen)) 9905 if (CR->getBuiltinCallee()) 9906 return; 9907 9908 // Emit the diagnostic. 9909 Diag(Loc, diag::warn_floatingpoint_eq) 9910 << LHS->getSourceRange() << RHS->getSourceRange(); 9911 } 9912 9913 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===// 9914 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===// 9915 9916 namespace { 9917 9918 /// Structure recording the 'active' range of an integer-valued 9919 /// expression. 9920 struct IntRange { 9921 /// The number of bits active in the int. 9922 unsigned Width; 9923 9924 /// True if the int is known not to have negative values. 9925 bool NonNegative; 9926 9927 IntRange(unsigned Width, bool NonNegative) 9928 : Width(Width), NonNegative(NonNegative) {} 9929 9930 /// Returns the range of the bool type. 9931 static IntRange forBoolType() { 9932 return IntRange(1, true); 9933 } 9934 9935 /// Returns the range of an opaque value of the given integral type. 9936 static IntRange forValueOfType(ASTContext &C, QualType T) { 9937 return forValueOfCanonicalType(C, 9938 T->getCanonicalTypeInternal().getTypePtr()); 9939 } 9940 9941 /// Returns the range of an opaque value of a canonical integral type. 9942 static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) { 9943 assert(T->isCanonicalUnqualified()); 9944 9945 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9946 T = VT->getElementType().getTypePtr(); 9947 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9948 T = CT->getElementType().getTypePtr(); 9949 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9950 T = AT->getValueType().getTypePtr(); 9951 9952 if (!C.getLangOpts().CPlusPlus) { 9953 // For enum types in C code, use the underlying datatype. 9954 if (const EnumType *ET = dyn_cast<EnumType>(T)) 9955 T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr(); 9956 } else if (const EnumType *ET = dyn_cast<EnumType>(T)) { 9957 // For enum types in C++, use the known bit width of the enumerators. 9958 EnumDecl *Enum = ET->getDecl(); 9959 // In C++11, enums can have a fixed underlying type. Use this type to 9960 // compute the range. 9961 if (Enum->isFixed()) { 9962 return IntRange(C.getIntWidth(QualType(T, 0)), 9963 !ET->isSignedIntegerOrEnumerationType()); 9964 } 9965 9966 unsigned NumPositive = Enum->getNumPositiveBits(); 9967 unsigned NumNegative = Enum->getNumNegativeBits(); 9968 9969 if (NumNegative == 0) 9970 return IntRange(NumPositive, true/*NonNegative*/); 9971 else 9972 return IntRange(std::max(NumPositive + 1, NumNegative), 9973 false/*NonNegative*/); 9974 } 9975 9976 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 9977 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 9978 9979 const BuiltinType *BT = cast<BuiltinType>(T); 9980 assert(BT->isInteger()); 9981 9982 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 9983 } 9984 9985 /// Returns the "target" range of a canonical integral type, i.e. 9986 /// the range of values expressible in the type. 9987 /// 9988 /// This matches forValueOfCanonicalType except that enums have the 9989 /// full range of their type, not the range of their enumerators. 9990 static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) { 9991 assert(T->isCanonicalUnqualified()); 9992 9993 if (const VectorType *VT = dyn_cast<VectorType>(T)) 9994 T = VT->getElementType().getTypePtr(); 9995 if (const ComplexType *CT = dyn_cast<ComplexType>(T)) 9996 T = CT->getElementType().getTypePtr(); 9997 if (const AtomicType *AT = dyn_cast<AtomicType>(T)) 9998 T = AT->getValueType().getTypePtr(); 9999 if (const EnumType *ET = dyn_cast<EnumType>(T)) 10000 T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr(); 10001 10002 if (const auto *EIT = dyn_cast<ExtIntType>(T)) 10003 return IntRange(EIT->getNumBits(), EIT->isUnsigned()); 10004 10005 const BuiltinType *BT = cast<BuiltinType>(T); 10006 assert(BT->isInteger()); 10007 10008 return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger()); 10009 } 10010 10011 /// Returns the supremum of two ranges: i.e. their conservative merge. 10012 static IntRange join(IntRange L, IntRange R) { 10013 return IntRange(std::max(L.Width, R.Width), 10014 L.NonNegative && R.NonNegative); 10015 } 10016 10017 /// Returns the infinum of two ranges: i.e. their aggressive merge. 10018 static IntRange meet(IntRange L, IntRange R) { 10019 return IntRange(std::min(L.Width, R.Width), 10020 L.NonNegative || R.NonNegative); 10021 } 10022 }; 10023 10024 } // namespace 10025 10026 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value, 10027 unsigned MaxWidth) { 10028 if (value.isSigned() && value.isNegative()) 10029 return IntRange(value.getMinSignedBits(), false); 10030 10031 if (value.getBitWidth() > MaxWidth) 10032 value = value.trunc(MaxWidth); 10033 10034 // isNonNegative() just checks the sign bit without considering 10035 // signedness. 10036 return IntRange(value.getActiveBits(), true); 10037 } 10038 10039 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty, 10040 unsigned MaxWidth) { 10041 if (result.isInt()) 10042 return GetValueRange(C, result.getInt(), MaxWidth); 10043 10044 if (result.isVector()) { 10045 IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth); 10046 for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) { 10047 IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth); 10048 R = IntRange::join(R, El); 10049 } 10050 return R; 10051 } 10052 10053 if (result.isComplexInt()) { 10054 IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth); 10055 IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth); 10056 return IntRange::join(R, I); 10057 } 10058 10059 // This can happen with lossless casts to intptr_t of "based" lvalues. 10060 // Assume it might use arbitrary bits. 10061 // FIXME: The only reason we need to pass the type in here is to get 10062 // the sign right on this one case. It would be nice if APValue 10063 // preserved this. 10064 assert(result.isLValue() || result.isAddrLabelDiff()); 10065 return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType()); 10066 } 10067 10068 static QualType GetExprType(const Expr *E) { 10069 QualType Ty = E->getType(); 10070 if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>()) 10071 Ty = AtomicRHS->getValueType(); 10072 return Ty; 10073 } 10074 10075 /// Pseudo-evaluate the given integer expression, estimating the 10076 /// range of values it might take. 10077 /// 10078 /// \param MaxWidth - the width to which the value will be truncated 10079 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, 10080 bool InConstantContext) { 10081 E = E->IgnoreParens(); 10082 10083 // Try a full evaluation first. 10084 Expr::EvalResult result; 10085 if (E->EvaluateAsRValue(result, C, InConstantContext)) 10086 return GetValueRange(C, result.Val, GetExprType(E), MaxWidth); 10087 10088 // I think we only want to look through implicit casts here; if the 10089 // user has an explicit widening cast, we should treat the value as 10090 // being of the new, wider type. 10091 if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) { 10092 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue) 10093 return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext); 10094 10095 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE)); 10096 10097 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast || 10098 CE->getCastKind() == CK_BooleanToSignedIntegral; 10099 10100 // Assume that non-integer casts can span the full range of the type. 10101 if (!isIntegerCast) 10102 return OutputTypeRange; 10103 10104 IntRange SubRange = GetExprRange(C, CE->getSubExpr(), 10105 std::min(MaxWidth, OutputTypeRange.Width), 10106 InConstantContext); 10107 10108 // Bail out if the subexpr's range is as wide as the cast type. 10109 if (SubRange.Width >= OutputTypeRange.Width) 10110 return OutputTypeRange; 10111 10112 // Otherwise, we take the smaller width, and we're non-negative if 10113 // either the output type or the subexpr is. 10114 return IntRange(SubRange.Width, 10115 SubRange.NonNegative || OutputTypeRange.NonNegative); 10116 } 10117 10118 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 10119 // If we can fold the condition, just take that operand. 10120 bool CondResult; 10121 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C)) 10122 return GetExprRange(C, 10123 CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), 10124 MaxWidth, InConstantContext); 10125 10126 // Otherwise, conservatively merge. 10127 IntRange L = 10128 GetExprRange(C, CO->getTrueExpr(), MaxWidth, InConstantContext); 10129 IntRange R = 10130 GetExprRange(C, CO->getFalseExpr(), MaxWidth, InConstantContext); 10131 return IntRange::join(L, R); 10132 } 10133 10134 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 10135 switch (BO->getOpcode()) { 10136 case BO_Cmp: 10137 llvm_unreachable("builtin <=> should have class type"); 10138 10139 // Boolean-valued operations are single-bit and positive. 10140 case BO_LAnd: 10141 case BO_LOr: 10142 case BO_LT: 10143 case BO_GT: 10144 case BO_LE: 10145 case BO_GE: 10146 case BO_EQ: 10147 case BO_NE: 10148 return IntRange::forBoolType(); 10149 10150 // The type of the assignments is the type of the LHS, so the RHS 10151 // is not necessarily the same type. 10152 case BO_MulAssign: 10153 case BO_DivAssign: 10154 case BO_RemAssign: 10155 case BO_AddAssign: 10156 case BO_SubAssign: 10157 case BO_XorAssign: 10158 case BO_OrAssign: 10159 // TODO: bitfields? 10160 return IntRange::forValueOfType(C, GetExprType(E)); 10161 10162 // Simple assignments just pass through the RHS, which will have 10163 // been coerced to the LHS type. 10164 case BO_Assign: 10165 // TODO: bitfields? 10166 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10167 10168 // Operations with opaque sources are black-listed. 10169 case BO_PtrMemD: 10170 case BO_PtrMemI: 10171 return IntRange::forValueOfType(C, GetExprType(E)); 10172 10173 // Bitwise-and uses the *infinum* of the two source ranges. 10174 case BO_And: 10175 case BO_AndAssign: 10176 return IntRange::meet( 10177 GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext), 10178 GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext)); 10179 10180 // Left shift gets black-listed based on a judgement call. 10181 case BO_Shl: 10182 // ...except that we want to treat '1 << (blah)' as logically 10183 // positive. It's an important idiom. 10184 if (IntegerLiteral *I 10185 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) { 10186 if (I->getValue() == 1) { 10187 IntRange R = IntRange::forValueOfType(C, GetExprType(E)); 10188 return IntRange(R.Width, /*NonNegative*/ true); 10189 } 10190 } 10191 LLVM_FALLTHROUGH; 10192 10193 case BO_ShlAssign: 10194 return IntRange::forValueOfType(C, GetExprType(E)); 10195 10196 // Right shift by a constant can narrow its left argument. 10197 case BO_Shr: 10198 case BO_ShrAssign: { 10199 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10200 10201 // If the shift amount is a positive constant, drop the width by 10202 // that much. 10203 llvm::APSInt shift; 10204 if (BO->getRHS()->isIntegerConstantExpr(shift, C) && 10205 shift.isNonNegative()) { 10206 unsigned zext = shift.getZExtValue(); 10207 if (zext >= L.Width) 10208 L.Width = (L.NonNegative ? 0 : 1); 10209 else 10210 L.Width -= zext; 10211 } 10212 10213 return L; 10214 } 10215 10216 // Comma acts as its right operand. 10217 case BO_Comma: 10218 return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10219 10220 // Black-list pointer subtractions. 10221 case BO_Sub: 10222 if (BO->getLHS()->getType()->isPointerType()) 10223 return IntRange::forValueOfType(C, GetExprType(E)); 10224 break; 10225 10226 // The width of a division result is mostly determined by the size 10227 // of the LHS. 10228 case BO_Div: { 10229 // Don't 'pre-truncate' the operands. 10230 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10231 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10232 10233 // If the divisor is constant, use that. 10234 llvm::APSInt divisor; 10235 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) { 10236 unsigned log2 = divisor.logBase2(); // floor(log_2(divisor)) 10237 if (log2 >= L.Width) 10238 L.Width = (L.NonNegative ? 0 : 1); 10239 else 10240 L.Width = std::min(L.Width - log2, MaxWidth); 10241 return L; 10242 } 10243 10244 // Otherwise, just use the LHS's width. 10245 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10246 return IntRange(L.Width, L.NonNegative && R.NonNegative); 10247 } 10248 10249 // The result of a remainder can't be larger than the result of 10250 // either side. 10251 case BO_Rem: { 10252 // Don't 'pre-truncate' the operands. 10253 unsigned opWidth = C.getIntWidth(GetExprType(E)); 10254 IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext); 10255 IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext); 10256 10257 IntRange meet = IntRange::meet(L, R); 10258 meet.Width = std::min(meet.Width, MaxWidth); 10259 return meet; 10260 } 10261 10262 // The default behavior is okay for these. 10263 case BO_Mul: 10264 case BO_Add: 10265 case BO_Xor: 10266 case BO_Or: 10267 break; 10268 } 10269 10270 // The default case is to treat the operation as if it were closed 10271 // on the narrowest type that encompasses both operands. 10272 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext); 10273 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext); 10274 return IntRange::join(L, R); 10275 } 10276 10277 if (const auto *UO = dyn_cast<UnaryOperator>(E)) { 10278 switch (UO->getOpcode()) { 10279 // Boolean-valued operations are white-listed. 10280 case UO_LNot: 10281 return IntRange::forBoolType(); 10282 10283 // Operations with opaque sources are black-listed. 10284 case UO_Deref: 10285 case UO_AddrOf: // should be impossible 10286 return IntRange::forValueOfType(C, GetExprType(E)); 10287 10288 default: 10289 return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext); 10290 } 10291 } 10292 10293 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 10294 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext); 10295 10296 if (const auto *BitField = E->getSourceBitField()) 10297 return IntRange(BitField->getBitWidthValue(C), 10298 BitField->getType()->isUnsignedIntegerOrEnumerationType()); 10299 10300 return IntRange::forValueOfType(C, GetExprType(E)); 10301 } 10302 10303 static IntRange GetExprRange(ASTContext &C, const Expr *E, 10304 bool InConstantContext) { 10305 return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext); 10306 } 10307 10308 /// Checks whether the given value, which currently has the given 10309 /// source semantics, has the same value when coerced through the 10310 /// target semantics. 10311 static bool IsSameFloatAfterCast(const llvm::APFloat &value, 10312 const llvm::fltSemantics &Src, 10313 const llvm::fltSemantics &Tgt) { 10314 llvm::APFloat truncated = value; 10315 10316 bool ignored; 10317 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored); 10318 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored); 10319 10320 return truncated.bitwiseIsEqual(value); 10321 } 10322 10323 /// Checks whether the given value, which currently has the given 10324 /// source semantics, has the same value when coerced through the 10325 /// target semantics. 10326 /// 10327 /// The value might be a vector of floats (or a complex number). 10328 static bool IsSameFloatAfterCast(const APValue &value, 10329 const llvm::fltSemantics &Src, 10330 const llvm::fltSemantics &Tgt) { 10331 if (value.isFloat()) 10332 return IsSameFloatAfterCast(value.getFloat(), Src, Tgt); 10333 10334 if (value.isVector()) { 10335 for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i) 10336 if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt)) 10337 return false; 10338 return true; 10339 } 10340 10341 assert(value.isComplexFloat()); 10342 return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) && 10343 IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt)); 10344 } 10345 10346 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, 10347 bool IsListInit = false); 10348 10349 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) { 10350 // Suppress cases where we are comparing against an enum constant. 10351 if (const DeclRefExpr *DR = 10352 dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) 10353 if (isa<EnumConstantDecl>(DR->getDecl())) 10354 return true; 10355 10356 // Suppress cases where the value is expanded from a macro, unless that macro 10357 // is how a language represents a boolean literal. This is the case in both C 10358 // and Objective-C. 10359 SourceLocation BeginLoc = E->getBeginLoc(); 10360 if (BeginLoc.isMacroID()) { 10361 StringRef MacroName = Lexer::getImmediateMacroName( 10362 BeginLoc, S.getSourceManager(), S.getLangOpts()); 10363 return MacroName != "YES" && MacroName != "NO" && 10364 MacroName != "true" && MacroName != "false"; 10365 } 10366 10367 return false; 10368 } 10369 10370 static bool isKnownToHaveUnsignedValue(Expr *E) { 10371 return E->getType()->isIntegerType() && 10372 (!E->getType()->isSignedIntegerType() || 10373 !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType()); 10374 } 10375 10376 namespace { 10377 /// The promoted range of values of a type. In general this has the 10378 /// following structure: 10379 /// 10380 /// |-----------| . . . |-----------| 10381 /// ^ ^ ^ ^ 10382 /// Min HoleMin HoleMax Max 10383 /// 10384 /// ... where there is only a hole if a signed type is promoted to unsigned 10385 /// (in which case Min and Max are the smallest and largest representable 10386 /// values). 10387 struct PromotedRange { 10388 // Min, or HoleMax if there is a hole. 10389 llvm::APSInt PromotedMin; 10390 // Max, or HoleMin if there is a hole. 10391 llvm::APSInt PromotedMax; 10392 10393 PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) { 10394 if (R.Width == 0) 10395 PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned); 10396 else if (R.Width >= BitWidth && !Unsigned) { 10397 // Promotion made the type *narrower*. This happens when promoting 10398 // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'. 10399 // Treat all values of 'signed int' as being in range for now. 10400 PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned); 10401 PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned); 10402 } else { 10403 PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative) 10404 .extOrTrunc(BitWidth); 10405 PromotedMin.setIsUnsigned(Unsigned); 10406 10407 PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative) 10408 .extOrTrunc(BitWidth); 10409 PromotedMax.setIsUnsigned(Unsigned); 10410 } 10411 } 10412 10413 // Determine whether this range is contiguous (has no hole). 10414 bool isContiguous() const { return PromotedMin <= PromotedMax; } 10415 10416 // Where a constant value is within the range. 10417 enum ComparisonResult { 10418 LT = 0x1, 10419 LE = 0x2, 10420 GT = 0x4, 10421 GE = 0x8, 10422 EQ = 0x10, 10423 NE = 0x20, 10424 InRangeFlag = 0x40, 10425 10426 Less = LE | LT | NE, 10427 Min = LE | InRangeFlag, 10428 InRange = InRangeFlag, 10429 Max = GE | InRangeFlag, 10430 Greater = GE | GT | NE, 10431 10432 OnlyValue = LE | GE | EQ | InRangeFlag, 10433 InHole = NE 10434 }; 10435 10436 ComparisonResult compare(const llvm::APSInt &Value) const { 10437 assert(Value.getBitWidth() == PromotedMin.getBitWidth() && 10438 Value.isUnsigned() == PromotedMin.isUnsigned()); 10439 if (!isContiguous()) { 10440 assert(Value.isUnsigned() && "discontiguous range for signed compare"); 10441 if (Value.isMinValue()) return Min; 10442 if (Value.isMaxValue()) return Max; 10443 if (Value >= PromotedMin) return InRange; 10444 if (Value <= PromotedMax) return InRange; 10445 return InHole; 10446 } 10447 10448 switch (llvm::APSInt::compareValues(Value, PromotedMin)) { 10449 case -1: return Less; 10450 case 0: return PromotedMin == PromotedMax ? OnlyValue : Min; 10451 case 1: 10452 switch (llvm::APSInt::compareValues(Value, PromotedMax)) { 10453 case -1: return InRange; 10454 case 0: return Max; 10455 case 1: return Greater; 10456 } 10457 } 10458 10459 llvm_unreachable("impossible compare result"); 10460 } 10461 10462 static llvm::Optional<StringRef> 10463 constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) { 10464 if (Op == BO_Cmp) { 10465 ComparisonResult LTFlag = LT, GTFlag = GT; 10466 if (ConstantOnRHS) std::swap(LTFlag, GTFlag); 10467 10468 if (R & EQ) return StringRef("'std::strong_ordering::equal'"); 10469 if (R & LTFlag) return StringRef("'std::strong_ordering::less'"); 10470 if (R & GTFlag) return StringRef("'std::strong_ordering::greater'"); 10471 return llvm::None; 10472 } 10473 10474 ComparisonResult TrueFlag, FalseFlag; 10475 if (Op == BO_EQ) { 10476 TrueFlag = EQ; 10477 FalseFlag = NE; 10478 } else if (Op == BO_NE) { 10479 TrueFlag = NE; 10480 FalseFlag = EQ; 10481 } else { 10482 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) { 10483 TrueFlag = LT; 10484 FalseFlag = GE; 10485 } else { 10486 TrueFlag = GT; 10487 FalseFlag = LE; 10488 } 10489 if (Op == BO_GE || Op == BO_LE) 10490 std::swap(TrueFlag, FalseFlag); 10491 } 10492 if (R & TrueFlag) 10493 return StringRef("true"); 10494 if (R & FalseFlag) 10495 return StringRef("false"); 10496 return llvm::None; 10497 } 10498 }; 10499 } 10500 10501 static bool HasEnumType(Expr *E) { 10502 // Strip off implicit integral promotions. 10503 while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) { 10504 if (ICE->getCastKind() != CK_IntegralCast && 10505 ICE->getCastKind() != CK_NoOp) 10506 break; 10507 E = ICE->getSubExpr(); 10508 } 10509 10510 return E->getType()->isEnumeralType(); 10511 } 10512 10513 static int classifyConstantValue(Expr *Constant) { 10514 // The values of this enumeration are used in the diagnostics 10515 // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare. 10516 enum ConstantValueKind { 10517 Miscellaneous = 0, 10518 LiteralTrue, 10519 LiteralFalse 10520 }; 10521 if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant)) 10522 return BL->getValue() ? ConstantValueKind::LiteralTrue 10523 : ConstantValueKind::LiteralFalse; 10524 return ConstantValueKind::Miscellaneous; 10525 } 10526 10527 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, 10528 Expr *Constant, Expr *Other, 10529 const llvm::APSInt &Value, 10530 bool RhsConstant) { 10531 if (S.inTemplateInstantiation()) 10532 return false; 10533 10534 Expr *OriginalOther = Other; 10535 10536 Constant = Constant->IgnoreParenImpCasts(); 10537 Other = Other->IgnoreParenImpCasts(); 10538 10539 // Suppress warnings on tautological comparisons between values of the same 10540 // enumeration type. There are only two ways we could warn on this: 10541 // - If the constant is outside the range of representable values of 10542 // the enumeration. In such a case, we should warn about the cast 10543 // to enumeration type, not about the comparison. 10544 // - If the constant is the maximum / minimum in-range value. For an 10545 // enumeratin type, such comparisons can be meaningful and useful. 10546 if (Constant->getType()->isEnumeralType() && 10547 S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType())) 10548 return false; 10549 10550 // TODO: Investigate using GetExprRange() to get tighter bounds 10551 // on the bit ranges. 10552 QualType OtherT = Other->getType(); 10553 if (const auto *AT = OtherT->getAs<AtomicType>()) 10554 OtherT = AT->getValueType(); 10555 IntRange OtherRange = IntRange::forValueOfType(S.Context, OtherT); 10556 10557 // Special case for ObjC BOOL on targets where its a typedef for a signed char 10558 // (Namely, macOS). 10559 bool IsObjCSignedCharBool = S.getLangOpts().ObjC && 10560 S.NSAPIObj->isObjCBOOLType(OtherT) && 10561 OtherT->isSpecificBuiltinType(BuiltinType::SChar); 10562 10563 // Whether we're treating Other as being a bool because of the form of 10564 // expression despite it having another type (typically 'int' in C). 10565 bool OtherIsBooleanDespiteType = 10566 !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue(); 10567 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool) 10568 OtherRange = IntRange::forBoolType(); 10569 10570 // Determine the promoted range of the other type and see if a comparison of 10571 // the constant against that range is tautological. 10572 PromotedRange OtherPromotedRange(OtherRange, Value.getBitWidth(), 10573 Value.isUnsigned()); 10574 auto Cmp = OtherPromotedRange.compare(Value); 10575 auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant); 10576 if (!Result) 10577 return false; 10578 10579 // Suppress the diagnostic for an in-range comparison if the constant comes 10580 // from a macro or enumerator. We don't want to diagnose 10581 // 10582 // some_long_value <= INT_MAX 10583 // 10584 // when sizeof(int) == sizeof(long). 10585 bool InRange = Cmp & PromotedRange::InRangeFlag; 10586 if (InRange && IsEnumConstOrFromMacro(S, Constant)) 10587 return false; 10588 10589 // If this is a comparison to an enum constant, include that 10590 // constant in the diagnostic. 10591 const EnumConstantDecl *ED = nullptr; 10592 if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant)) 10593 ED = dyn_cast<EnumConstantDecl>(DR->getDecl()); 10594 10595 // Should be enough for uint128 (39 decimal digits) 10596 SmallString<64> PrettySourceValue; 10597 llvm::raw_svector_ostream OS(PrettySourceValue); 10598 if (ED) { 10599 OS << '\'' << *ED << "' (" << Value << ")"; 10600 } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>( 10601 Constant->IgnoreParenImpCasts())) { 10602 OS << (BL->getValue() ? "YES" : "NO"); 10603 } else { 10604 OS << Value; 10605 } 10606 10607 if (IsObjCSignedCharBool) { 10608 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10609 S.PDiag(diag::warn_tautological_compare_objc_bool) 10610 << OS.str() << *Result); 10611 return true; 10612 } 10613 10614 // FIXME: We use a somewhat different formatting for the in-range cases and 10615 // cases involving boolean values for historical reasons. We should pick a 10616 // consistent way of presenting these diagnostics. 10617 if (!InRange || Other->isKnownToHaveBooleanValue()) { 10618 10619 S.DiagRuntimeBehavior( 10620 E->getOperatorLoc(), E, 10621 S.PDiag(!InRange ? diag::warn_out_of_range_compare 10622 : diag::warn_tautological_bool_compare) 10623 << OS.str() << classifyConstantValue(Constant) << OtherT 10624 << OtherIsBooleanDespiteType << *Result 10625 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange()); 10626 } else { 10627 unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0) 10628 ? (HasEnumType(OriginalOther) 10629 ? diag::warn_unsigned_enum_always_true_comparison 10630 : diag::warn_unsigned_always_true_comparison) 10631 : diag::warn_tautological_constant_compare; 10632 10633 S.Diag(E->getOperatorLoc(), Diag) 10634 << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result 10635 << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange(); 10636 } 10637 10638 return true; 10639 } 10640 10641 /// Analyze the operands of the given comparison. Implements the 10642 /// fallback case from AnalyzeComparison. 10643 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) { 10644 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10645 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10646 } 10647 10648 /// Implements -Wsign-compare. 10649 /// 10650 /// \param E the binary operator to check for warnings 10651 static void AnalyzeComparison(Sema &S, BinaryOperator *E) { 10652 // The type the comparison is being performed in. 10653 QualType T = E->getLHS()->getType(); 10654 10655 // Only analyze comparison operators where both sides have been converted to 10656 // the same type. 10657 if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType())) 10658 return AnalyzeImpConvsInComparison(S, E); 10659 10660 // Don't analyze value-dependent comparisons directly. 10661 if (E->isValueDependent()) 10662 return AnalyzeImpConvsInComparison(S, E); 10663 10664 Expr *LHS = E->getLHS(); 10665 Expr *RHS = E->getRHS(); 10666 10667 if (T->isIntegralType(S.Context)) { 10668 llvm::APSInt RHSValue; 10669 llvm::APSInt LHSValue; 10670 10671 bool IsRHSIntegralLiteral = RHS->isIntegerConstantExpr(RHSValue, S.Context); 10672 bool IsLHSIntegralLiteral = LHS->isIntegerConstantExpr(LHSValue, S.Context); 10673 10674 // We don't care about expressions whose result is a constant. 10675 if (IsRHSIntegralLiteral && IsLHSIntegralLiteral) 10676 return AnalyzeImpConvsInComparison(S, E); 10677 10678 // We only care about expressions where just one side is literal 10679 if (IsRHSIntegralLiteral ^ IsLHSIntegralLiteral) { 10680 // Is the constant on the RHS or LHS? 10681 const bool RhsConstant = IsRHSIntegralLiteral; 10682 Expr *Const = RhsConstant ? RHS : LHS; 10683 Expr *Other = RhsConstant ? LHS : RHS; 10684 const llvm::APSInt &Value = RhsConstant ? RHSValue : LHSValue; 10685 10686 // Check whether an integer constant comparison results in a value 10687 // of 'true' or 'false'. 10688 if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant)) 10689 return AnalyzeImpConvsInComparison(S, E); 10690 } 10691 } 10692 10693 if (!T->hasUnsignedIntegerRepresentation()) { 10694 // We don't do anything special if this isn't an unsigned integral 10695 // comparison: we're only interested in integral comparisons, and 10696 // signed comparisons only happen in cases we don't care to warn about. 10697 return AnalyzeImpConvsInComparison(S, E); 10698 } 10699 10700 LHS = LHS->IgnoreParenImpCasts(); 10701 RHS = RHS->IgnoreParenImpCasts(); 10702 10703 if (!S.getLangOpts().CPlusPlus) { 10704 // Avoid warning about comparison of integers with different signs when 10705 // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of 10706 // the type of `E`. 10707 if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType())) 10708 LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10709 if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType())) 10710 RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts(); 10711 } 10712 10713 // Check to see if one of the (unmodified) operands is of different 10714 // signedness. 10715 Expr *signedOperand, *unsignedOperand; 10716 if (LHS->getType()->hasSignedIntegerRepresentation()) { 10717 assert(!RHS->getType()->hasSignedIntegerRepresentation() && 10718 "unsigned comparison between two signed integer expressions?"); 10719 signedOperand = LHS; 10720 unsignedOperand = RHS; 10721 } else if (RHS->getType()->hasSignedIntegerRepresentation()) { 10722 signedOperand = RHS; 10723 unsignedOperand = LHS; 10724 } else { 10725 return AnalyzeImpConvsInComparison(S, E); 10726 } 10727 10728 // Otherwise, calculate the effective range of the signed operand. 10729 IntRange signedRange = 10730 GetExprRange(S.Context, signedOperand, S.isConstantEvaluated()); 10731 10732 // Go ahead and analyze implicit conversions in the operands. Note 10733 // that we skip the implicit conversions on both sides. 10734 AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc()); 10735 AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc()); 10736 10737 // If the signed range is non-negative, -Wsign-compare won't fire. 10738 if (signedRange.NonNegative) 10739 return; 10740 10741 // For (in)equality comparisons, if the unsigned operand is a 10742 // constant which cannot collide with a overflowed signed operand, 10743 // then reinterpreting the signed operand as unsigned will not 10744 // change the result of the comparison. 10745 if (E->isEqualityOp()) { 10746 unsigned comparisonWidth = S.Context.getIntWidth(T); 10747 IntRange unsignedRange = 10748 GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated()); 10749 10750 // We should never be unable to prove that the unsigned operand is 10751 // non-negative. 10752 assert(unsignedRange.NonNegative && "unsigned range includes negative?"); 10753 10754 if (unsignedRange.Width < comparisonWidth) 10755 return; 10756 } 10757 10758 S.DiagRuntimeBehavior(E->getOperatorLoc(), E, 10759 S.PDiag(diag::warn_mixed_sign_comparison) 10760 << LHS->getType() << RHS->getType() 10761 << LHS->getSourceRange() << RHS->getSourceRange()); 10762 } 10763 10764 /// Analyzes an attempt to assign the given value to a bitfield. 10765 /// 10766 /// Returns true if there was something fishy about the attempt. 10767 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, 10768 SourceLocation InitLoc) { 10769 assert(Bitfield->isBitField()); 10770 if (Bitfield->isInvalidDecl()) 10771 return false; 10772 10773 // White-list bool bitfields. 10774 QualType BitfieldType = Bitfield->getType(); 10775 if (BitfieldType->isBooleanType()) 10776 return false; 10777 10778 if (BitfieldType->isEnumeralType()) { 10779 EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl(); 10780 // If the underlying enum type was not explicitly specified as an unsigned 10781 // type and the enum contain only positive values, MSVC++ will cause an 10782 // inconsistency by storing this as a signed type. 10783 if (S.getLangOpts().CPlusPlus11 && 10784 !BitfieldEnumDecl->getIntegerTypeSourceInfo() && 10785 BitfieldEnumDecl->getNumPositiveBits() > 0 && 10786 BitfieldEnumDecl->getNumNegativeBits() == 0) { 10787 S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield) 10788 << BitfieldEnumDecl->getNameAsString(); 10789 } 10790 } 10791 10792 if (Bitfield->getType()->isBooleanType()) 10793 return false; 10794 10795 // Ignore value- or type-dependent expressions. 10796 if (Bitfield->getBitWidth()->isValueDependent() || 10797 Bitfield->getBitWidth()->isTypeDependent() || 10798 Init->isValueDependent() || 10799 Init->isTypeDependent()) 10800 return false; 10801 10802 Expr *OriginalInit = Init->IgnoreParenImpCasts(); 10803 unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context); 10804 10805 Expr::EvalResult Result; 10806 if (!OriginalInit->EvaluateAsInt(Result, S.Context, 10807 Expr::SE_AllowSideEffects)) { 10808 // The RHS is not constant. If the RHS has an enum type, make sure the 10809 // bitfield is wide enough to hold all the values of the enum without 10810 // truncation. 10811 if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) { 10812 EnumDecl *ED = EnumTy->getDecl(); 10813 bool SignedBitfield = BitfieldType->isSignedIntegerType(); 10814 10815 // Enum types are implicitly signed on Windows, so check if there are any 10816 // negative enumerators to see if the enum was intended to be signed or 10817 // not. 10818 bool SignedEnum = ED->getNumNegativeBits() > 0; 10819 10820 // Check for surprising sign changes when assigning enum values to a 10821 // bitfield of different signedness. If the bitfield is signed and we 10822 // have exactly the right number of bits to store this unsigned enum, 10823 // suggest changing the enum to an unsigned type. This typically happens 10824 // on Windows where unfixed enums always use an underlying type of 'int'. 10825 unsigned DiagID = 0; 10826 if (SignedEnum && !SignedBitfield) { 10827 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum; 10828 } else if (SignedBitfield && !SignedEnum && 10829 ED->getNumPositiveBits() == FieldWidth) { 10830 DiagID = diag::warn_signed_bitfield_enum_conversion; 10831 } 10832 10833 if (DiagID) { 10834 S.Diag(InitLoc, DiagID) << Bitfield << ED; 10835 TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo(); 10836 SourceRange TypeRange = 10837 TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange(); 10838 S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign) 10839 << SignedEnum << TypeRange; 10840 } 10841 10842 // Compute the required bitwidth. If the enum has negative values, we need 10843 // one more bit than the normal number of positive bits to represent the 10844 // sign bit. 10845 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1, 10846 ED->getNumNegativeBits()) 10847 : ED->getNumPositiveBits(); 10848 10849 // Check the bitwidth. 10850 if (BitsNeeded > FieldWidth) { 10851 Expr *WidthExpr = Bitfield->getBitWidth(); 10852 S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum) 10853 << Bitfield << ED; 10854 S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield) 10855 << BitsNeeded << ED << WidthExpr->getSourceRange(); 10856 } 10857 } 10858 10859 return false; 10860 } 10861 10862 llvm::APSInt Value = Result.Val.getInt(); 10863 10864 unsigned OriginalWidth = Value.getBitWidth(); 10865 10866 if (!Value.isSigned() || Value.isNegative()) 10867 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit)) 10868 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not) 10869 OriginalWidth = Value.getMinSignedBits(); 10870 10871 if (OriginalWidth <= FieldWidth) 10872 return false; 10873 10874 // Compute the value which the bitfield will contain. 10875 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth); 10876 TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType()); 10877 10878 // Check whether the stored value is equal to the original value. 10879 TruncatedValue = TruncatedValue.extend(OriginalWidth); 10880 if (llvm::APSInt::isSameValue(Value, TruncatedValue)) 10881 return false; 10882 10883 // Special-case bitfields of width 1: booleans are naturally 0/1, and 10884 // therefore don't strictly fit into a signed bitfield of width 1. 10885 if (FieldWidth == 1 && Value == 1) 10886 return false; 10887 10888 std::string PrettyValue = Value.toString(10); 10889 std::string PrettyTrunc = TruncatedValue.toString(10); 10890 10891 S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant) 10892 << PrettyValue << PrettyTrunc << OriginalInit->getType() 10893 << Init->getSourceRange(); 10894 10895 return true; 10896 } 10897 10898 /// Analyze the given simple or compound assignment for warning-worthy 10899 /// operations. 10900 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) { 10901 // Just recurse on the LHS. 10902 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 10903 10904 // We want to recurse on the RHS as normal unless we're assigning to 10905 // a bitfield. 10906 if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) { 10907 if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(), 10908 E->getOperatorLoc())) { 10909 // Recurse, ignoring any implicit conversions on the RHS. 10910 return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(), 10911 E->getOperatorLoc()); 10912 } 10913 } 10914 10915 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 10916 10917 // Diagnose implicitly sequentially-consistent atomic assignment. 10918 if (E->getLHS()->getType()->isAtomicType()) 10919 S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 10920 } 10921 10922 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10923 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T, 10924 SourceLocation CContext, unsigned diag, 10925 bool pruneControlFlow = false) { 10926 if (pruneControlFlow) { 10927 S.DiagRuntimeBehavior(E->getExprLoc(), E, 10928 S.PDiag(diag) 10929 << SourceType << T << E->getSourceRange() 10930 << SourceRange(CContext)); 10931 return; 10932 } 10933 S.Diag(E->getExprLoc(), diag) 10934 << SourceType << T << E->getSourceRange() << SourceRange(CContext); 10935 } 10936 10937 /// Diagnose an implicit cast; purely a helper for CheckImplicitConversion. 10938 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T, 10939 SourceLocation CContext, 10940 unsigned diag, bool pruneControlFlow = false) { 10941 DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow); 10942 } 10943 10944 static bool isObjCSignedCharBool(Sema &S, QualType Ty) { 10945 return Ty->isSpecificBuiltinType(BuiltinType::SChar) && 10946 S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty); 10947 } 10948 10949 static void adornObjCBoolConversionDiagWithTernaryFixit( 10950 Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) { 10951 Expr *Ignored = SourceExpr->IgnoreImplicit(); 10952 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored)) 10953 Ignored = OVE->getSourceExpr(); 10954 bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) || 10955 isa<BinaryOperator>(Ignored) || 10956 isa<CXXOperatorCallExpr>(Ignored); 10957 SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc()); 10958 if (NeedsParens) 10959 Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(") 10960 << FixItHint::CreateInsertion(EndLoc, ")"); 10961 Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO"); 10962 } 10963 10964 /// Diagnose an implicit cast from a floating point value to an integer value. 10965 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T, 10966 SourceLocation CContext) { 10967 const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool); 10968 const bool PruneWarnings = S.inTemplateInstantiation(); 10969 10970 Expr *InnerE = E->IgnoreParenImpCasts(); 10971 // We also want to warn on, e.g., "int i = -1.234" 10972 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE)) 10973 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus) 10974 InnerE = UOp->getSubExpr()->IgnoreParenImpCasts(); 10975 10976 const bool IsLiteral = 10977 isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE); 10978 10979 llvm::APFloat Value(0.0); 10980 bool IsConstant = 10981 E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects); 10982 if (!IsConstant) { 10983 if (isObjCSignedCharBool(S, T)) { 10984 return adornObjCBoolConversionDiagWithTernaryFixit( 10985 S, E, 10986 S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool) 10987 << E->getType()); 10988 } 10989 10990 return DiagnoseImpCast(S, E, T, CContext, 10991 diag::warn_impcast_float_integer, PruneWarnings); 10992 } 10993 10994 bool isExact = false; 10995 10996 llvm::APSInt IntegerValue(S.Context.getIntWidth(T), 10997 T->hasUnsignedIntegerRepresentation()); 10998 llvm::APFloat::opStatus Result = Value.convertToInteger( 10999 IntegerValue, llvm::APFloat::rmTowardZero, &isExact); 11000 11001 // FIXME: Force the precision of the source value down so we don't print 11002 // digits which are usually useless (we don't really care here if we 11003 // truncate a digit by accident in edge cases). Ideally, APFloat::toString 11004 // would automatically print the shortest representation, but it's a bit 11005 // tricky to implement. 11006 SmallString<16> PrettySourceValue; 11007 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics()); 11008 precision = (precision * 59 + 195) / 196; 11009 Value.toString(PrettySourceValue, precision); 11010 11011 if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) { 11012 return adornObjCBoolConversionDiagWithTernaryFixit( 11013 S, E, 11014 S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool) 11015 << PrettySourceValue); 11016 } 11017 11018 if (Result == llvm::APFloat::opOK && isExact) { 11019 if (IsLiteral) return; 11020 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer, 11021 PruneWarnings); 11022 } 11023 11024 // Conversion of a floating-point value to a non-bool integer where the 11025 // integral part cannot be represented by the integer type is undefined. 11026 if (!IsBool && Result == llvm::APFloat::opInvalidOp) 11027 return DiagnoseImpCast( 11028 S, E, T, CContext, 11029 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range 11030 : diag::warn_impcast_float_to_integer_out_of_range, 11031 PruneWarnings); 11032 11033 unsigned DiagID = 0; 11034 if (IsLiteral) { 11035 // Warn on floating point literal to integer. 11036 DiagID = diag::warn_impcast_literal_float_to_integer; 11037 } else if (IntegerValue == 0) { 11038 if (Value.isZero()) { // Skip -0.0 to 0 conversion. 11039 return DiagnoseImpCast(S, E, T, CContext, 11040 diag::warn_impcast_float_integer, PruneWarnings); 11041 } 11042 // Warn on non-zero to zero conversion. 11043 DiagID = diag::warn_impcast_float_to_integer_zero; 11044 } else { 11045 if (IntegerValue.isUnsigned()) { 11046 if (!IntegerValue.isMaxValue()) { 11047 return DiagnoseImpCast(S, E, T, CContext, 11048 diag::warn_impcast_float_integer, PruneWarnings); 11049 } 11050 } else { // IntegerValue.isSigned() 11051 if (!IntegerValue.isMaxSignedValue() && 11052 !IntegerValue.isMinSignedValue()) { 11053 return DiagnoseImpCast(S, E, T, CContext, 11054 diag::warn_impcast_float_integer, PruneWarnings); 11055 } 11056 } 11057 // Warn on evaluatable floating point expression to integer conversion. 11058 DiagID = diag::warn_impcast_float_to_integer; 11059 } 11060 11061 SmallString<16> PrettyTargetValue; 11062 if (IsBool) 11063 PrettyTargetValue = Value.isZero() ? "false" : "true"; 11064 else 11065 IntegerValue.toString(PrettyTargetValue); 11066 11067 if (PruneWarnings) { 11068 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11069 S.PDiag(DiagID) 11070 << E->getType() << T.getUnqualifiedType() 11071 << PrettySourceValue << PrettyTargetValue 11072 << E->getSourceRange() << SourceRange(CContext)); 11073 } else { 11074 S.Diag(E->getExprLoc(), DiagID) 11075 << E->getType() << T.getUnqualifiedType() << PrettySourceValue 11076 << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext); 11077 } 11078 } 11079 11080 /// Analyze the given compound assignment for the possible losing of 11081 /// floating-point precision. 11082 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) { 11083 assert(isa<CompoundAssignOperator>(E) && 11084 "Must be compound assignment operation"); 11085 // Recurse on the LHS and RHS in here 11086 AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc()); 11087 AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc()); 11088 11089 if (E->getLHS()->getType()->isAtomicType()) 11090 S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst); 11091 11092 // Now check the outermost expression 11093 const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>(); 11094 const auto *RBT = cast<CompoundAssignOperator>(E) 11095 ->getComputationResultType() 11096 ->getAs<BuiltinType>(); 11097 11098 // The below checks assume source is floating point. 11099 if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return; 11100 11101 // If source is floating point but target is an integer. 11102 if (ResultBT->isInteger()) 11103 return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(), 11104 E->getExprLoc(), diag::warn_impcast_float_integer); 11105 11106 if (!ResultBT->isFloatingPoint()) 11107 return; 11108 11109 // If both source and target are floating points, warn about losing precision. 11110 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11111 QualType(ResultBT, 0), QualType(RBT, 0)); 11112 if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc())) 11113 // warn about dropping FP rank. 11114 DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(), 11115 diag::warn_impcast_float_result_precision); 11116 } 11117 11118 static std::string PrettyPrintInRange(const llvm::APSInt &Value, 11119 IntRange Range) { 11120 if (!Range.Width) return "0"; 11121 11122 llvm::APSInt ValueInRange = Value; 11123 ValueInRange.setIsSigned(!Range.NonNegative); 11124 ValueInRange = ValueInRange.trunc(Range.Width); 11125 return ValueInRange.toString(10); 11126 } 11127 11128 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) { 11129 if (!isa<ImplicitCastExpr>(Ex)) 11130 return false; 11131 11132 Expr *InnerE = Ex->IgnoreParenImpCasts(); 11133 const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr(); 11134 const Type *Source = 11135 S.Context.getCanonicalType(InnerE->getType()).getTypePtr(); 11136 if (Target->isDependentType()) 11137 return false; 11138 11139 const BuiltinType *FloatCandidateBT = 11140 dyn_cast<BuiltinType>(ToBool ? Source : Target); 11141 const Type *BoolCandidateType = ToBool ? Target : Source; 11142 11143 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) && 11144 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint())); 11145 } 11146 11147 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall, 11148 SourceLocation CC) { 11149 unsigned NumArgs = TheCall->getNumArgs(); 11150 for (unsigned i = 0; i < NumArgs; ++i) { 11151 Expr *CurrA = TheCall->getArg(i); 11152 if (!IsImplicitBoolFloatConversion(S, CurrA, true)) 11153 continue; 11154 11155 bool IsSwapped = ((i > 0) && 11156 IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false)); 11157 IsSwapped |= ((i < (NumArgs - 1)) && 11158 IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false)); 11159 if (IsSwapped) { 11160 // Warn on this floating-point to bool conversion. 11161 DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(), 11162 CurrA->getType(), CC, 11163 diag::warn_impcast_floating_point_to_bool); 11164 } 11165 } 11166 } 11167 11168 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, 11169 SourceLocation CC) { 11170 if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer, 11171 E->getExprLoc())) 11172 return; 11173 11174 // Don't warn on functions which have return type nullptr_t. 11175 if (isa<CallExpr>(E)) 11176 return; 11177 11178 // Check for NULL (GNUNull) or nullptr (CXX11_nullptr). 11179 const Expr::NullPointerConstantKind NullKind = 11180 E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull); 11181 if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr) 11182 return; 11183 11184 // Return if target type is a safe conversion. 11185 if (T->isAnyPointerType() || T->isBlockPointerType() || 11186 T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType()) 11187 return; 11188 11189 SourceLocation Loc = E->getSourceRange().getBegin(); 11190 11191 // Venture through the macro stacks to get to the source of macro arguments. 11192 // The new location is a better location than the complete location that was 11193 // passed in. 11194 Loc = S.SourceMgr.getTopMacroCallerLoc(Loc); 11195 CC = S.SourceMgr.getTopMacroCallerLoc(CC); 11196 11197 // __null is usually wrapped in a macro. Go up a macro if that is the case. 11198 if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) { 11199 StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics( 11200 Loc, S.SourceMgr, S.getLangOpts()); 11201 if (MacroName == "NULL") 11202 Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin(); 11203 } 11204 11205 // Only warn if the null and context location are in the same macro expansion. 11206 if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC)) 11207 return; 11208 11209 S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer) 11210 << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC) 11211 << FixItHint::CreateReplacement(Loc, 11212 S.getFixItZeroLiteralForType(T, Loc)); 11213 } 11214 11215 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11216 ObjCArrayLiteral *ArrayLiteral); 11217 11218 static void 11219 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11220 ObjCDictionaryLiteral *DictionaryLiteral); 11221 11222 /// Check a single element within a collection literal against the 11223 /// target element type. 11224 static void checkObjCCollectionLiteralElement(Sema &S, 11225 QualType TargetElementType, 11226 Expr *Element, 11227 unsigned ElementKind) { 11228 // Skip a bitcast to 'id' or qualified 'id'. 11229 if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) { 11230 if (ICE->getCastKind() == CK_BitCast && 11231 ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>()) 11232 Element = ICE->getSubExpr(); 11233 } 11234 11235 QualType ElementType = Element->getType(); 11236 ExprResult ElementResult(Element); 11237 if (ElementType->getAs<ObjCObjectPointerType>() && 11238 S.CheckSingleAssignmentConstraints(TargetElementType, 11239 ElementResult, 11240 false, false) 11241 != Sema::Compatible) { 11242 S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element) 11243 << ElementType << ElementKind << TargetElementType 11244 << Element->getSourceRange(); 11245 } 11246 11247 if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element)) 11248 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral); 11249 else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element)) 11250 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral); 11251 } 11252 11253 /// Check an Objective-C array literal being converted to the given 11254 /// target type. 11255 static void checkObjCArrayLiteral(Sema &S, QualType TargetType, 11256 ObjCArrayLiteral *ArrayLiteral) { 11257 if (!S.NSArrayDecl) 11258 return; 11259 11260 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11261 if (!TargetObjCPtr) 11262 return; 11263 11264 if (TargetObjCPtr->isUnspecialized() || 11265 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11266 != S.NSArrayDecl->getCanonicalDecl()) 11267 return; 11268 11269 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11270 if (TypeArgs.size() != 1) 11271 return; 11272 11273 QualType TargetElementType = TypeArgs[0]; 11274 for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) { 11275 checkObjCCollectionLiteralElement(S, TargetElementType, 11276 ArrayLiteral->getElement(I), 11277 0); 11278 } 11279 } 11280 11281 /// Check an Objective-C dictionary literal being converted to the given 11282 /// target type. 11283 static void 11284 checkObjCDictionaryLiteral(Sema &S, QualType TargetType, 11285 ObjCDictionaryLiteral *DictionaryLiteral) { 11286 if (!S.NSDictionaryDecl) 11287 return; 11288 11289 const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>(); 11290 if (!TargetObjCPtr) 11291 return; 11292 11293 if (TargetObjCPtr->isUnspecialized() || 11294 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl() 11295 != S.NSDictionaryDecl->getCanonicalDecl()) 11296 return; 11297 11298 auto TypeArgs = TargetObjCPtr->getTypeArgs(); 11299 if (TypeArgs.size() != 2) 11300 return; 11301 11302 QualType TargetKeyType = TypeArgs[0]; 11303 QualType TargetObjectType = TypeArgs[1]; 11304 for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) { 11305 auto Element = DictionaryLiteral->getKeyValueElement(I); 11306 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1); 11307 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2); 11308 } 11309 } 11310 11311 // Helper function to filter out cases for constant width constant conversion. 11312 // Don't warn on char array initialization or for non-decimal values. 11313 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, 11314 SourceLocation CC) { 11315 // If initializing from a constant, and the constant starts with '0', 11316 // then it is a binary, octal, or hexadecimal. Allow these constants 11317 // to fill all the bits, even if there is a sign change. 11318 if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) { 11319 const char FirstLiteralCharacter = 11320 S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0]; 11321 if (FirstLiteralCharacter == '0') 11322 return false; 11323 } 11324 11325 // If the CC location points to a '{', and the type is char, then assume 11326 // assume it is an array initialization. 11327 if (CC.isValid() && T->isCharType()) { 11328 const char FirstContextCharacter = 11329 S.getSourceManager().getCharacterData(CC)[0]; 11330 if (FirstContextCharacter == '{') 11331 return false; 11332 } 11333 11334 return true; 11335 } 11336 11337 static const IntegerLiteral *getIntegerLiteral(Expr *E) { 11338 const auto *IL = dyn_cast<IntegerLiteral>(E); 11339 if (!IL) { 11340 if (auto *UO = dyn_cast<UnaryOperator>(E)) { 11341 if (UO->getOpcode() == UO_Minus) 11342 return dyn_cast<IntegerLiteral>(UO->getSubExpr()); 11343 } 11344 } 11345 11346 return IL; 11347 } 11348 11349 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) { 11350 E = E->IgnoreParenImpCasts(); 11351 SourceLocation ExprLoc = E->getExprLoc(); 11352 11353 if (const auto *BO = dyn_cast<BinaryOperator>(E)) { 11354 BinaryOperator::Opcode Opc = BO->getOpcode(); 11355 Expr::EvalResult Result; 11356 // Do not diagnose unsigned shifts. 11357 if (Opc == BO_Shl) { 11358 const auto *LHS = getIntegerLiteral(BO->getLHS()); 11359 const auto *RHS = getIntegerLiteral(BO->getRHS()); 11360 if (LHS && LHS->getValue() == 0) 11361 S.Diag(ExprLoc, diag::warn_left_shift_always) << 0; 11362 else if (!E->isValueDependent() && LHS && RHS && 11363 RHS->getValue().isNonNegative() && 11364 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) 11365 S.Diag(ExprLoc, diag::warn_left_shift_always) 11366 << (Result.Val.getInt() != 0); 11367 else if (E->getType()->isSignedIntegerType()) 11368 S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E; 11369 } 11370 } 11371 11372 if (const auto *CO = dyn_cast<ConditionalOperator>(E)) { 11373 const auto *LHS = getIntegerLiteral(CO->getTrueExpr()); 11374 const auto *RHS = getIntegerLiteral(CO->getFalseExpr()); 11375 if (!LHS || !RHS) 11376 return; 11377 if ((LHS->getValue() == 0 || LHS->getValue() == 1) && 11378 (RHS->getValue() == 0 || RHS->getValue() == 1)) 11379 // Do not diagnose common idioms. 11380 return; 11381 if (LHS->getValue() != 0 && RHS->getValue() != 0) 11382 S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true); 11383 } 11384 } 11385 11386 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T, 11387 SourceLocation CC, 11388 bool *ICContext = nullptr, 11389 bool IsListInit = false) { 11390 if (E->isTypeDependent() || E->isValueDependent()) return; 11391 11392 const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr(); 11393 const Type *Target = S.Context.getCanonicalType(T).getTypePtr(); 11394 if (Source == Target) return; 11395 if (Target->isDependentType()) return; 11396 11397 // If the conversion context location is invalid don't complain. We also 11398 // don't want to emit a warning if the issue occurs from the expansion of 11399 // a system macro. The problem is that 'getSpellingLoc()' is slow, so we 11400 // delay this check as long as possible. Once we detect we are in that 11401 // scenario, we just return. 11402 if (CC.isInvalid()) 11403 return; 11404 11405 if (Source->isAtomicType()) 11406 S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst); 11407 11408 // Diagnose implicit casts to bool. 11409 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) { 11410 if (isa<StringLiteral>(E)) 11411 // Warn on string literal to bool. Checks for string literals in logical 11412 // and expressions, for instance, assert(0 && "error here"), are 11413 // prevented by a check in AnalyzeImplicitConversions(). 11414 return DiagnoseImpCast(S, E, T, CC, 11415 diag::warn_impcast_string_literal_to_bool); 11416 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) || 11417 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) { 11418 // This covers the literal expressions that evaluate to Objective-C 11419 // objects. 11420 return DiagnoseImpCast(S, E, T, CC, 11421 diag::warn_impcast_objective_c_literal_to_bool); 11422 } 11423 if (Source->isPointerType() || Source->canDecayToPointerType()) { 11424 // Warn on pointer to bool conversion that is always true. 11425 S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false, 11426 SourceRange(CC)); 11427 } 11428 } 11429 11430 // If the we're converting a constant to an ObjC BOOL on a platform where BOOL 11431 // is a typedef for signed char (macOS), then that constant value has to be 1 11432 // or 0. 11433 if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) { 11434 Expr::EvalResult Result; 11435 if (E->EvaluateAsInt(Result, S.getASTContext(), 11436 Expr::SE_AllowSideEffects)) { 11437 if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) { 11438 adornObjCBoolConversionDiagWithTernaryFixit( 11439 S, E, 11440 S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool) 11441 << Result.Val.getInt().toString(10)); 11442 } 11443 return; 11444 } 11445 } 11446 11447 // Check implicit casts from Objective-C collection literals to specialized 11448 // collection types, e.g., NSArray<NSString *> *. 11449 if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E)) 11450 checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral); 11451 else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E)) 11452 checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral); 11453 11454 // Strip vector types. 11455 if (isa<VectorType>(Source)) { 11456 if (!isa<VectorType>(Target)) { 11457 if (S.SourceMgr.isInSystemMacro(CC)) 11458 return; 11459 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar); 11460 } 11461 11462 // If the vector cast is cast between two vectors of the same size, it is 11463 // a bitcast, not a conversion. 11464 if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target)) 11465 return; 11466 11467 Source = cast<VectorType>(Source)->getElementType().getTypePtr(); 11468 Target = cast<VectorType>(Target)->getElementType().getTypePtr(); 11469 } 11470 if (auto VecTy = dyn_cast<VectorType>(Target)) 11471 Target = VecTy->getElementType().getTypePtr(); 11472 11473 // Strip complex types. 11474 if (isa<ComplexType>(Source)) { 11475 if (!isa<ComplexType>(Target)) { 11476 if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType()) 11477 return; 11478 11479 return DiagnoseImpCast(S, E, T, CC, 11480 S.getLangOpts().CPlusPlus 11481 ? diag::err_impcast_complex_scalar 11482 : diag::warn_impcast_complex_scalar); 11483 } 11484 11485 Source = cast<ComplexType>(Source)->getElementType().getTypePtr(); 11486 Target = cast<ComplexType>(Target)->getElementType().getTypePtr(); 11487 } 11488 11489 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source); 11490 const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target); 11491 11492 // If the source is floating point... 11493 if (SourceBT && SourceBT->isFloatingPoint()) { 11494 // ...and the target is floating point... 11495 if (TargetBT && TargetBT->isFloatingPoint()) { 11496 // ...then warn if we're dropping FP rank. 11497 11498 int Order = S.getASTContext().getFloatingTypeSemanticOrder( 11499 QualType(SourceBT, 0), QualType(TargetBT, 0)); 11500 if (Order > 0) { 11501 // Don't warn about float constants that are precisely 11502 // representable in the target type. 11503 Expr::EvalResult result; 11504 if (E->EvaluateAsRValue(result, S.Context)) { 11505 // Value might be a float, a float vector, or a float complex. 11506 if (IsSameFloatAfterCast(result.Val, 11507 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)), 11508 S.Context.getFloatTypeSemantics(QualType(SourceBT, 0)))) 11509 return; 11510 } 11511 11512 if (S.SourceMgr.isInSystemMacro(CC)) 11513 return; 11514 11515 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision); 11516 } 11517 // ... or possibly if we're increasing rank, too 11518 else if (Order < 0) { 11519 if (S.SourceMgr.isInSystemMacro(CC)) 11520 return; 11521 11522 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion); 11523 } 11524 return; 11525 } 11526 11527 // If the target is integral, always warn. 11528 if (TargetBT && TargetBT->isInteger()) { 11529 if (S.SourceMgr.isInSystemMacro(CC)) 11530 return; 11531 11532 DiagnoseFloatingImpCast(S, E, T, CC); 11533 } 11534 11535 // Detect the case where a call result is converted from floating-point to 11536 // to bool, and the final argument to the call is converted from bool, to 11537 // discover this typo: 11538 // 11539 // bool b = fabs(x < 1.0); // should be "bool b = fabs(x) < 1.0;" 11540 // 11541 // FIXME: This is an incredibly special case; is there some more general 11542 // way to detect this class of misplaced-parentheses bug? 11543 if (Target->isBooleanType() && isa<CallExpr>(E)) { 11544 // Check last argument of function call to see if it is an 11545 // implicit cast from a type matching the type the result 11546 // is being cast to. 11547 CallExpr *CEx = cast<CallExpr>(E); 11548 if (unsigned NumArgs = CEx->getNumArgs()) { 11549 Expr *LastA = CEx->getArg(NumArgs - 1); 11550 Expr *InnerE = LastA->IgnoreParenImpCasts(); 11551 if (isa<ImplicitCastExpr>(LastA) && 11552 InnerE->getType()->isBooleanType()) { 11553 // Warn on this floating-point to bool conversion 11554 DiagnoseImpCast(S, E, T, CC, 11555 diag::warn_impcast_floating_point_to_bool); 11556 } 11557 } 11558 } 11559 return; 11560 } 11561 11562 // Valid casts involving fixed point types should be accounted for here. 11563 if (Source->isFixedPointType()) { 11564 if (Target->isUnsaturatedFixedPointType()) { 11565 Expr::EvalResult Result; 11566 if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects, 11567 S.isConstantEvaluated())) { 11568 APFixedPoint Value = Result.Val.getFixedPoint(); 11569 APFixedPoint MaxVal = S.Context.getFixedPointMax(T); 11570 APFixedPoint MinVal = S.Context.getFixedPointMin(T); 11571 if (Value > MaxVal || Value < MinVal) { 11572 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11573 S.PDiag(diag::warn_impcast_fixed_point_range) 11574 << Value.toString() << T 11575 << E->getSourceRange() 11576 << clang::SourceRange(CC)); 11577 return; 11578 } 11579 } 11580 } else if (Target->isIntegerType()) { 11581 Expr::EvalResult Result; 11582 if (!S.isConstantEvaluated() && 11583 E->EvaluateAsFixedPoint(Result, S.Context, 11584 Expr::SE_AllowSideEffects)) { 11585 APFixedPoint FXResult = Result.Val.getFixedPoint(); 11586 11587 bool Overflowed; 11588 llvm::APSInt IntResult = FXResult.convertToInt( 11589 S.Context.getIntWidth(T), 11590 Target->isSignedIntegerOrEnumerationType(), &Overflowed); 11591 11592 if (Overflowed) { 11593 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11594 S.PDiag(diag::warn_impcast_fixed_point_range) 11595 << FXResult.toString() << T 11596 << E->getSourceRange() 11597 << clang::SourceRange(CC)); 11598 return; 11599 } 11600 } 11601 } 11602 } else if (Target->isUnsaturatedFixedPointType()) { 11603 if (Source->isIntegerType()) { 11604 Expr::EvalResult Result; 11605 if (!S.isConstantEvaluated() && 11606 E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) { 11607 llvm::APSInt Value = Result.Val.getInt(); 11608 11609 bool Overflowed; 11610 APFixedPoint IntResult = APFixedPoint::getFromIntValue( 11611 Value, S.Context.getFixedPointSemantics(T), &Overflowed); 11612 11613 if (Overflowed) { 11614 S.DiagRuntimeBehavior(E->getExprLoc(), E, 11615 S.PDiag(diag::warn_impcast_fixed_point_range) 11616 << Value.toString(/*Radix=*/10) << T 11617 << E->getSourceRange() 11618 << clang::SourceRange(CC)); 11619 return; 11620 } 11621 } 11622 } 11623 } 11624 11625 // If we are casting an integer type to a floating point type without 11626 // initialization-list syntax, we might lose accuracy if the floating 11627 // point type has a narrower significand than the integer type. 11628 if (SourceBT && TargetBT && SourceBT->isIntegerType() && 11629 TargetBT->isFloatingType() && !IsListInit) { 11630 // Determine the number of precision bits in the source integer type. 11631 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11632 unsigned int SourcePrecision = SourceRange.Width; 11633 11634 // Determine the number of precision bits in the 11635 // target floating point type. 11636 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision( 11637 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11638 11639 if (SourcePrecision > 0 && TargetPrecision > 0 && 11640 SourcePrecision > TargetPrecision) { 11641 11642 llvm::APSInt SourceInt; 11643 if (E->isIntegerConstantExpr(SourceInt, S.Context)) { 11644 // If the source integer is a constant, convert it to the target 11645 // floating point type. Issue a warning if the value changes 11646 // during the whole conversion. 11647 llvm::APFloat TargetFloatValue( 11648 S.Context.getFloatTypeSemantics(QualType(TargetBT, 0))); 11649 llvm::APFloat::opStatus ConversionStatus = 11650 TargetFloatValue.convertFromAPInt( 11651 SourceInt, SourceBT->isSignedInteger(), 11652 llvm::APFloat::rmNearestTiesToEven); 11653 11654 if (ConversionStatus != llvm::APFloat::opOK) { 11655 std::string PrettySourceValue = SourceInt.toString(10); 11656 SmallString<32> PrettyTargetValue; 11657 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision); 11658 11659 S.DiagRuntimeBehavior( 11660 E->getExprLoc(), E, 11661 S.PDiag(diag::warn_impcast_integer_float_precision_constant) 11662 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11663 << E->getSourceRange() << clang::SourceRange(CC)); 11664 } 11665 } else { 11666 // Otherwise, the implicit conversion may lose precision. 11667 DiagnoseImpCast(S, E, T, CC, 11668 diag::warn_impcast_integer_float_precision); 11669 } 11670 } 11671 } 11672 11673 DiagnoseNullConversion(S, E, T, CC); 11674 11675 S.DiscardMisalignedMemberAddress(Target, E); 11676 11677 if (Target->isBooleanType()) 11678 DiagnoseIntInBoolContext(S, E); 11679 11680 if (!Source->isIntegerType() || !Target->isIntegerType()) 11681 return; 11682 11683 // TODO: remove this early return once the false positives for constant->bool 11684 // in templates, macros, etc, are reduced or removed. 11685 if (Target->isSpecificBuiltinType(BuiltinType::Bool)) 11686 return; 11687 11688 if (isObjCSignedCharBool(S, T) && !Source->isCharType() && 11689 !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) { 11690 return adornObjCBoolConversionDiagWithTernaryFixit( 11691 S, E, 11692 S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool) 11693 << E->getType()); 11694 } 11695 11696 IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated()); 11697 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target); 11698 11699 if (SourceRange.Width > TargetRange.Width) { 11700 // If the source is a constant, use a default-on diagnostic. 11701 // TODO: this should happen for bitfield stores, too. 11702 Expr::EvalResult Result; 11703 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects, 11704 S.isConstantEvaluated())) { 11705 llvm::APSInt Value(32); 11706 Value = Result.Val.getInt(); 11707 11708 if (S.SourceMgr.isInSystemMacro(CC)) 11709 return; 11710 11711 std::string PrettySourceValue = Value.toString(10); 11712 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11713 11714 S.DiagRuntimeBehavior( 11715 E->getExprLoc(), E, 11716 S.PDiag(diag::warn_impcast_integer_precision_constant) 11717 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11718 << E->getSourceRange() << clang::SourceRange(CC)); 11719 return; 11720 } 11721 11722 // People want to build with -Wshorten-64-to-32 and not -Wconversion. 11723 if (S.SourceMgr.isInSystemMacro(CC)) 11724 return; 11725 11726 if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64) 11727 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32, 11728 /* pruneControlFlow */ true); 11729 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision); 11730 } 11731 11732 if (TargetRange.Width > SourceRange.Width) { 11733 if (auto *UO = dyn_cast<UnaryOperator>(E)) 11734 if (UO->getOpcode() == UO_Minus) 11735 if (Source->isUnsignedIntegerType()) { 11736 if (Target->isUnsignedIntegerType()) 11737 return DiagnoseImpCast(S, E, T, CC, 11738 diag::warn_impcast_high_order_zero_bits); 11739 if (Target->isSignedIntegerType()) 11740 return DiagnoseImpCast(S, E, T, CC, 11741 diag::warn_impcast_nonnegative_result); 11742 } 11743 } 11744 11745 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative && 11746 SourceRange.NonNegative && Source->isSignedIntegerType()) { 11747 // Warn when doing a signed to signed conversion, warn if the positive 11748 // source value is exactly the width of the target type, which will 11749 // cause a negative value to be stored. 11750 11751 Expr::EvalResult Result; 11752 if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) && 11753 !S.SourceMgr.isInSystemMacro(CC)) { 11754 llvm::APSInt Value = Result.Val.getInt(); 11755 if (isSameWidthConstantConversion(S, E, T, CC)) { 11756 std::string PrettySourceValue = Value.toString(10); 11757 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange); 11758 11759 S.DiagRuntimeBehavior( 11760 E->getExprLoc(), E, 11761 S.PDiag(diag::warn_impcast_integer_precision_constant) 11762 << PrettySourceValue << PrettyTargetValue << E->getType() << T 11763 << E->getSourceRange() << clang::SourceRange(CC)); 11764 return; 11765 } 11766 } 11767 11768 // Fall through for non-constants to give a sign conversion warning. 11769 } 11770 11771 if ((TargetRange.NonNegative && !SourceRange.NonNegative) || 11772 (!TargetRange.NonNegative && SourceRange.NonNegative && 11773 SourceRange.Width == TargetRange.Width)) { 11774 if (S.SourceMgr.isInSystemMacro(CC)) 11775 return; 11776 11777 unsigned DiagID = diag::warn_impcast_integer_sign; 11778 11779 // Traditionally, gcc has warned about this under -Wsign-compare. 11780 // We also want to warn about it in -Wconversion. 11781 // So if -Wconversion is off, use a completely identical diagnostic 11782 // in the sign-compare group. 11783 // The conditional-checking code will 11784 if (ICContext) { 11785 DiagID = diag::warn_impcast_integer_sign_conditional; 11786 *ICContext = true; 11787 } 11788 11789 return DiagnoseImpCast(S, E, T, CC, DiagID); 11790 } 11791 11792 // Diagnose conversions between different enumeration types. 11793 // In C, we pretend that the type of an EnumConstantDecl is its enumeration 11794 // type, to give us better diagnostics. 11795 QualType SourceType = E->getType(); 11796 if (!S.getLangOpts().CPlusPlus) { 11797 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 11798 if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { 11799 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext()); 11800 SourceType = S.Context.getTypeDeclType(Enum); 11801 Source = S.Context.getCanonicalType(SourceType).getTypePtr(); 11802 } 11803 } 11804 11805 if (const EnumType *SourceEnum = Source->getAs<EnumType>()) 11806 if (const EnumType *TargetEnum = Target->getAs<EnumType>()) 11807 if (SourceEnum->getDecl()->hasNameForLinkage() && 11808 TargetEnum->getDecl()->hasNameForLinkage() && 11809 SourceEnum != TargetEnum) { 11810 if (S.SourceMgr.isInSystemMacro(CC)) 11811 return; 11812 11813 return DiagnoseImpCast(S, E, SourceType, T, CC, 11814 diag::warn_impcast_different_enum_types); 11815 } 11816 } 11817 11818 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11819 SourceLocation CC, QualType T); 11820 11821 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, 11822 SourceLocation CC, bool &ICContext) { 11823 E = E->IgnoreParenImpCasts(); 11824 11825 if (isa<ConditionalOperator>(E)) 11826 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T); 11827 11828 AnalyzeImplicitConversions(S, E, CC); 11829 if (E->getType() != T) 11830 return CheckImplicitConversion(S, E, T, CC, &ICContext); 11831 } 11832 11833 static void CheckConditionalOperator(Sema &S, ConditionalOperator *E, 11834 SourceLocation CC, QualType T) { 11835 AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc()); 11836 11837 bool Suspicious = false; 11838 CheckConditionalOperand(S, E->getTrueExpr(), T, CC, Suspicious); 11839 CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious); 11840 11841 if (T->isBooleanType()) 11842 DiagnoseIntInBoolContext(S, E); 11843 11844 // If -Wconversion would have warned about either of the candidates 11845 // for a signedness conversion to the context type... 11846 if (!Suspicious) return; 11847 11848 // ...but it's currently ignored... 11849 if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC)) 11850 return; 11851 11852 // ...then check whether it would have warned about either of the 11853 // candidates for a signedness conversion to the condition type. 11854 if (E->getType() == T) return; 11855 11856 Suspicious = false; 11857 CheckImplicitConversion(S, E->getTrueExpr()->IgnoreParenImpCasts(), 11858 E->getType(), CC, &Suspicious); 11859 if (!Suspicious) 11860 CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(), 11861 E->getType(), CC, &Suspicious); 11862 } 11863 11864 /// Check conversion of given expression to boolean. 11865 /// Input argument E is a logical expression. 11866 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) { 11867 if (S.getLangOpts().Bool) 11868 return; 11869 if (E->IgnoreParenImpCasts()->getType()->isAtomicType()) 11870 return; 11871 CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC); 11872 } 11873 11874 namespace { 11875 struct AnalyzeImplicitConversionsWorkItem { 11876 Expr *E; 11877 SourceLocation CC; 11878 bool IsListInit; 11879 }; 11880 } 11881 11882 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions 11883 /// that should be visited are added to WorkList. 11884 static void AnalyzeImplicitConversions( 11885 Sema &S, AnalyzeImplicitConversionsWorkItem Item, 11886 llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) { 11887 Expr *OrigE = Item.E; 11888 SourceLocation CC = Item.CC; 11889 11890 QualType T = OrigE->getType(); 11891 Expr *E = OrigE->IgnoreParenImpCasts(); 11892 11893 // Propagate whether we are in a C++ list initialization expression. 11894 // If so, we do not issue warnings for implicit int-float conversion 11895 // precision loss, because C++11 narrowing already handles it. 11896 bool IsListInit = Item.IsListInit || 11897 (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus); 11898 11899 if (E->isTypeDependent() || E->isValueDependent()) 11900 return; 11901 11902 Expr *SourceExpr = E; 11903 // Examine, but don't traverse into the source expression of an 11904 // OpaqueValueExpr, since it may have multiple parents and we don't want to 11905 // emit duplicate diagnostics. Its fine to examine the form or attempt to 11906 // evaluate it in the context of checking the specific conversion to T though. 11907 if (auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 11908 if (auto *Src = OVE->getSourceExpr()) 11909 SourceExpr = Src; 11910 11911 if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr)) 11912 if (UO->getOpcode() == UO_Not && 11913 UO->getSubExpr()->isKnownToHaveBooleanValue()) 11914 S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool) 11915 << OrigE->getSourceRange() << T->isBooleanType() 11916 << FixItHint::CreateReplacement(UO->getBeginLoc(), "!"); 11917 11918 // For conditional operators, we analyze the arguments as if they 11919 // were being fed directly into the output. 11920 if (auto *CO = dyn_cast<ConditionalOperator>(SourceExpr)) { 11921 CheckConditionalOperator(S, CO, CC, T); 11922 return; 11923 } 11924 11925 // Check implicit argument conversions for function calls. 11926 if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr)) 11927 CheckImplicitArgumentConversions(S, Call, CC); 11928 11929 // Go ahead and check any implicit conversions we might have skipped. 11930 // The non-canonical typecheck is just an optimization; 11931 // CheckImplicitConversion will filter out dead implicit conversions. 11932 if (SourceExpr->getType() != T) 11933 CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit); 11934 11935 // Now continue drilling into this expression. 11936 11937 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) { 11938 // The bound subexpressions in a PseudoObjectExpr are not reachable 11939 // as transitive children. 11940 // FIXME: Use a more uniform representation for this. 11941 for (auto *SE : POE->semantics()) 11942 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE)) 11943 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit}); 11944 } 11945 11946 // Skip past explicit casts. 11947 if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) { 11948 E = CE->getSubExpr()->IgnoreParenImpCasts(); 11949 if (!CE->getType()->isVoidType() && E->getType()->isAtomicType()) 11950 S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst); 11951 WorkList.push_back({E, CC, IsListInit}); 11952 return; 11953 } 11954 11955 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 11956 // Do a somewhat different check with comparison operators. 11957 if (BO->isComparisonOp()) 11958 return AnalyzeComparison(S, BO); 11959 11960 // And with simple assignments. 11961 if (BO->getOpcode() == BO_Assign) 11962 return AnalyzeAssignment(S, BO); 11963 // And with compound assignments. 11964 if (BO->isAssignmentOp()) 11965 return AnalyzeCompoundAssignment(S, BO); 11966 } 11967 11968 // These break the otherwise-useful invariant below. Fortunately, 11969 // we don't really need to recurse into them, because any internal 11970 // expressions should have been analyzed already when they were 11971 // built into statements. 11972 if (isa<StmtExpr>(E)) return; 11973 11974 // Don't descend into unevaluated contexts. 11975 if (isa<UnaryExprOrTypeTraitExpr>(E)) return; 11976 11977 // Now just recurse over the expression's children. 11978 CC = E->getExprLoc(); 11979 BinaryOperator *BO = dyn_cast<BinaryOperator>(E); 11980 bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd; 11981 for (Stmt *SubStmt : E->children()) { 11982 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt); 11983 if (!ChildExpr) 11984 continue; 11985 11986 if (IsLogicalAndOperator && 11987 isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts())) 11988 // Ignore checking string literals that are in logical and operators. 11989 // This is a common pattern for asserts. 11990 continue; 11991 WorkList.push_back({ChildExpr, CC, IsListInit}); 11992 } 11993 11994 if (BO && BO->isLogicalOp()) { 11995 Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts(); 11996 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 11997 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 11998 11999 SubExpr = BO->getRHS()->IgnoreParenImpCasts(); 12000 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr)) 12001 ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc()); 12002 } 12003 12004 if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) { 12005 if (U->getOpcode() == UO_LNot) { 12006 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC); 12007 } else if (U->getOpcode() != UO_AddrOf) { 12008 if (U->getSubExpr()->getType()->isAtomicType()) 12009 S.Diag(U->getSubExpr()->getBeginLoc(), 12010 diag::warn_atomic_implicit_seq_cst); 12011 } 12012 } 12013 } 12014 12015 /// AnalyzeImplicitConversions - Find and report any interesting 12016 /// implicit conversions in the given expression. There are a couple 12017 /// of competing diagnostics here, -Wconversion and -Wsign-compare. 12018 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC, 12019 bool IsListInit/*= false*/) { 12020 llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList; 12021 WorkList.push_back({OrigE, CC, IsListInit}); 12022 while (!WorkList.empty()) 12023 AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList); 12024 } 12025 12026 /// Diagnose integer type and any valid implicit conversion to it. 12027 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) { 12028 // Taking into account implicit conversions, 12029 // allow any integer. 12030 if (!E->getType()->isIntegerType()) { 12031 S.Diag(E->getBeginLoc(), 12032 diag::err_opencl_enqueue_kernel_invalid_local_size_type); 12033 return true; 12034 } 12035 // Potentially emit standard warnings for implicit conversions if enabled 12036 // using -Wconversion. 12037 CheckImplicitConversion(S, E, IntT, E->getBeginLoc()); 12038 return false; 12039 } 12040 12041 // Helper function for Sema::DiagnoseAlwaysNonNullPointer. 12042 // Returns true when emitting a warning about taking the address of a reference. 12043 static bool CheckForReference(Sema &SemaRef, const Expr *E, 12044 const PartialDiagnostic &PD) { 12045 E = E->IgnoreParenImpCasts(); 12046 12047 const FunctionDecl *FD = nullptr; 12048 12049 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 12050 if (!DRE->getDecl()->getType()->isReferenceType()) 12051 return false; 12052 } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12053 if (!M->getMemberDecl()->getType()->isReferenceType()) 12054 return false; 12055 } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) { 12056 if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType()) 12057 return false; 12058 FD = Call->getDirectCallee(); 12059 } else { 12060 return false; 12061 } 12062 12063 SemaRef.Diag(E->getExprLoc(), PD); 12064 12065 // If possible, point to location of function. 12066 if (FD) { 12067 SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD; 12068 } 12069 12070 return true; 12071 } 12072 12073 // Returns true if the SourceLocation is expanded from any macro body. 12074 // Returns false if the SourceLocation is invalid, is from not in a macro 12075 // expansion, or is from expanded from a top-level macro argument. 12076 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) { 12077 if (Loc.isInvalid()) 12078 return false; 12079 12080 while (Loc.isMacroID()) { 12081 if (SM.isMacroBodyExpansion(Loc)) 12082 return true; 12083 Loc = SM.getImmediateMacroCallerLoc(Loc); 12084 } 12085 12086 return false; 12087 } 12088 12089 /// Diagnose pointers that are always non-null. 12090 /// \param E the expression containing the pointer 12091 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is 12092 /// compared to a null pointer 12093 /// \param IsEqual True when the comparison is equal to a null pointer 12094 /// \param Range Extra SourceRange to highlight in the diagnostic 12095 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E, 12096 Expr::NullPointerConstantKind NullKind, 12097 bool IsEqual, SourceRange Range) { 12098 if (!E) 12099 return; 12100 12101 // Don't warn inside macros. 12102 if (E->getExprLoc().isMacroID()) { 12103 const SourceManager &SM = getSourceManager(); 12104 if (IsInAnyMacroBody(SM, E->getExprLoc()) || 12105 IsInAnyMacroBody(SM, Range.getBegin())) 12106 return; 12107 } 12108 E = E->IgnoreImpCasts(); 12109 12110 const bool IsCompare = NullKind != Expr::NPCK_NotNull; 12111 12112 if (isa<CXXThisExpr>(E)) { 12113 unsigned DiagID = IsCompare ? diag::warn_this_null_compare 12114 : diag::warn_this_bool_conversion; 12115 Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual; 12116 return; 12117 } 12118 12119 bool IsAddressOf = false; 12120 12121 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12122 if (UO->getOpcode() != UO_AddrOf) 12123 return; 12124 IsAddressOf = true; 12125 E = UO->getSubExpr(); 12126 } 12127 12128 if (IsAddressOf) { 12129 unsigned DiagID = IsCompare 12130 ? diag::warn_address_of_reference_null_compare 12131 : diag::warn_address_of_reference_bool_conversion; 12132 PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range 12133 << IsEqual; 12134 if (CheckForReference(*this, E, PD)) { 12135 return; 12136 } 12137 } 12138 12139 auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) { 12140 bool IsParam = isa<NonNullAttr>(NonnullAttr); 12141 std::string Str; 12142 llvm::raw_string_ostream S(Str); 12143 E->printPretty(S, nullptr, getPrintingPolicy()); 12144 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare 12145 : diag::warn_cast_nonnull_to_bool; 12146 Diag(E->getExprLoc(), DiagID) << IsParam << S.str() 12147 << E->getSourceRange() << Range << IsEqual; 12148 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam; 12149 }; 12150 12151 // If we have a CallExpr that is tagged with returns_nonnull, we can complain. 12152 if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) { 12153 if (auto *Callee = Call->getDirectCallee()) { 12154 if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) { 12155 ComplainAboutNonnullParamOrCall(A); 12156 return; 12157 } 12158 } 12159 } 12160 12161 // Expect to find a single Decl. Skip anything more complicated. 12162 ValueDecl *D = nullptr; 12163 if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) { 12164 D = R->getDecl(); 12165 } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) { 12166 D = M->getMemberDecl(); 12167 } 12168 12169 // Weak Decls can be null. 12170 if (!D || D->isWeak()) 12171 return; 12172 12173 // Check for parameter decl with nonnull attribute 12174 if (const auto* PV = dyn_cast<ParmVarDecl>(D)) { 12175 if (getCurFunction() && 12176 !getCurFunction()->ModifiedNonNullParams.count(PV)) { 12177 if (const Attr *A = PV->getAttr<NonNullAttr>()) { 12178 ComplainAboutNonnullParamOrCall(A); 12179 return; 12180 } 12181 12182 if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) { 12183 // Skip function template not specialized yet. 12184 if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate) 12185 return; 12186 auto ParamIter = llvm::find(FD->parameters(), PV); 12187 assert(ParamIter != FD->param_end()); 12188 unsigned ParamNo = std::distance(FD->param_begin(), ParamIter); 12189 12190 for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) { 12191 if (!NonNull->args_size()) { 12192 ComplainAboutNonnullParamOrCall(NonNull); 12193 return; 12194 } 12195 12196 for (const ParamIdx &ArgNo : NonNull->args()) { 12197 if (ArgNo.getASTIndex() == ParamNo) { 12198 ComplainAboutNonnullParamOrCall(NonNull); 12199 return; 12200 } 12201 } 12202 } 12203 } 12204 } 12205 } 12206 12207 QualType T = D->getType(); 12208 const bool IsArray = T->isArrayType(); 12209 const bool IsFunction = T->isFunctionType(); 12210 12211 // Address of function is used to silence the function warning. 12212 if (IsAddressOf && IsFunction) { 12213 return; 12214 } 12215 12216 // Found nothing. 12217 if (!IsAddressOf && !IsFunction && !IsArray) 12218 return; 12219 12220 // Pretty print the expression for the diagnostic. 12221 std::string Str; 12222 llvm::raw_string_ostream S(Str); 12223 E->printPretty(S, nullptr, getPrintingPolicy()); 12224 12225 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare 12226 : diag::warn_impcast_pointer_to_bool; 12227 enum { 12228 AddressOf, 12229 FunctionPointer, 12230 ArrayPointer 12231 } DiagType; 12232 if (IsAddressOf) 12233 DiagType = AddressOf; 12234 else if (IsFunction) 12235 DiagType = FunctionPointer; 12236 else if (IsArray) 12237 DiagType = ArrayPointer; 12238 else 12239 llvm_unreachable("Could not determine diagnostic."); 12240 Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange() 12241 << Range << IsEqual; 12242 12243 if (!IsFunction) 12244 return; 12245 12246 // Suggest '&' to silence the function warning. 12247 Diag(E->getExprLoc(), diag::note_function_warning_silence) 12248 << FixItHint::CreateInsertion(E->getBeginLoc(), "&"); 12249 12250 // Check to see if '()' fixit should be emitted. 12251 QualType ReturnType; 12252 UnresolvedSet<4> NonTemplateOverloads; 12253 tryExprAsCall(*E, ReturnType, NonTemplateOverloads); 12254 if (ReturnType.isNull()) 12255 return; 12256 12257 if (IsCompare) { 12258 // There are two cases here. If there is null constant, the only suggest 12259 // for a pointer return type. If the null is 0, then suggest if the return 12260 // type is a pointer or an integer type. 12261 if (!ReturnType->isPointerType()) { 12262 if (NullKind == Expr::NPCK_ZeroExpression || 12263 NullKind == Expr::NPCK_ZeroLiteral) { 12264 if (!ReturnType->isIntegerType()) 12265 return; 12266 } else { 12267 return; 12268 } 12269 } 12270 } else { // !IsCompare 12271 // For function to bool, only suggest if the function pointer has bool 12272 // return type. 12273 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool)) 12274 return; 12275 } 12276 Diag(E->getExprLoc(), diag::note_function_to_function_call) 12277 << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()"); 12278 } 12279 12280 /// Diagnoses "dangerous" implicit conversions within the given 12281 /// expression (which is a full expression). Implements -Wconversion 12282 /// and -Wsign-compare. 12283 /// 12284 /// \param CC the "context" location of the implicit conversion, i.e. 12285 /// the most location of the syntactic entity requiring the implicit 12286 /// conversion 12287 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) { 12288 // Don't diagnose in unevaluated contexts. 12289 if (isUnevaluatedContext()) 12290 return; 12291 12292 // Don't diagnose for value- or type-dependent expressions. 12293 if (E->isTypeDependent() || E->isValueDependent()) 12294 return; 12295 12296 // Check for array bounds violations in cases where the check isn't triggered 12297 // elsewhere for other Expr types (like BinaryOperators), e.g. when an 12298 // ArraySubscriptExpr is on the RHS of a variable initialization. 12299 CheckArrayAccess(E); 12300 12301 // This is not the right CC for (e.g.) a variable initialization. 12302 AnalyzeImplicitConversions(*this, E, CC); 12303 } 12304 12305 /// CheckBoolLikeConversion - Check conversion of given expression to boolean. 12306 /// Input argument E is a logical expression. 12307 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) { 12308 ::CheckBoolLikeConversion(*this, E, CC); 12309 } 12310 12311 /// Diagnose when expression is an integer constant expression and its evaluation 12312 /// results in integer overflow 12313 void Sema::CheckForIntOverflow (Expr *E) { 12314 // Use a work list to deal with nested struct initializers. 12315 SmallVector<Expr *, 2> Exprs(1, E); 12316 12317 do { 12318 Expr *OriginalE = Exprs.pop_back_val(); 12319 Expr *E = OriginalE->IgnoreParenCasts(); 12320 12321 if (isa<BinaryOperator>(E)) { 12322 E->EvaluateForOverflow(Context); 12323 continue; 12324 } 12325 12326 if (auto InitList = dyn_cast<InitListExpr>(OriginalE)) 12327 Exprs.append(InitList->inits().begin(), InitList->inits().end()); 12328 else if (isa<ObjCBoxedExpr>(OriginalE)) 12329 E->EvaluateForOverflow(Context); 12330 else if (auto Call = dyn_cast<CallExpr>(E)) 12331 Exprs.append(Call->arg_begin(), Call->arg_end()); 12332 else if (auto Message = dyn_cast<ObjCMessageExpr>(E)) 12333 Exprs.append(Message->arg_begin(), Message->arg_end()); 12334 } while (!Exprs.empty()); 12335 } 12336 12337 namespace { 12338 12339 /// Visitor for expressions which looks for unsequenced operations on the 12340 /// same object. 12341 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> { 12342 using Base = ConstEvaluatedExprVisitor<SequenceChecker>; 12343 12344 /// A tree of sequenced regions within an expression. Two regions are 12345 /// unsequenced if one is an ancestor or a descendent of the other. When we 12346 /// finish processing an expression with sequencing, such as a comma 12347 /// expression, we fold its tree nodes into its parent, since they are 12348 /// unsequenced with respect to nodes we will visit later. 12349 class SequenceTree { 12350 struct Value { 12351 explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {} 12352 unsigned Parent : 31; 12353 unsigned Merged : 1; 12354 }; 12355 SmallVector<Value, 8> Values; 12356 12357 public: 12358 /// A region within an expression which may be sequenced with respect 12359 /// to some other region. 12360 class Seq { 12361 friend class SequenceTree; 12362 12363 unsigned Index; 12364 12365 explicit Seq(unsigned N) : Index(N) {} 12366 12367 public: 12368 Seq() : Index(0) {} 12369 }; 12370 12371 SequenceTree() { Values.push_back(Value(0)); } 12372 Seq root() const { return Seq(0); } 12373 12374 /// Create a new sequence of operations, which is an unsequenced 12375 /// subset of \p Parent. This sequence of operations is sequenced with 12376 /// respect to other children of \p Parent. 12377 Seq allocate(Seq Parent) { 12378 Values.push_back(Value(Parent.Index)); 12379 return Seq(Values.size() - 1); 12380 } 12381 12382 /// Merge a sequence of operations into its parent. 12383 void merge(Seq S) { 12384 Values[S.Index].Merged = true; 12385 } 12386 12387 /// Determine whether two operations are unsequenced. This operation 12388 /// is asymmetric: \p Cur should be the more recent sequence, and \p Old 12389 /// should have been merged into its parent as appropriate. 12390 bool isUnsequenced(Seq Cur, Seq Old) { 12391 unsigned C = representative(Cur.Index); 12392 unsigned Target = representative(Old.Index); 12393 while (C >= Target) { 12394 if (C == Target) 12395 return true; 12396 C = Values[C].Parent; 12397 } 12398 return false; 12399 } 12400 12401 private: 12402 /// Pick a representative for a sequence. 12403 unsigned representative(unsigned K) { 12404 if (Values[K].Merged) 12405 // Perform path compression as we go. 12406 return Values[K].Parent = representative(Values[K].Parent); 12407 return K; 12408 } 12409 }; 12410 12411 /// An object for which we can track unsequenced uses. 12412 using Object = const NamedDecl *; 12413 12414 /// Different flavors of object usage which we track. We only track the 12415 /// least-sequenced usage of each kind. 12416 enum UsageKind { 12417 /// A read of an object. Multiple unsequenced reads are OK. 12418 UK_Use, 12419 12420 /// A modification of an object which is sequenced before the value 12421 /// computation of the expression, such as ++n in C++. 12422 UK_ModAsValue, 12423 12424 /// A modification of an object which is not sequenced before the value 12425 /// computation of the expression, such as n++. 12426 UK_ModAsSideEffect, 12427 12428 UK_Count = UK_ModAsSideEffect + 1 12429 }; 12430 12431 /// Bundle together a sequencing region and the expression corresponding 12432 /// to a specific usage. One Usage is stored for each usage kind in UsageInfo. 12433 struct Usage { 12434 const Expr *UsageExpr; 12435 SequenceTree::Seq Seq; 12436 12437 Usage() : UsageExpr(nullptr), Seq() {} 12438 }; 12439 12440 struct UsageInfo { 12441 Usage Uses[UK_Count]; 12442 12443 /// Have we issued a diagnostic for this object already? 12444 bool Diagnosed; 12445 12446 UsageInfo() : Uses(), Diagnosed(false) {} 12447 }; 12448 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>; 12449 12450 Sema &SemaRef; 12451 12452 /// Sequenced regions within the expression. 12453 SequenceTree Tree; 12454 12455 /// Declaration modifications and references which we have seen. 12456 UsageInfoMap UsageMap; 12457 12458 /// The region we are currently within. 12459 SequenceTree::Seq Region; 12460 12461 /// Filled in with declarations which were modified as a side-effect 12462 /// (that is, post-increment operations). 12463 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr; 12464 12465 /// Expressions to check later. We defer checking these to reduce 12466 /// stack usage. 12467 SmallVectorImpl<const Expr *> &WorkList; 12468 12469 /// RAII object wrapping the visitation of a sequenced subexpression of an 12470 /// expression. At the end of this process, the side-effects of the evaluation 12471 /// become sequenced with respect to the value computation of the result, so 12472 /// we downgrade any UK_ModAsSideEffect within the evaluation to 12473 /// UK_ModAsValue. 12474 struct SequencedSubexpression { 12475 SequencedSubexpression(SequenceChecker &Self) 12476 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) { 12477 Self.ModAsSideEffect = &ModAsSideEffect; 12478 } 12479 12480 ~SequencedSubexpression() { 12481 for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) { 12482 // Add a new usage with usage kind UK_ModAsValue, and then restore 12483 // the previous usage with UK_ModAsSideEffect (thus clearing it if 12484 // the previous one was empty). 12485 UsageInfo &UI = Self.UsageMap[M.first]; 12486 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect]; 12487 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue); 12488 SideEffectUsage = M.second; 12489 } 12490 Self.ModAsSideEffect = OldModAsSideEffect; 12491 } 12492 12493 SequenceChecker &Self; 12494 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect; 12495 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect; 12496 }; 12497 12498 /// RAII object wrapping the visitation of a subexpression which we might 12499 /// choose to evaluate as a constant. If any subexpression is evaluated and 12500 /// found to be non-constant, this allows us to suppress the evaluation of 12501 /// the outer expression. 12502 class EvaluationTracker { 12503 public: 12504 EvaluationTracker(SequenceChecker &Self) 12505 : Self(Self), Prev(Self.EvalTracker) { 12506 Self.EvalTracker = this; 12507 } 12508 12509 ~EvaluationTracker() { 12510 Self.EvalTracker = Prev; 12511 if (Prev) 12512 Prev->EvalOK &= EvalOK; 12513 } 12514 12515 bool evaluate(const Expr *E, bool &Result) { 12516 if (!EvalOK || E->isValueDependent()) 12517 return false; 12518 EvalOK = E->EvaluateAsBooleanCondition( 12519 Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated()); 12520 return EvalOK; 12521 } 12522 12523 private: 12524 SequenceChecker &Self; 12525 EvaluationTracker *Prev; 12526 bool EvalOK = true; 12527 } *EvalTracker = nullptr; 12528 12529 /// Find the object which is produced by the specified expression, 12530 /// if any. 12531 Object getObject(const Expr *E, bool Mod) const { 12532 E = E->IgnoreParenCasts(); 12533 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 12534 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec)) 12535 return getObject(UO->getSubExpr(), Mod); 12536 } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) { 12537 if (BO->getOpcode() == BO_Comma) 12538 return getObject(BO->getRHS(), Mod); 12539 if (Mod && BO->isAssignmentOp()) 12540 return getObject(BO->getLHS(), Mod); 12541 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) { 12542 // FIXME: Check for more interesting cases, like "x.n = ++x.n". 12543 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts())) 12544 return ME->getMemberDecl(); 12545 } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) 12546 // FIXME: If this is a reference, map through to its value. 12547 return DRE->getDecl(); 12548 return nullptr; 12549 } 12550 12551 /// Note that an object \p O was modified or used by an expression 12552 /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for 12553 /// the object \p O as obtained via the \p UsageMap. 12554 void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) { 12555 // Get the old usage for the given object and usage kind. 12556 Usage &U = UI.Uses[UK]; 12557 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) { 12558 // If we have a modification as side effect and are in a sequenced 12559 // subexpression, save the old Usage so that we can restore it later 12560 // in SequencedSubexpression::~SequencedSubexpression. 12561 if (UK == UK_ModAsSideEffect && ModAsSideEffect) 12562 ModAsSideEffect->push_back(std::make_pair(O, U)); 12563 // Then record the new usage with the current sequencing region. 12564 U.UsageExpr = UsageExpr; 12565 U.Seq = Region; 12566 } 12567 } 12568 12569 /// Check whether a modification or use of an object \p O in an expression 12570 /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is 12571 /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap. 12572 /// \p IsModMod is true when we are checking for a mod-mod unsequenced 12573 /// usage and false we are checking for a mod-use unsequenced usage. 12574 void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, 12575 UsageKind OtherKind, bool IsModMod) { 12576 if (UI.Diagnosed) 12577 return; 12578 12579 const Usage &U = UI.Uses[OtherKind]; 12580 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) 12581 return; 12582 12583 const Expr *Mod = U.UsageExpr; 12584 const Expr *ModOrUse = UsageExpr; 12585 if (OtherKind == UK_Use) 12586 std::swap(Mod, ModOrUse); 12587 12588 SemaRef.DiagRuntimeBehavior( 12589 Mod->getExprLoc(), {Mod, ModOrUse}, 12590 SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod 12591 : diag::warn_unsequenced_mod_use) 12592 << O << SourceRange(ModOrUse->getExprLoc())); 12593 UI.Diagnosed = true; 12594 } 12595 12596 // A note on note{Pre, Post}{Use, Mod}: 12597 // 12598 // (It helps to follow the algorithm with an expression such as 12599 // "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced 12600 // operations before C++17 and both are well-defined in C++17). 12601 // 12602 // When visiting a node which uses/modify an object we first call notePreUse 12603 // or notePreMod before visiting its sub-expression(s). At this point the 12604 // children of the current node have not yet been visited and so the eventual 12605 // uses/modifications resulting from the children of the current node have not 12606 // been recorded yet. 12607 // 12608 // We then visit the children of the current node. After that notePostUse or 12609 // notePostMod is called. These will 1) detect an unsequenced modification 12610 // as side effect (as in "k++ + k") and 2) add a new usage with the 12611 // appropriate usage kind. 12612 // 12613 // We also have to be careful that some operation sequences modification as 12614 // side effect as well (for example: || or ,). To account for this we wrap 12615 // the visitation of such a sub-expression (for example: the LHS of || or ,) 12616 // with SequencedSubexpression. SequencedSubexpression is an RAII object 12617 // which record usages which are modifications as side effect, and then 12618 // downgrade them (or more accurately restore the previous usage which was a 12619 // modification as side effect) when exiting the scope of the sequenced 12620 // subexpression. 12621 12622 void notePreUse(Object O, const Expr *UseExpr) { 12623 UsageInfo &UI = UsageMap[O]; 12624 // Uses conflict with other modifications. 12625 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false); 12626 } 12627 12628 void notePostUse(Object O, const Expr *UseExpr) { 12629 UsageInfo &UI = UsageMap[O]; 12630 checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect, 12631 /*IsModMod=*/false); 12632 addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use); 12633 } 12634 12635 void notePreMod(Object O, const Expr *ModExpr) { 12636 UsageInfo &UI = UsageMap[O]; 12637 // Modifications conflict with other modifications and with uses. 12638 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true); 12639 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false); 12640 } 12641 12642 void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) { 12643 UsageInfo &UI = UsageMap[O]; 12644 checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect, 12645 /*IsModMod=*/true); 12646 addUsage(O, UI, ModExpr, /*UsageKind=*/UK); 12647 } 12648 12649 public: 12650 SequenceChecker(Sema &S, const Expr *E, 12651 SmallVectorImpl<const Expr *> &WorkList) 12652 : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) { 12653 Visit(E); 12654 // Silence a -Wunused-private-field since WorkList is now unused. 12655 // TODO: Evaluate if it can be used, and if not remove it. 12656 (void)this->WorkList; 12657 } 12658 12659 void VisitStmt(const Stmt *S) { 12660 // Skip all statements which aren't expressions for now. 12661 } 12662 12663 void VisitExpr(const Expr *E) { 12664 // By default, just recurse to evaluated subexpressions. 12665 Base::VisitStmt(E); 12666 } 12667 12668 void VisitCastExpr(const CastExpr *E) { 12669 Object O = Object(); 12670 if (E->getCastKind() == CK_LValueToRValue) 12671 O = getObject(E->getSubExpr(), false); 12672 12673 if (O) 12674 notePreUse(O, E); 12675 VisitExpr(E); 12676 if (O) 12677 notePostUse(O, E); 12678 } 12679 12680 void VisitSequencedExpressions(const Expr *SequencedBefore, 12681 const Expr *SequencedAfter) { 12682 SequenceTree::Seq BeforeRegion = Tree.allocate(Region); 12683 SequenceTree::Seq AfterRegion = Tree.allocate(Region); 12684 SequenceTree::Seq OldRegion = Region; 12685 12686 { 12687 SequencedSubexpression SeqBefore(*this); 12688 Region = BeforeRegion; 12689 Visit(SequencedBefore); 12690 } 12691 12692 Region = AfterRegion; 12693 Visit(SequencedAfter); 12694 12695 Region = OldRegion; 12696 12697 Tree.merge(BeforeRegion); 12698 Tree.merge(AfterRegion); 12699 } 12700 12701 void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) { 12702 // C++17 [expr.sub]p1: 12703 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The 12704 // expression E1 is sequenced before the expression E2. 12705 if (SemaRef.getLangOpts().CPlusPlus17) 12706 VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS()); 12707 else { 12708 Visit(ASE->getLHS()); 12709 Visit(ASE->getRHS()); 12710 } 12711 } 12712 12713 void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12714 void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); } 12715 void VisitBinPtrMem(const BinaryOperator *BO) { 12716 // C++17 [expr.mptr.oper]p4: 12717 // Abbreviating pm-expression.*cast-expression as E1.*E2, [...] 12718 // the expression E1 is sequenced before the expression E2. 12719 if (SemaRef.getLangOpts().CPlusPlus17) 12720 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12721 else { 12722 Visit(BO->getLHS()); 12723 Visit(BO->getRHS()); 12724 } 12725 } 12726 12727 void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12728 void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); } 12729 void VisitBinShlShr(const BinaryOperator *BO) { 12730 // C++17 [expr.shift]p4: 12731 // The expression E1 is sequenced before the expression E2. 12732 if (SemaRef.getLangOpts().CPlusPlus17) 12733 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12734 else { 12735 Visit(BO->getLHS()); 12736 Visit(BO->getRHS()); 12737 } 12738 } 12739 12740 void VisitBinComma(const BinaryOperator *BO) { 12741 // C++11 [expr.comma]p1: 12742 // Every value computation and side effect associated with the left 12743 // expression is sequenced before every value computation and side 12744 // effect associated with the right expression. 12745 VisitSequencedExpressions(BO->getLHS(), BO->getRHS()); 12746 } 12747 12748 void VisitBinAssign(const BinaryOperator *BO) { 12749 SequenceTree::Seq RHSRegion; 12750 SequenceTree::Seq LHSRegion; 12751 if (SemaRef.getLangOpts().CPlusPlus17) { 12752 RHSRegion = Tree.allocate(Region); 12753 LHSRegion = Tree.allocate(Region); 12754 } else { 12755 RHSRegion = Region; 12756 LHSRegion = Region; 12757 } 12758 SequenceTree::Seq OldRegion = Region; 12759 12760 // C++11 [expr.ass]p1: 12761 // [...] the assignment is sequenced after the value computation 12762 // of the right and left operands, [...] 12763 // 12764 // so check it before inspecting the operands and update the 12765 // map afterwards. 12766 Object O = getObject(BO->getLHS(), /*Mod=*/true); 12767 if (O) 12768 notePreMod(O, BO); 12769 12770 if (SemaRef.getLangOpts().CPlusPlus17) { 12771 // C++17 [expr.ass]p1: 12772 // [...] The right operand is sequenced before the left operand. [...] 12773 { 12774 SequencedSubexpression SeqBefore(*this); 12775 Region = RHSRegion; 12776 Visit(BO->getRHS()); 12777 } 12778 12779 Region = LHSRegion; 12780 Visit(BO->getLHS()); 12781 12782 if (O && isa<CompoundAssignOperator>(BO)) 12783 notePostUse(O, BO); 12784 12785 } else { 12786 // C++11 does not specify any sequencing between the LHS and RHS. 12787 Region = LHSRegion; 12788 Visit(BO->getLHS()); 12789 12790 if (O && isa<CompoundAssignOperator>(BO)) 12791 notePostUse(O, BO); 12792 12793 Region = RHSRegion; 12794 Visit(BO->getRHS()); 12795 } 12796 12797 // C++11 [expr.ass]p1: 12798 // the assignment is sequenced [...] before the value computation of the 12799 // assignment expression. 12800 // C11 6.5.16/3 has no such rule. 12801 Region = OldRegion; 12802 if (O) 12803 notePostMod(O, BO, 12804 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12805 : UK_ModAsSideEffect); 12806 if (SemaRef.getLangOpts().CPlusPlus17) { 12807 Tree.merge(RHSRegion); 12808 Tree.merge(LHSRegion); 12809 } 12810 } 12811 12812 void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) { 12813 VisitBinAssign(CAO); 12814 } 12815 12816 void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12817 void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); } 12818 void VisitUnaryPreIncDec(const UnaryOperator *UO) { 12819 Object O = getObject(UO->getSubExpr(), true); 12820 if (!O) 12821 return VisitExpr(UO); 12822 12823 notePreMod(O, UO); 12824 Visit(UO->getSubExpr()); 12825 // C++11 [expr.pre.incr]p1: 12826 // the expression ++x is equivalent to x+=1 12827 notePostMod(O, UO, 12828 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue 12829 : UK_ModAsSideEffect); 12830 } 12831 12832 void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12833 void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); } 12834 void VisitUnaryPostIncDec(const UnaryOperator *UO) { 12835 Object O = getObject(UO->getSubExpr(), true); 12836 if (!O) 12837 return VisitExpr(UO); 12838 12839 notePreMod(O, UO); 12840 Visit(UO->getSubExpr()); 12841 notePostMod(O, UO, UK_ModAsSideEffect); 12842 } 12843 12844 void VisitBinLOr(const BinaryOperator *BO) { 12845 // C++11 [expr.log.or]p2: 12846 // If the second expression is evaluated, every value computation and 12847 // side effect associated with the first expression is sequenced before 12848 // every value computation and side effect associated with the 12849 // second expression. 12850 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12851 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12852 SequenceTree::Seq OldRegion = Region; 12853 12854 EvaluationTracker Eval(*this); 12855 { 12856 SequencedSubexpression Sequenced(*this); 12857 Region = LHSRegion; 12858 Visit(BO->getLHS()); 12859 } 12860 12861 // C++11 [expr.log.or]p1: 12862 // [...] the second operand is not evaluated if the first operand 12863 // evaluates to true. 12864 bool EvalResult = false; 12865 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12866 bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult); 12867 if (ShouldVisitRHS) { 12868 Region = RHSRegion; 12869 Visit(BO->getRHS()); 12870 } 12871 12872 Region = OldRegion; 12873 Tree.merge(LHSRegion); 12874 Tree.merge(RHSRegion); 12875 } 12876 12877 void VisitBinLAnd(const BinaryOperator *BO) { 12878 // C++11 [expr.log.and]p2: 12879 // If the second expression is evaluated, every value computation and 12880 // side effect associated with the first expression is sequenced before 12881 // every value computation and side effect associated with the 12882 // second expression. 12883 SequenceTree::Seq LHSRegion = Tree.allocate(Region); 12884 SequenceTree::Seq RHSRegion = Tree.allocate(Region); 12885 SequenceTree::Seq OldRegion = Region; 12886 12887 EvaluationTracker Eval(*this); 12888 { 12889 SequencedSubexpression Sequenced(*this); 12890 Region = LHSRegion; 12891 Visit(BO->getLHS()); 12892 } 12893 12894 // C++11 [expr.log.and]p1: 12895 // [...] the second operand is not evaluated if the first operand is false. 12896 bool EvalResult = false; 12897 bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult); 12898 bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult); 12899 if (ShouldVisitRHS) { 12900 Region = RHSRegion; 12901 Visit(BO->getRHS()); 12902 } 12903 12904 Region = OldRegion; 12905 Tree.merge(LHSRegion); 12906 Tree.merge(RHSRegion); 12907 } 12908 12909 void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) { 12910 // C++11 [expr.cond]p1: 12911 // [...] Every value computation and side effect associated with the first 12912 // expression is sequenced before every value computation and side effect 12913 // associated with the second or third expression. 12914 SequenceTree::Seq ConditionRegion = Tree.allocate(Region); 12915 12916 // No sequencing is specified between the true and false expression. 12917 // However since exactly one of both is going to be evaluated we can 12918 // consider them to be sequenced. This is needed to avoid warning on 12919 // something like "x ? y+= 1 : y += 2;" in the case where we will visit 12920 // both the true and false expressions because we can't evaluate x. 12921 // This will still allow us to detect an expression like (pre C++17) 12922 // "(x ? y += 1 : y += 2) = y". 12923 // 12924 // We don't wrap the visitation of the true and false expression with 12925 // SequencedSubexpression because we don't want to downgrade modifications 12926 // as side effect in the true and false expressions after the visition 12927 // is done. (for example in the expression "(x ? y++ : y++) + y" we should 12928 // not warn between the two "y++", but we should warn between the "y++" 12929 // and the "y". 12930 SequenceTree::Seq TrueRegion = Tree.allocate(Region); 12931 SequenceTree::Seq FalseRegion = Tree.allocate(Region); 12932 SequenceTree::Seq OldRegion = Region; 12933 12934 EvaluationTracker Eval(*this); 12935 { 12936 SequencedSubexpression Sequenced(*this); 12937 Region = ConditionRegion; 12938 Visit(CO->getCond()); 12939 } 12940 12941 // C++11 [expr.cond]p1: 12942 // [...] The first expression is contextually converted to bool (Clause 4). 12943 // It is evaluated and if it is true, the result of the conditional 12944 // expression is the value of the second expression, otherwise that of the 12945 // third expression. Only one of the second and third expressions is 12946 // evaluated. [...] 12947 bool EvalResult = false; 12948 bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult); 12949 bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult); 12950 bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult); 12951 if (ShouldVisitTrueExpr) { 12952 Region = TrueRegion; 12953 Visit(CO->getTrueExpr()); 12954 } 12955 if (ShouldVisitFalseExpr) { 12956 Region = FalseRegion; 12957 Visit(CO->getFalseExpr()); 12958 } 12959 12960 Region = OldRegion; 12961 Tree.merge(ConditionRegion); 12962 Tree.merge(TrueRegion); 12963 Tree.merge(FalseRegion); 12964 } 12965 12966 void VisitCallExpr(const CallExpr *CE) { 12967 // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions. 12968 12969 if (CE->isUnevaluatedBuiltinCall(Context)) 12970 return; 12971 12972 // C++11 [intro.execution]p15: 12973 // When calling a function [...], every value computation and side effect 12974 // associated with any argument expression, or with the postfix expression 12975 // designating the called function, is sequenced before execution of every 12976 // expression or statement in the body of the function [and thus before 12977 // the value computation of its result]. 12978 SequencedSubexpression Sequenced(*this); 12979 SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] { 12980 // C++17 [expr.call]p5 12981 // The postfix-expression is sequenced before each expression in the 12982 // expression-list and any default argument. [...] 12983 SequenceTree::Seq CalleeRegion; 12984 SequenceTree::Seq OtherRegion; 12985 if (SemaRef.getLangOpts().CPlusPlus17) { 12986 CalleeRegion = Tree.allocate(Region); 12987 OtherRegion = Tree.allocate(Region); 12988 } else { 12989 CalleeRegion = Region; 12990 OtherRegion = Region; 12991 } 12992 SequenceTree::Seq OldRegion = Region; 12993 12994 // Visit the callee expression first. 12995 Region = CalleeRegion; 12996 if (SemaRef.getLangOpts().CPlusPlus17) { 12997 SequencedSubexpression Sequenced(*this); 12998 Visit(CE->getCallee()); 12999 } else { 13000 Visit(CE->getCallee()); 13001 } 13002 13003 // Then visit the argument expressions. 13004 Region = OtherRegion; 13005 for (const Expr *Argument : CE->arguments()) 13006 Visit(Argument); 13007 13008 Region = OldRegion; 13009 if (SemaRef.getLangOpts().CPlusPlus17) { 13010 Tree.merge(CalleeRegion); 13011 Tree.merge(OtherRegion); 13012 } 13013 }); 13014 } 13015 13016 void VisitCXXConstructExpr(const CXXConstructExpr *CCE) { 13017 // This is a call, so all subexpressions are sequenced before the result. 13018 SequencedSubexpression Sequenced(*this); 13019 13020 if (!CCE->isListInitialization()) 13021 return VisitExpr(CCE); 13022 13023 // In C++11, list initializations are sequenced. 13024 SmallVector<SequenceTree::Seq, 32> Elts; 13025 SequenceTree::Seq Parent = Region; 13026 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 13027 E = CCE->arg_end(); 13028 I != E; ++I) { 13029 Region = Tree.allocate(Parent); 13030 Elts.push_back(Region); 13031 Visit(*I); 13032 } 13033 13034 // Forget that the initializers are sequenced. 13035 Region = Parent; 13036 for (unsigned I = 0; I < Elts.size(); ++I) 13037 Tree.merge(Elts[I]); 13038 } 13039 13040 void VisitInitListExpr(const InitListExpr *ILE) { 13041 if (!SemaRef.getLangOpts().CPlusPlus11) 13042 return VisitExpr(ILE); 13043 13044 // In C++11, list initializations are sequenced. 13045 SmallVector<SequenceTree::Seq, 32> Elts; 13046 SequenceTree::Seq Parent = Region; 13047 for (unsigned I = 0; I < ILE->getNumInits(); ++I) { 13048 const Expr *E = ILE->getInit(I); 13049 if (!E) 13050 continue; 13051 Region = Tree.allocate(Parent); 13052 Elts.push_back(Region); 13053 Visit(E); 13054 } 13055 13056 // Forget that the initializers are sequenced. 13057 Region = Parent; 13058 for (unsigned I = 0; I < Elts.size(); ++I) 13059 Tree.merge(Elts[I]); 13060 } 13061 }; 13062 13063 } // namespace 13064 13065 void Sema::CheckUnsequencedOperations(const Expr *E) { 13066 SmallVector<const Expr *, 8> WorkList; 13067 WorkList.push_back(E); 13068 while (!WorkList.empty()) { 13069 const Expr *Item = WorkList.pop_back_val(); 13070 SequenceChecker(*this, Item, WorkList); 13071 } 13072 } 13073 13074 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc, 13075 bool IsConstexpr) { 13076 llvm::SaveAndRestore<bool> ConstantContext( 13077 isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E)); 13078 CheckImplicitConversions(E, CheckLoc); 13079 if (!E->isInstantiationDependent()) 13080 CheckUnsequencedOperations(E); 13081 if (!IsConstexpr && !E->isValueDependent()) 13082 CheckForIntOverflow(E); 13083 DiagnoseMisalignedMembers(); 13084 } 13085 13086 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc, 13087 FieldDecl *BitField, 13088 Expr *Init) { 13089 (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc); 13090 } 13091 13092 static void diagnoseArrayStarInParamType(Sema &S, QualType PType, 13093 SourceLocation Loc) { 13094 if (!PType->isVariablyModifiedType()) 13095 return; 13096 if (const auto *PointerTy = dyn_cast<PointerType>(PType)) { 13097 diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc); 13098 return; 13099 } 13100 if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) { 13101 diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc); 13102 return; 13103 } 13104 if (const auto *ParenTy = dyn_cast<ParenType>(PType)) { 13105 diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc); 13106 return; 13107 } 13108 13109 const ArrayType *AT = S.Context.getAsArrayType(PType); 13110 if (!AT) 13111 return; 13112 13113 if (AT->getSizeModifier() != ArrayType::Star) { 13114 diagnoseArrayStarInParamType(S, AT->getElementType(), Loc); 13115 return; 13116 } 13117 13118 S.Diag(Loc, diag::err_array_star_in_function_definition); 13119 } 13120 13121 /// CheckParmsForFunctionDef - Check that the parameters of the given 13122 /// function are appropriate for the definition of a function. This 13123 /// takes care of any checks that cannot be performed on the 13124 /// declaration itself, e.g., that the types of each of the function 13125 /// parameters are complete. 13126 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, 13127 bool CheckParameterNames) { 13128 bool HasInvalidParm = false; 13129 for (ParmVarDecl *Param : Parameters) { 13130 // C99 6.7.5.3p4: the parameters in a parameter type list in a 13131 // function declarator that is part of a function definition of 13132 // that function shall not have incomplete type. 13133 // 13134 // This is also C++ [dcl.fct]p6. 13135 if (!Param->isInvalidDecl() && 13136 RequireCompleteType(Param->getLocation(), Param->getType(), 13137 diag::err_typecheck_decl_incomplete_type)) { 13138 Param->setInvalidDecl(); 13139 HasInvalidParm = true; 13140 } 13141 13142 // C99 6.9.1p5: If the declarator includes a parameter type list, the 13143 // declaration of each parameter shall include an identifier. 13144 if (CheckParameterNames && Param->getIdentifier() == nullptr && 13145 !Param->isImplicit() && !getLangOpts().CPlusPlus) { 13146 // Diagnose this as an extension in C17 and earlier. 13147 if (!getLangOpts().C2x) 13148 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x); 13149 } 13150 13151 // C99 6.7.5.3p12: 13152 // If the function declarator is not part of a definition of that 13153 // function, parameters may have incomplete type and may use the [*] 13154 // notation in their sequences of declarator specifiers to specify 13155 // variable length array types. 13156 QualType PType = Param->getOriginalType(); 13157 // FIXME: This diagnostic should point the '[*]' if source-location 13158 // information is added for it. 13159 diagnoseArrayStarInParamType(*this, PType, Param->getLocation()); 13160 13161 // If the parameter is a c++ class type and it has to be destructed in the 13162 // callee function, declare the destructor so that it can be called by the 13163 // callee function. Do not perform any direct access check on the dtor here. 13164 if (!Param->isInvalidDecl()) { 13165 if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) { 13166 if (!ClassDecl->isInvalidDecl() && 13167 !ClassDecl->hasIrrelevantDestructor() && 13168 !ClassDecl->isDependentContext() && 13169 ClassDecl->isParamDestroyedInCallee()) { 13170 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl); 13171 MarkFunctionReferenced(Param->getLocation(), Destructor); 13172 DiagnoseUseOfDecl(Destructor, Param->getLocation()); 13173 } 13174 } 13175 } 13176 13177 // Parameters with the pass_object_size attribute only need to be marked 13178 // constant at function definitions. Because we lack information about 13179 // whether we're on a declaration or definition when we're instantiating the 13180 // attribute, we need to check for constness here. 13181 if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>()) 13182 if (!Param->getType().isConstQualified()) 13183 Diag(Param->getLocation(), diag::err_attribute_pointers_only) 13184 << Attr->getSpelling() << 1; 13185 13186 // Check for parameter names shadowing fields from the class. 13187 if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) { 13188 // The owning context for the parameter should be the function, but we 13189 // want to see if this function's declaration context is a record. 13190 DeclContext *DC = Param->getDeclContext(); 13191 if (DC && DC->isFunctionOrMethod()) { 13192 if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent())) 13193 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(), 13194 RD, /*DeclIsField*/ false); 13195 } 13196 } 13197 } 13198 13199 return HasInvalidParm; 13200 } 13201 13202 Optional<std::pair<CharUnits, CharUnits>> 13203 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx); 13204 13205 /// Compute the alignment and offset of the base class object given the 13206 /// derived-to-base cast expression and the alignment and offset of the derived 13207 /// class object. 13208 static std::pair<CharUnits, CharUnits> 13209 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, 13210 CharUnits BaseAlignment, CharUnits Offset, 13211 ASTContext &Ctx) { 13212 for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE; 13213 ++PathI) { 13214 const CXXBaseSpecifier *Base = *PathI; 13215 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl(); 13216 if (Base->isVirtual()) { 13217 // The complete object may have a lower alignment than the non-virtual 13218 // alignment of the base, in which case the base may be misaligned. Choose 13219 // the smaller of the non-virtual alignment and BaseAlignment, which is a 13220 // conservative lower bound of the complete object alignment. 13221 CharUnits NonVirtualAlignment = 13222 Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment(); 13223 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment); 13224 Offset = CharUnits::Zero(); 13225 } else { 13226 const ASTRecordLayout &RL = 13227 Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl()); 13228 Offset += RL.getBaseClassOffset(BaseDecl); 13229 } 13230 DerivedType = Base->getType(); 13231 } 13232 13233 return std::make_pair(BaseAlignment, Offset); 13234 } 13235 13236 /// Compute the alignment and offset of a binary additive operator. 13237 static Optional<std::pair<CharUnits, CharUnits>> 13238 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, 13239 bool IsSub, ASTContext &Ctx) { 13240 QualType PointeeType = PtrE->getType()->getPointeeType(); 13241 13242 if (!PointeeType->isConstantSizeType()) 13243 return llvm::None; 13244 13245 auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx); 13246 13247 if (!P) 13248 return llvm::None; 13249 13250 llvm::APSInt IdxRes; 13251 CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType); 13252 if (IntE->isIntegerConstantExpr(IdxRes, Ctx)) { 13253 CharUnits Offset = EltSize * IdxRes.getExtValue(); 13254 if (IsSub) 13255 Offset = -Offset; 13256 return std::make_pair(P->first, P->second + Offset); 13257 } 13258 13259 // If the integer expression isn't a constant expression, compute the lower 13260 // bound of the alignment using the alignment and offset of the pointer 13261 // expression and the element size. 13262 return std::make_pair( 13263 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize), 13264 CharUnits::Zero()); 13265 } 13266 13267 /// This helper function takes an lvalue expression and returns the alignment of 13268 /// a VarDecl and a constant offset from the VarDecl. 13269 Optional<std::pair<CharUnits, CharUnits>> 13270 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) { 13271 E = E->IgnoreParens(); 13272 switch (E->getStmtClass()) { 13273 default: 13274 break; 13275 case Stmt::CStyleCastExprClass: 13276 case Stmt::CXXStaticCastExprClass: 13277 case Stmt::ImplicitCastExprClass: { 13278 auto *CE = cast<CastExpr>(E); 13279 const Expr *From = CE->getSubExpr(); 13280 switch (CE->getCastKind()) { 13281 default: 13282 break; 13283 case CK_NoOp: 13284 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13285 case CK_UncheckedDerivedToBase: 13286 case CK_DerivedToBase: { 13287 auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13288 if (!P) 13289 break; 13290 return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first, 13291 P->second, Ctx); 13292 } 13293 } 13294 break; 13295 } 13296 case Stmt::ArraySubscriptExprClass: { 13297 auto *ASE = cast<ArraySubscriptExpr>(E); 13298 return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(), 13299 false, Ctx); 13300 } 13301 case Stmt::DeclRefExprClass: { 13302 if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) { 13303 // FIXME: If VD is captured by copy or is an escaping __block variable, 13304 // use the alignment of VD's type. 13305 if (!VD->getType()->isReferenceType()) 13306 return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero()); 13307 if (VD->hasInit()) 13308 return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx); 13309 } 13310 break; 13311 } 13312 case Stmt::MemberExprClass: { 13313 auto *ME = cast<MemberExpr>(E); 13314 if (ME->isArrow()) 13315 break; 13316 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()); 13317 if (!FD || FD->getType()->isReferenceType()) 13318 break; 13319 auto P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx); 13320 if (!P) 13321 break; 13322 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent()); 13323 uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex()); 13324 return std::make_pair(P->first, 13325 P->second + CharUnits::fromQuantity(Offset)); 13326 } 13327 case Stmt::UnaryOperatorClass: { 13328 auto *UO = cast<UnaryOperator>(E); 13329 switch (UO->getOpcode()) { 13330 default: 13331 break; 13332 case UO_Deref: 13333 return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx); 13334 } 13335 break; 13336 } 13337 case Stmt::BinaryOperatorClass: { 13338 auto *BO = cast<BinaryOperator>(E); 13339 auto Opcode = BO->getOpcode(); 13340 switch (Opcode) { 13341 default: 13342 break; 13343 case BO_Comma: 13344 return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx); 13345 } 13346 break; 13347 } 13348 } 13349 return llvm::None; 13350 } 13351 13352 /// This helper function takes a pointer expression and returns the alignment of 13353 /// a VarDecl and a constant offset from the VarDecl. 13354 Optional<std::pair<CharUnits, CharUnits>> 13355 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) { 13356 E = E->IgnoreParens(); 13357 switch (E->getStmtClass()) { 13358 default: 13359 break; 13360 case Stmt::CStyleCastExprClass: 13361 case Stmt::CXXStaticCastExprClass: 13362 case Stmt::ImplicitCastExprClass: { 13363 auto *CE = cast<CastExpr>(E); 13364 const Expr *From = CE->getSubExpr(); 13365 switch (CE->getCastKind()) { 13366 default: 13367 break; 13368 case CK_NoOp: 13369 return getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13370 case CK_ArrayToPointerDecay: 13371 return getBaseAlignmentAndOffsetFromLValue(From, Ctx); 13372 case CK_UncheckedDerivedToBase: 13373 case CK_DerivedToBase: { 13374 auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx); 13375 if (!P) 13376 break; 13377 return getDerivedToBaseAlignmentAndOffset( 13378 CE, From->getType()->getPointeeType(), P->first, P->second, Ctx); 13379 } 13380 } 13381 break; 13382 } 13383 case Stmt::UnaryOperatorClass: { 13384 auto *UO = cast<UnaryOperator>(E); 13385 if (UO->getOpcode() == UO_AddrOf) 13386 return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx); 13387 break; 13388 } 13389 case Stmt::BinaryOperatorClass: { 13390 auto *BO = cast<BinaryOperator>(E); 13391 auto Opcode = BO->getOpcode(); 13392 switch (Opcode) { 13393 default: 13394 break; 13395 case BO_Add: 13396 case BO_Sub: { 13397 const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS(); 13398 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType()) 13399 std::swap(LHS, RHS); 13400 return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub, 13401 Ctx); 13402 } 13403 case BO_Comma: 13404 return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx); 13405 } 13406 break; 13407 } 13408 } 13409 return llvm::None; 13410 } 13411 13412 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) { 13413 // See if we can compute the alignment of a VarDecl and an offset from it. 13414 Optional<std::pair<CharUnits, CharUnits>> P = 13415 getBaseAlignmentAndOffsetFromPtr(E, S.Context); 13416 13417 if (P) 13418 return P->first.alignmentAtOffset(P->second); 13419 13420 // If that failed, return the type's alignment. 13421 return S.Context.getTypeAlignInChars(E->getType()->getPointeeType()); 13422 } 13423 13424 /// CheckCastAlign - Implements -Wcast-align, which warns when a 13425 /// pointer cast increases the alignment requirements. 13426 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) { 13427 // This is actually a lot of work to potentially be doing on every 13428 // cast; don't do it if we're ignoring -Wcast_align (as is the default). 13429 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin())) 13430 return; 13431 13432 // Ignore dependent types. 13433 if (T->isDependentType() || Op->getType()->isDependentType()) 13434 return; 13435 13436 // Require that the destination be a pointer type. 13437 const PointerType *DestPtr = T->getAs<PointerType>(); 13438 if (!DestPtr) return; 13439 13440 // If the destination has alignment 1, we're done. 13441 QualType DestPointee = DestPtr->getPointeeType(); 13442 if (DestPointee->isIncompleteType()) return; 13443 CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee); 13444 if (DestAlign.isOne()) return; 13445 13446 // Require that the source be a pointer type. 13447 const PointerType *SrcPtr = Op->getType()->getAs<PointerType>(); 13448 if (!SrcPtr) return; 13449 QualType SrcPointee = SrcPtr->getPointeeType(); 13450 13451 // Whitelist casts from cv void*. We already implicitly 13452 // whitelisted casts to cv void*, since they have alignment 1. 13453 // Also whitelist casts involving incomplete types, which implicitly 13454 // includes 'void'. 13455 if (SrcPointee->isIncompleteType()) return; 13456 13457 CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this); 13458 13459 if (SrcAlign >= DestAlign) return; 13460 13461 Diag(TRange.getBegin(), diag::warn_cast_align) 13462 << Op->getType() << T 13463 << static_cast<unsigned>(SrcAlign.getQuantity()) 13464 << static_cast<unsigned>(DestAlign.getQuantity()) 13465 << TRange << Op->getSourceRange(); 13466 } 13467 13468 /// Check whether this array fits the idiom of a size-one tail padded 13469 /// array member of a struct. 13470 /// 13471 /// We avoid emitting out-of-bounds access warnings for such arrays as they are 13472 /// commonly used to emulate flexible arrays in C89 code. 13473 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, 13474 const NamedDecl *ND) { 13475 if (Size != 1 || !ND) return false; 13476 13477 const FieldDecl *FD = dyn_cast<FieldDecl>(ND); 13478 if (!FD) return false; 13479 13480 // Don't consider sizes resulting from macro expansions or template argument 13481 // substitution to form C89 tail-padded arrays. 13482 13483 TypeSourceInfo *TInfo = FD->getTypeSourceInfo(); 13484 while (TInfo) { 13485 TypeLoc TL = TInfo->getTypeLoc(); 13486 // Look through typedefs. 13487 if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) { 13488 const TypedefNameDecl *TDL = TTL.getTypedefNameDecl(); 13489 TInfo = TDL->getTypeSourceInfo(); 13490 continue; 13491 } 13492 if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) { 13493 const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr()); 13494 if (!SizeExpr || SizeExpr->getExprLoc().isMacroID()) 13495 return false; 13496 } 13497 break; 13498 } 13499 13500 const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext()); 13501 if (!RD) return false; 13502 if (RD->isUnion()) return false; 13503 if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 13504 if (!CRD->isStandardLayout()) return false; 13505 } 13506 13507 // See if this is the last field decl in the record. 13508 const Decl *D = FD; 13509 while ((D = D->getNextDeclInContext())) 13510 if (isa<FieldDecl>(D)) 13511 return false; 13512 return true; 13513 } 13514 13515 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, 13516 const ArraySubscriptExpr *ASE, 13517 bool AllowOnePastEnd, bool IndexNegated) { 13518 // Already diagnosed by the constant evaluator. 13519 if (isConstantEvaluated()) 13520 return; 13521 13522 IndexExpr = IndexExpr->IgnoreParenImpCasts(); 13523 if (IndexExpr->isValueDependent()) 13524 return; 13525 13526 const Type *EffectiveType = 13527 BaseExpr->getType()->getPointeeOrArrayElementType(); 13528 BaseExpr = BaseExpr->IgnoreParenCasts(); 13529 const ConstantArrayType *ArrayTy = 13530 Context.getAsConstantArrayType(BaseExpr->getType()); 13531 13532 if (!ArrayTy) 13533 return; 13534 13535 const Type *BaseType = ArrayTy->getElementType().getTypePtr(); 13536 if (EffectiveType->isDependentType() || BaseType->isDependentType()) 13537 return; 13538 13539 Expr::EvalResult Result; 13540 if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects)) 13541 return; 13542 13543 llvm::APSInt index = Result.Val.getInt(); 13544 if (IndexNegated) 13545 index = -index; 13546 13547 const NamedDecl *ND = nullptr; 13548 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13549 ND = DRE->getDecl(); 13550 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13551 ND = ME->getMemberDecl(); 13552 13553 if (index.isUnsigned() || !index.isNegative()) { 13554 // It is possible that the type of the base expression after 13555 // IgnoreParenCasts is incomplete, even though the type of the base 13556 // expression before IgnoreParenCasts is complete (see PR39746 for an 13557 // example). In this case we have no information about whether the array 13558 // access exceeds the array bounds. However we can still diagnose an array 13559 // access which precedes the array bounds. 13560 if (BaseType->isIncompleteType()) 13561 return; 13562 13563 llvm::APInt size = ArrayTy->getSize(); 13564 if (!size.isStrictlyPositive()) 13565 return; 13566 13567 if (BaseType != EffectiveType) { 13568 // Make sure we're comparing apples to apples when comparing index to size 13569 uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType); 13570 uint64_t array_typesize = Context.getTypeSize(BaseType); 13571 // Handle ptrarith_typesize being zero, such as when casting to void* 13572 if (!ptrarith_typesize) ptrarith_typesize = 1; 13573 if (ptrarith_typesize != array_typesize) { 13574 // There's a cast to a different size type involved 13575 uint64_t ratio = array_typesize / ptrarith_typesize; 13576 // TODO: Be smarter about handling cases where array_typesize is not a 13577 // multiple of ptrarith_typesize 13578 if (ptrarith_typesize * ratio == array_typesize) 13579 size *= llvm::APInt(size.getBitWidth(), ratio); 13580 } 13581 } 13582 13583 if (size.getBitWidth() > index.getBitWidth()) 13584 index = index.zext(size.getBitWidth()); 13585 else if (size.getBitWidth() < index.getBitWidth()) 13586 size = size.zext(index.getBitWidth()); 13587 13588 // For array subscripting the index must be less than size, but for pointer 13589 // arithmetic also allow the index (offset) to be equal to size since 13590 // computing the next address after the end of the array is legal and 13591 // commonly done e.g. in C++ iterators and range-based for loops. 13592 if (AllowOnePastEnd ? index.ule(size) : index.ult(size)) 13593 return; 13594 13595 // Also don't warn for arrays of size 1 which are members of some 13596 // structure. These are often used to approximate flexible arrays in C89 13597 // code. 13598 if (IsTailPaddedMemberArray(*this, size, ND)) 13599 return; 13600 13601 // Suppress the warning if the subscript expression (as identified by the 13602 // ']' location) and the index expression are both from macro expansions 13603 // within a system header. 13604 if (ASE) { 13605 SourceLocation RBracketLoc = SourceMgr.getSpellingLoc( 13606 ASE->getRBracketLoc()); 13607 if (SourceMgr.isInSystemHeader(RBracketLoc)) { 13608 SourceLocation IndexLoc = 13609 SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc()); 13610 if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc)) 13611 return; 13612 } 13613 } 13614 13615 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds; 13616 if (ASE) 13617 DiagID = diag::warn_array_index_exceeds_bounds; 13618 13619 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13620 PDiag(DiagID) << index.toString(10, true) 13621 << size.toString(10, true) 13622 << (unsigned)size.getLimitedValue(~0U) 13623 << IndexExpr->getSourceRange()); 13624 } else { 13625 unsigned DiagID = diag::warn_array_index_precedes_bounds; 13626 if (!ASE) { 13627 DiagID = diag::warn_ptr_arith_precedes_bounds; 13628 if (index.isNegative()) index = -index; 13629 } 13630 13631 DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr, 13632 PDiag(DiagID) << index.toString(10, true) 13633 << IndexExpr->getSourceRange()); 13634 } 13635 13636 if (!ND) { 13637 // Try harder to find a NamedDecl to point at in the note. 13638 while (const ArraySubscriptExpr *ASE = 13639 dyn_cast<ArraySubscriptExpr>(BaseExpr)) 13640 BaseExpr = ASE->getBase()->IgnoreParenCasts(); 13641 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr)) 13642 ND = DRE->getDecl(); 13643 if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr)) 13644 ND = ME->getMemberDecl(); 13645 } 13646 13647 if (ND) 13648 DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr, 13649 PDiag(diag::note_array_declared_here) 13650 << ND->getDeclName()); 13651 } 13652 13653 void Sema::CheckArrayAccess(const Expr *expr) { 13654 int AllowOnePastEnd = 0; 13655 while (expr) { 13656 expr = expr->IgnoreParenImpCasts(); 13657 switch (expr->getStmtClass()) { 13658 case Stmt::ArraySubscriptExprClass: { 13659 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr); 13660 CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE, 13661 AllowOnePastEnd > 0); 13662 expr = ASE->getBase(); 13663 break; 13664 } 13665 case Stmt::MemberExprClass: { 13666 expr = cast<MemberExpr>(expr)->getBase(); 13667 break; 13668 } 13669 case Stmt::OMPArraySectionExprClass: { 13670 const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr); 13671 if (ASE->getLowerBound()) 13672 CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(), 13673 /*ASE=*/nullptr, AllowOnePastEnd > 0); 13674 return; 13675 } 13676 case Stmt::UnaryOperatorClass: { 13677 // Only unwrap the * and & unary operators 13678 const UnaryOperator *UO = cast<UnaryOperator>(expr); 13679 expr = UO->getSubExpr(); 13680 switch (UO->getOpcode()) { 13681 case UO_AddrOf: 13682 AllowOnePastEnd++; 13683 break; 13684 case UO_Deref: 13685 AllowOnePastEnd--; 13686 break; 13687 default: 13688 return; 13689 } 13690 break; 13691 } 13692 case Stmt::ConditionalOperatorClass: { 13693 const ConditionalOperator *cond = cast<ConditionalOperator>(expr); 13694 if (const Expr *lhs = cond->getLHS()) 13695 CheckArrayAccess(lhs); 13696 if (const Expr *rhs = cond->getRHS()) 13697 CheckArrayAccess(rhs); 13698 return; 13699 } 13700 case Stmt::CXXOperatorCallExprClass: { 13701 const auto *OCE = cast<CXXOperatorCallExpr>(expr); 13702 for (const auto *Arg : OCE->arguments()) 13703 CheckArrayAccess(Arg); 13704 return; 13705 } 13706 default: 13707 return; 13708 } 13709 } 13710 } 13711 13712 //===--- CHECK: Objective-C retain cycles ----------------------------------// 13713 13714 namespace { 13715 13716 struct RetainCycleOwner { 13717 VarDecl *Variable = nullptr; 13718 SourceRange Range; 13719 SourceLocation Loc; 13720 bool Indirect = false; 13721 13722 RetainCycleOwner() = default; 13723 13724 void setLocsFrom(Expr *e) { 13725 Loc = e->getExprLoc(); 13726 Range = e->getSourceRange(); 13727 } 13728 }; 13729 13730 } // namespace 13731 13732 /// Consider whether capturing the given variable can possibly lead to 13733 /// a retain cycle. 13734 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) { 13735 // In ARC, it's captured strongly iff the variable has __strong 13736 // lifetime. In MRR, it's captured strongly if the variable is 13737 // __block and has an appropriate type. 13738 if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13739 return false; 13740 13741 owner.Variable = var; 13742 if (ref) 13743 owner.setLocsFrom(ref); 13744 return true; 13745 } 13746 13747 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) { 13748 while (true) { 13749 e = e->IgnoreParens(); 13750 if (CastExpr *cast = dyn_cast<CastExpr>(e)) { 13751 switch (cast->getCastKind()) { 13752 case CK_BitCast: 13753 case CK_LValueBitCast: 13754 case CK_LValueToRValue: 13755 case CK_ARCReclaimReturnedObject: 13756 e = cast->getSubExpr(); 13757 continue; 13758 13759 default: 13760 return false; 13761 } 13762 } 13763 13764 if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) { 13765 ObjCIvarDecl *ivar = ref->getDecl(); 13766 if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong) 13767 return false; 13768 13769 // Try to find a retain cycle in the base. 13770 if (!findRetainCycleOwner(S, ref->getBase(), owner)) 13771 return false; 13772 13773 if (ref->isFreeIvar()) owner.setLocsFrom(ref); 13774 owner.Indirect = true; 13775 return true; 13776 } 13777 13778 if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) { 13779 VarDecl *var = dyn_cast<VarDecl>(ref->getDecl()); 13780 if (!var) return false; 13781 return considerVariable(var, ref, owner); 13782 } 13783 13784 if (MemberExpr *member = dyn_cast<MemberExpr>(e)) { 13785 if (member->isArrow()) return false; 13786 13787 // Don't count this as an indirect ownership. 13788 e = member->getBase(); 13789 continue; 13790 } 13791 13792 if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) { 13793 // Only pay attention to pseudo-objects on property references. 13794 ObjCPropertyRefExpr *pre 13795 = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm() 13796 ->IgnoreParens()); 13797 if (!pre) return false; 13798 if (pre->isImplicitProperty()) return false; 13799 ObjCPropertyDecl *property = pre->getExplicitProperty(); 13800 if (!property->isRetaining() && 13801 !(property->getPropertyIvarDecl() && 13802 property->getPropertyIvarDecl()->getType() 13803 .getObjCLifetime() == Qualifiers::OCL_Strong)) 13804 return false; 13805 13806 owner.Indirect = true; 13807 if (pre->isSuperReceiver()) { 13808 owner.Variable = S.getCurMethodDecl()->getSelfDecl(); 13809 if (!owner.Variable) 13810 return false; 13811 owner.Loc = pre->getLocation(); 13812 owner.Range = pre->getSourceRange(); 13813 return true; 13814 } 13815 e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase()) 13816 ->getSourceExpr()); 13817 continue; 13818 } 13819 13820 // Array ivars? 13821 13822 return false; 13823 } 13824 } 13825 13826 namespace { 13827 13828 struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> { 13829 ASTContext &Context; 13830 VarDecl *Variable; 13831 Expr *Capturer = nullptr; 13832 bool VarWillBeReased = false; 13833 13834 FindCaptureVisitor(ASTContext &Context, VarDecl *variable) 13835 : EvaluatedExprVisitor<FindCaptureVisitor>(Context), 13836 Context(Context), Variable(variable) {} 13837 13838 void VisitDeclRefExpr(DeclRefExpr *ref) { 13839 if (ref->getDecl() == Variable && !Capturer) 13840 Capturer = ref; 13841 } 13842 13843 void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) { 13844 if (Capturer) return; 13845 Visit(ref->getBase()); 13846 if (Capturer && ref->isFreeIvar()) 13847 Capturer = ref; 13848 } 13849 13850 void VisitBlockExpr(BlockExpr *block) { 13851 // Look inside nested blocks 13852 if (block->getBlockDecl()->capturesVariable(Variable)) 13853 Visit(block->getBlockDecl()->getBody()); 13854 } 13855 13856 void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) { 13857 if (Capturer) return; 13858 if (OVE->getSourceExpr()) 13859 Visit(OVE->getSourceExpr()); 13860 } 13861 13862 void VisitBinaryOperator(BinaryOperator *BinOp) { 13863 if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign) 13864 return; 13865 Expr *LHS = BinOp->getLHS(); 13866 if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) { 13867 if (DRE->getDecl() != Variable) 13868 return; 13869 if (Expr *RHS = BinOp->getRHS()) { 13870 RHS = RHS->IgnoreParenCasts(); 13871 llvm::APSInt Value; 13872 VarWillBeReased = 13873 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0); 13874 } 13875 } 13876 } 13877 }; 13878 13879 } // namespace 13880 13881 /// Check whether the given argument is a block which captures a 13882 /// variable. 13883 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) { 13884 assert(owner.Variable && owner.Loc.isValid()); 13885 13886 e = e->IgnoreParenCasts(); 13887 13888 // Look through [^{...} copy] and Block_copy(^{...}). 13889 if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) { 13890 Selector Cmd = ME->getSelector(); 13891 if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") { 13892 e = ME->getInstanceReceiver(); 13893 if (!e) 13894 return nullptr; 13895 e = e->IgnoreParenCasts(); 13896 } 13897 } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) { 13898 if (CE->getNumArgs() == 1) { 13899 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl()); 13900 if (Fn) { 13901 const IdentifierInfo *FnI = Fn->getIdentifier(); 13902 if (FnI && FnI->isStr("_Block_copy")) { 13903 e = CE->getArg(0)->IgnoreParenCasts(); 13904 } 13905 } 13906 } 13907 } 13908 13909 BlockExpr *block = dyn_cast<BlockExpr>(e); 13910 if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable)) 13911 return nullptr; 13912 13913 FindCaptureVisitor visitor(S.Context, owner.Variable); 13914 visitor.Visit(block->getBlockDecl()->getBody()); 13915 return visitor.VarWillBeReased ? nullptr : visitor.Capturer; 13916 } 13917 13918 static void diagnoseRetainCycle(Sema &S, Expr *capturer, 13919 RetainCycleOwner &owner) { 13920 assert(capturer); 13921 assert(owner.Variable && owner.Loc.isValid()); 13922 13923 S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle) 13924 << owner.Variable << capturer->getSourceRange(); 13925 S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner) 13926 << owner.Indirect << owner.Range; 13927 } 13928 13929 /// Check for a keyword selector that starts with the word 'add' or 13930 /// 'set'. 13931 static bool isSetterLikeSelector(Selector sel) { 13932 if (sel.isUnarySelector()) return false; 13933 13934 StringRef str = sel.getNameForSlot(0); 13935 while (!str.empty() && str.front() == '_') str = str.substr(1); 13936 if (str.startswith("set")) 13937 str = str.substr(3); 13938 else if (str.startswith("add")) { 13939 // Specially whitelist 'addOperationWithBlock:'. 13940 if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock")) 13941 return false; 13942 str = str.substr(3); 13943 } 13944 else 13945 return false; 13946 13947 if (str.empty()) return true; 13948 return !isLowercase(str.front()); 13949 } 13950 13951 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S, 13952 ObjCMessageExpr *Message) { 13953 bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass( 13954 Message->getReceiverInterface(), 13955 NSAPI::ClassId_NSMutableArray); 13956 if (!IsMutableArray) { 13957 return None; 13958 } 13959 13960 Selector Sel = Message->getSelector(); 13961 13962 Optional<NSAPI::NSArrayMethodKind> MKOpt = 13963 S.NSAPIObj->getNSArrayMethodKind(Sel); 13964 if (!MKOpt) { 13965 return None; 13966 } 13967 13968 NSAPI::NSArrayMethodKind MK = *MKOpt; 13969 13970 switch (MK) { 13971 case NSAPI::NSMutableArr_addObject: 13972 case NSAPI::NSMutableArr_insertObjectAtIndex: 13973 case NSAPI::NSMutableArr_setObjectAtIndexedSubscript: 13974 return 0; 13975 case NSAPI::NSMutableArr_replaceObjectAtIndex: 13976 return 1; 13977 13978 default: 13979 return None; 13980 } 13981 13982 return None; 13983 } 13984 13985 static 13986 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S, 13987 ObjCMessageExpr *Message) { 13988 bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass( 13989 Message->getReceiverInterface(), 13990 NSAPI::ClassId_NSMutableDictionary); 13991 if (!IsMutableDictionary) { 13992 return None; 13993 } 13994 13995 Selector Sel = Message->getSelector(); 13996 13997 Optional<NSAPI::NSDictionaryMethodKind> MKOpt = 13998 S.NSAPIObj->getNSDictionaryMethodKind(Sel); 13999 if (!MKOpt) { 14000 return None; 14001 } 14002 14003 NSAPI::NSDictionaryMethodKind MK = *MKOpt; 14004 14005 switch (MK) { 14006 case NSAPI::NSMutableDict_setObjectForKey: 14007 case NSAPI::NSMutableDict_setValueForKey: 14008 case NSAPI::NSMutableDict_setObjectForKeyedSubscript: 14009 return 0; 14010 14011 default: 14012 return None; 14013 } 14014 14015 return None; 14016 } 14017 14018 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) { 14019 bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass( 14020 Message->getReceiverInterface(), 14021 NSAPI::ClassId_NSMutableSet); 14022 14023 bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass( 14024 Message->getReceiverInterface(), 14025 NSAPI::ClassId_NSMutableOrderedSet); 14026 if (!IsMutableSet && !IsMutableOrderedSet) { 14027 return None; 14028 } 14029 14030 Selector Sel = Message->getSelector(); 14031 14032 Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel); 14033 if (!MKOpt) { 14034 return None; 14035 } 14036 14037 NSAPI::NSSetMethodKind MK = *MKOpt; 14038 14039 switch (MK) { 14040 case NSAPI::NSMutableSet_addObject: 14041 case NSAPI::NSOrderedSet_setObjectAtIndex: 14042 case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript: 14043 case NSAPI::NSOrderedSet_insertObjectAtIndex: 14044 return 0; 14045 case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject: 14046 return 1; 14047 } 14048 14049 return None; 14050 } 14051 14052 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) { 14053 if (!Message->isInstanceMessage()) { 14054 return; 14055 } 14056 14057 Optional<int> ArgOpt; 14058 14059 if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) && 14060 !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) && 14061 !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) { 14062 return; 14063 } 14064 14065 int ArgIndex = *ArgOpt; 14066 14067 Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts(); 14068 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) { 14069 Arg = OE->getSourceExpr()->IgnoreImpCasts(); 14070 } 14071 14072 if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) { 14073 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14074 if (ArgRE->isObjCSelfExpr()) { 14075 Diag(Message->getSourceRange().getBegin(), 14076 diag::warn_objc_circular_container) 14077 << ArgRE->getDecl() << StringRef("'super'"); 14078 } 14079 } 14080 } else { 14081 Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts(); 14082 14083 if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) { 14084 Receiver = OE->getSourceExpr()->IgnoreImpCasts(); 14085 } 14086 14087 if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) { 14088 if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) { 14089 if (ReceiverRE->getDecl() == ArgRE->getDecl()) { 14090 ValueDecl *Decl = ReceiverRE->getDecl(); 14091 Diag(Message->getSourceRange().getBegin(), 14092 diag::warn_objc_circular_container) 14093 << Decl << Decl; 14094 if (!ArgRE->isObjCSelfExpr()) { 14095 Diag(Decl->getLocation(), 14096 diag::note_objc_circular_container_declared_here) 14097 << Decl; 14098 } 14099 } 14100 } 14101 } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) { 14102 if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) { 14103 if (IvarRE->getDecl() == IvarArgRE->getDecl()) { 14104 ObjCIvarDecl *Decl = IvarRE->getDecl(); 14105 Diag(Message->getSourceRange().getBegin(), 14106 diag::warn_objc_circular_container) 14107 << Decl << Decl; 14108 Diag(Decl->getLocation(), 14109 diag::note_objc_circular_container_declared_here) 14110 << Decl; 14111 } 14112 } 14113 } 14114 } 14115 } 14116 14117 /// Check a message send to see if it's likely to cause a retain cycle. 14118 void Sema::checkRetainCycles(ObjCMessageExpr *msg) { 14119 // Only check instance methods whose selector looks like a setter. 14120 if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector())) 14121 return; 14122 14123 // Try to find a variable that the receiver is strongly owned by. 14124 RetainCycleOwner owner; 14125 if (msg->getReceiverKind() == ObjCMessageExpr::Instance) { 14126 if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner)) 14127 return; 14128 } else { 14129 assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance); 14130 owner.Variable = getCurMethodDecl()->getSelfDecl(); 14131 owner.Loc = msg->getSuperLoc(); 14132 owner.Range = msg->getSuperLoc(); 14133 } 14134 14135 // Check whether the receiver is captured by any of the arguments. 14136 const ObjCMethodDecl *MD = msg->getMethodDecl(); 14137 for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) { 14138 if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) { 14139 // noescape blocks should not be retained by the method. 14140 if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>()) 14141 continue; 14142 return diagnoseRetainCycle(*this, capturer, owner); 14143 } 14144 } 14145 } 14146 14147 /// Check a property assign to see if it's likely to cause a retain cycle. 14148 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) { 14149 RetainCycleOwner owner; 14150 if (!findRetainCycleOwner(*this, receiver, owner)) 14151 return; 14152 14153 if (Expr *capturer = findCapturingExpr(*this, argument, owner)) 14154 diagnoseRetainCycle(*this, capturer, owner); 14155 } 14156 14157 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) { 14158 RetainCycleOwner Owner; 14159 if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner)) 14160 return; 14161 14162 // Because we don't have an expression for the variable, we have to set the 14163 // location explicitly here. 14164 Owner.Loc = Var->getLocation(); 14165 Owner.Range = Var->getSourceRange(); 14166 14167 if (Expr *Capturer = findCapturingExpr(*this, Init, Owner)) 14168 diagnoseRetainCycle(*this, Capturer, Owner); 14169 } 14170 14171 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, 14172 Expr *RHS, bool isProperty) { 14173 // Check if RHS is an Objective-C object literal, which also can get 14174 // immediately zapped in a weak reference. Note that we explicitly 14175 // allow ObjCStringLiterals, since those are designed to never really die. 14176 RHS = RHS->IgnoreParenImpCasts(); 14177 14178 // This enum needs to match with the 'select' in 14179 // warn_objc_arc_literal_assign (off-by-1). 14180 Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS); 14181 if (Kind == Sema::LK_String || Kind == Sema::LK_None) 14182 return false; 14183 14184 S.Diag(Loc, diag::warn_arc_literal_assign) 14185 << (unsigned) Kind 14186 << (isProperty ? 0 : 1) 14187 << RHS->getSourceRange(); 14188 14189 return true; 14190 } 14191 14192 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, 14193 Qualifiers::ObjCLifetime LT, 14194 Expr *RHS, bool isProperty) { 14195 // Strip off any implicit cast added to get to the one ARC-specific. 14196 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14197 if (cast->getCastKind() == CK_ARCConsumeObject) { 14198 S.Diag(Loc, diag::warn_arc_retained_assign) 14199 << (LT == Qualifiers::OCL_ExplicitNone) 14200 << (isProperty ? 0 : 1) 14201 << RHS->getSourceRange(); 14202 return true; 14203 } 14204 RHS = cast->getSubExpr(); 14205 } 14206 14207 if (LT == Qualifiers::OCL_Weak && 14208 checkUnsafeAssignLiteral(S, Loc, RHS, isProperty)) 14209 return true; 14210 14211 return false; 14212 } 14213 14214 bool Sema::checkUnsafeAssigns(SourceLocation Loc, 14215 QualType LHS, Expr *RHS) { 14216 Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime(); 14217 14218 if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone) 14219 return false; 14220 14221 if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false)) 14222 return true; 14223 14224 return false; 14225 } 14226 14227 void Sema::checkUnsafeExprAssigns(SourceLocation Loc, 14228 Expr *LHS, Expr *RHS) { 14229 QualType LHSType; 14230 // PropertyRef on LHS type need be directly obtained from 14231 // its declaration as it has a PseudoType. 14232 ObjCPropertyRefExpr *PRE 14233 = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens()); 14234 if (PRE && !PRE->isImplicitProperty()) { 14235 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14236 if (PD) 14237 LHSType = PD->getType(); 14238 } 14239 14240 if (LHSType.isNull()) 14241 LHSType = LHS->getType(); 14242 14243 Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime(); 14244 14245 if (LT == Qualifiers::OCL_Weak) { 14246 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc)) 14247 getCurFunction()->markSafeWeakUse(LHS); 14248 } 14249 14250 if (checkUnsafeAssigns(Loc, LHSType, RHS)) 14251 return; 14252 14253 // FIXME. Check for other life times. 14254 if (LT != Qualifiers::OCL_None) 14255 return; 14256 14257 if (PRE) { 14258 if (PRE->isImplicitProperty()) 14259 return; 14260 const ObjCPropertyDecl *PD = PRE->getExplicitProperty(); 14261 if (!PD) 14262 return; 14263 14264 unsigned Attributes = PD->getPropertyAttributes(); 14265 if (Attributes & ObjCPropertyAttribute::kind_assign) { 14266 // when 'assign' attribute was not explicitly specified 14267 // by user, ignore it and rely on property type itself 14268 // for lifetime info. 14269 unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten(); 14270 if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) && 14271 LHSType->isObjCRetainableType()) 14272 return; 14273 14274 while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) { 14275 if (cast->getCastKind() == CK_ARCConsumeObject) { 14276 Diag(Loc, diag::warn_arc_retained_property_assign) 14277 << RHS->getSourceRange(); 14278 return; 14279 } 14280 RHS = cast->getSubExpr(); 14281 } 14282 } else if (Attributes & ObjCPropertyAttribute::kind_weak) { 14283 if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true)) 14284 return; 14285 } 14286 } 14287 } 14288 14289 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===// 14290 14291 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, 14292 SourceLocation StmtLoc, 14293 const NullStmt *Body) { 14294 // Do not warn if the body is a macro that expands to nothing, e.g: 14295 // 14296 // #define CALL(x) 14297 // if (condition) 14298 // CALL(0); 14299 if (Body->hasLeadingEmptyMacro()) 14300 return false; 14301 14302 // Get line numbers of statement and body. 14303 bool StmtLineInvalid; 14304 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc, 14305 &StmtLineInvalid); 14306 if (StmtLineInvalid) 14307 return false; 14308 14309 bool BodyLineInvalid; 14310 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(), 14311 &BodyLineInvalid); 14312 if (BodyLineInvalid) 14313 return false; 14314 14315 // Warn if null statement and body are on the same line. 14316 if (StmtLine != BodyLine) 14317 return false; 14318 14319 return true; 14320 } 14321 14322 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc, 14323 const Stmt *Body, 14324 unsigned DiagID) { 14325 // Since this is a syntactic check, don't emit diagnostic for template 14326 // instantiations, this just adds noise. 14327 if (CurrentInstantiationScope) 14328 return; 14329 14330 // The body should be a null statement. 14331 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14332 if (!NBody) 14333 return; 14334 14335 // Do the usual checks. 14336 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14337 return; 14338 14339 Diag(NBody->getSemiLoc(), DiagID); 14340 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14341 } 14342 14343 void Sema::DiagnoseEmptyLoopBody(const Stmt *S, 14344 const Stmt *PossibleBody) { 14345 assert(!CurrentInstantiationScope); // Ensured by caller 14346 14347 SourceLocation StmtLoc; 14348 const Stmt *Body; 14349 unsigned DiagID; 14350 if (const ForStmt *FS = dyn_cast<ForStmt>(S)) { 14351 StmtLoc = FS->getRParenLoc(); 14352 Body = FS->getBody(); 14353 DiagID = diag::warn_empty_for_body; 14354 } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) { 14355 StmtLoc = WS->getCond()->getSourceRange().getEnd(); 14356 Body = WS->getBody(); 14357 DiagID = diag::warn_empty_while_body; 14358 } else 14359 return; // Neither `for' nor `while'. 14360 14361 // The body should be a null statement. 14362 const NullStmt *NBody = dyn_cast<NullStmt>(Body); 14363 if (!NBody) 14364 return; 14365 14366 // Skip expensive checks if diagnostic is disabled. 14367 if (Diags.isIgnored(DiagID, NBody->getSemiLoc())) 14368 return; 14369 14370 // Do the usual checks. 14371 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody)) 14372 return; 14373 14374 // `for(...);' and `while(...);' are popular idioms, so in order to keep 14375 // noise level low, emit diagnostics only if for/while is followed by a 14376 // CompoundStmt, e.g.: 14377 // for (int i = 0; i < n; i++); 14378 // { 14379 // a(i); 14380 // } 14381 // or if for/while is followed by a statement with more indentation 14382 // than for/while itself: 14383 // for (int i = 0; i < n; i++); 14384 // a(i); 14385 bool ProbableTypo = isa<CompoundStmt>(PossibleBody); 14386 if (!ProbableTypo) { 14387 bool BodyColInvalid; 14388 unsigned BodyCol = SourceMgr.getPresumedColumnNumber( 14389 PossibleBody->getBeginLoc(), &BodyColInvalid); 14390 if (BodyColInvalid) 14391 return; 14392 14393 bool StmtColInvalid; 14394 unsigned StmtCol = 14395 SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid); 14396 if (StmtColInvalid) 14397 return; 14398 14399 if (BodyCol > StmtCol) 14400 ProbableTypo = true; 14401 } 14402 14403 if (ProbableTypo) { 14404 Diag(NBody->getSemiLoc(), DiagID); 14405 Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line); 14406 } 14407 } 14408 14409 //===--- CHECK: Warn on self move with std::move. -------------------------===// 14410 14411 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself. 14412 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, 14413 SourceLocation OpLoc) { 14414 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc)) 14415 return; 14416 14417 if (inTemplateInstantiation()) 14418 return; 14419 14420 // Strip parens and casts away. 14421 LHSExpr = LHSExpr->IgnoreParenImpCasts(); 14422 RHSExpr = RHSExpr->IgnoreParenImpCasts(); 14423 14424 // Check for a call expression 14425 const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr); 14426 if (!CE || CE->getNumArgs() != 1) 14427 return; 14428 14429 // Check for a call to std::move 14430 if (!CE->isCallToStdMove()) 14431 return; 14432 14433 // Get argument from std::move 14434 RHSExpr = CE->getArg(0); 14435 14436 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr); 14437 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr); 14438 14439 // Two DeclRefExpr's, check that the decls are the same. 14440 if (LHSDeclRef && RHSDeclRef) { 14441 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14442 return; 14443 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14444 RHSDeclRef->getDecl()->getCanonicalDecl()) 14445 return; 14446 14447 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14448 << LHSExpr->getSourceRange() 14449 << RHSExpr->getSourceRange(); 14450 return; 14451 } 14452 14453 // Member variables require a different approach to check for self moves. 14454 // MemberExpr's are the same if every nested MemberExpr refers to the same 14455 // Decl and that the base Expr's are DeclRefExpr's with the same Decl or 14456 // the base Expr's are CXXThisExpr's. 14457 const Expr *LHSBase = LHSExpr; 14458 const Expr *RHSBase = RHSExpr; 14459 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr); 14460 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr); 14461 if (!LHSME || !RHSME) 14462 return; 14463 14464 while (LHSME && RHSME) { 14465 if (LHSME->getMemberDecl()->getCanonicalDecl() != 14466 RHSME->getMemberDecl()->getCanonicalDecl()) 14467 return; 14468 14469 LHSBase = LHSME->getBase(); 14470 RHSBase = RHSME->getBase(); 14471 LHSME = dyn_cast<MemberExpr>(LHSBase); 14472 RHSME = dyn_cast<MemberExpr>(RHSBase); 14473 } 14474 14475 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase); 14476 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase); 14477 if (LHSDeclRef && RHSDeclRef) { 14478 if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl()) 14479 return; 14480 if (LHSDeclRef->getDecl()->getCanonicalDecl() != 14481 RHSDeclRef->getDecl()->getCanonicalDecl()) 14482 return; 14483 14484 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14485 << LHSExpr->getSourceRange() 14486 << RHSExpr->getSourceRange(); 14487 return; 14488 } 14489 14490 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase)) 14491 Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType() 14492 << LHSExpr->getSourceRange() 14493 << RHSExpr->getSourceRange(); 14494 } 14495 14496 //===--- Layout compatibility ----------------------------------------------// 14497 14498 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2); 14499 14500 /// Check if two enumeration types are layout-compatible. 14501 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) { 14502 // C++11 [dcl.enum] p8: 14503 // Two enumeration types are layout-compatible if they have the same 14504 // underlying type. 14505 return ED1->isComplete() && ED2->isComplete() && 14506 C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType()); 14507 } 14508 14509 /// Check if two fields are layout-compatible. 14510 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1, 14511 FieldDecl *Field2) { 14512 if (!isLayoutCompatible(C, Field1->getType(), Field2->getType())) 14513 return false; 14514 14515 if (Field1->isBitField() != Field2->isBitField()) 14516 return false; 14517 14518 if (Field1->isBitField()) { 14519 // Make sure that the bit-fields are the same length. 14520 unsigned Bits1 = Field1->getBitWidthValue(C); 14521 unsigned Bits2 = Field2->getBitWidthValue(C); 14522 14523 if (Bits1 != Bits2) 14524 return false; 14525 } 14526 14527 return true; 14528 } 14529 14530 /// Check if two standard-layout structs are layout-compatible. 14531 /// (C++11 [class.mem] p17) 14532 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1, 14533 RecordDecl *RD2) { 14534 // If both records are C++ classes, check that base classes match. 14535 if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) { 14536 // If one of records is a CXXRecordDecl we are in C++ mode, 14537 // thus the other one is a CXXRecordDecl, too. 14538 const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2); 14539 // Check number of base classes. 14540 if (D1CXX->getNumBases() != D2CXX->getNumBases()) 14541 return false; 14542 14543 // Check the base classes. 14544 for (CXXRecordDecl::base_class_const_iterator 14545 Base1 = D1CXX->bases_begin(), 14546 BaseEnd1 = D1CXX->bases_end(), 14547 Base2 = D2CXX->bases_begin(); 14548 Base1 != BaseEnd1; 14549 ++Base1, ++Base2) { 14550 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType())) 14551 return false; 14552 } 14553 } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) { 14554 // If only RD2 is a C++ class, it should have zero base classes. 14555 if (D2CXX->getNumBases() > 0) 14556 return false; 14557 } 14558 14559 // Check the fields. 14560 RecordDecl::field_iterator Field2 = RD2->field_begin(), 14561 Field2End = RD2->field_end(), 14562 Field1 = RD1->field_begin(), 14563 Field1End = RD1->field_end(); 14564 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) { 14565 if (!isLayoutCompatible(C, *Field1, *Field2)) 14566 return false; 14567 } 14568 if (Field1 != Field1End || Field2 != Field2End) 14569 return false; 14570 14571 return true; 14572 } 14573 14574 /// Check if two standard-layout unions are layout-compatible. 14575 /// (C++11 [class.mem] p18) 14576 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1, 14577 RecordDecl *RD2) { 14578 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields; 14579 for (auto *Field2 : RD2->fields()) 14580 UnmatchedFields.insert(Field2); 14581 14582 for (auto *Field1 : RD1->fields()) { 14583 llvm::SmallPtrSet<FieldDecl *, 8>::iterator 14584 I = UnmatchedFields.begin(), 14585 E = UnmatchedFields.end(); 14586 14587 for ( ; I != E; ++I) { 14588 if (isLayoutCompatible(C, Field1, *I)) { 14589 bool Result = UnmatchedFields.erase(*I); 14590 (void) Result; 14591 assert(Result); 14592 break; 14593 } 14594 } 14595 if (I == E) 14596 return false; 14597 } 14598 14599 return UnmatchedFields.empty(); 14600 } 14601 14602 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1, 14603 RecordDecl *RD2) { 14604 if (RD1->isUnion() != RD2->isUnion()) 14605 return false; 14606 14607 if (RD1->isUnion()) 14608 return isLayoutCompatibleUnion(C, RD1, RD2); 14609 else 14610 return isLayoutCompatibleStruct(C, RD1, RD2); 14611 } 14612 14613 /// Check if two types are layout-compatible in C++11 sense. 14614 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) { 14615 if (T1.isNull() || T2.isNull()) 14616 return false; 14617 14618 // C++11 [basic.types] p11: 14619 // If two types T1 and T2 are the same type, then T1 and T2 are 14620 // layout-compatible types. 14621 if (C.hasSameType(T1, T2)) 14622 return true; 14623 14624 T1 = T1.getCanonicalType().getUnqualifiedType(); 14625 T2 = T2.getCanonicalType().getUnqualifiedType(); 14626 14627 const Type::TypeClass TC1 = T1->getTypeClass(); 14628 const Type::TypeClass TC2 = T2->getTypeClass(); 14629 14630 if (TC1 != TC2) 14631 return false; 14632 14633 if (TC1 == Type::Enum) { 14634 return isLayoutCompatible(C, 14635 cast<EnumType>(T1)->getDecl(), 14636 cast<EnumType>(T2)->getDecl()); 14637 } else if (TC1 == Type::Record) { 14638 if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType()) 14639 return false; 14640 14641 return isLayoutCompatible(C, 14642 cast<RecordType>(T1)->getDecl(), 14643 cast<RecordType>(T2)->getDecl()); 14644 } 14645 14646 return false; 14647 } 14648 14649 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----// 14650 14651 /// Given a type tag expression find the type tag itself. 14652 /// 14653 /// \param TypeExpr Type tag expression, as it appears in user's code. 14654 /// 14655 /// \param VD Declaration of an identifier that appears in a type tag. 14656 /// 14657 /// \param MagicValue Type tag magic value. 14658 /// 14659 /// \param isConstantEvaluated wether the evalaution should be performed in 14660 14661 /// constant context. 14662 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, 14663 const ValueDecl **VD, uint64_t *MagicValue, 14664 bool isConstantEvaluated) { 14665 while(true) { 14666 if (!TypeExpr) 14667 return false; 14668 14669 TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts(); 14670 14671 switch (TypeExpr->getStmtClass()) { 14672 case Stmt::UnaryOperatorClass: { 14673 const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr); 14674 if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) { 14675 TypeExpr = UO->getSubExpr(); 14676 continue; 14677 } 14678 return false; 14679 } 14680 14681 case Stmt::DeclRefExprClass: { 14682 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr); 14683 *VD = DRE->getDecl(); 14684 return true; 14685 } 14686 14687 case Stmt::IntegerLiteralClass: { 14688 const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr); 14689 llvm::APInt MagicValueAPInt = IL->getValue(); 14690 if (MagicValueAPInt.getActiveBits() <= 64) { 14691 *MagicValue = MagicValueAPInt.getZExtValue(); 14692 return true; 14693 } else 14694 return false; 14695 } 14696 14697 case Stmt::BinaryConditionalOperatorClass: 14698 case Stmt::ConditionalOperatorClass: { 14699 const AbstractConditionalOperator *ACO = 14700 cast<AbstractConditionalOperator>(TypeExpr); 14701 bool Result; 14702 if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx, 14703 isConstantEvaluated)) { 14704 if (Result) 14705 TypeExpr = ACO->getTrueExpr(); 14706 else 14707 TypeExpr = ACO->getFalseExpr(); 14708 continue; 14709 } 14710 return false; 14711 } 14712 14713 case Stmt::BinaryOperatorClass: { 14714 const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr); 14715 if (BO->getOpcode() == BO_Comma) { 14716 TypeExpr = BO->getRHS(); 14717 continue; 14718 } 14719 return false; 14720 } 14721 14722 default: 14723 return false; 14724 } 14725 } 14726 } 14727 14728 /// Retrieve the C type corresponding to type tag TypeExpr. 14729 /// 14730 /// \param TypeExpr Expression that specifies a type tag. 14731 /// 14732 /// \param MagicValues Registered magic values. 14733 /// 14734 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong 14735 /// kind. 14736 /// 14737 /// \param TypeInfo Information about the corresponding C type. 14738 /// 14739 /// \param isConstantEvaluated wether the evalaution should be performed in 14740 /// constant context. 14741 /// 14742 /// \returns true if the corresponding C type was found. 14743 static bool GetMatchingCType( 14744 const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, 14745 const ASTContext &Ctx, 14746 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData> 14747 *MagicValues, 14748 bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, 14749 bool isConstantEvaluated) { 14750 FoundWrongKind = false; 14751 14752 // Variable declaration that has type_tag_for_datatype attribute. 14753 const ValueDecl *VD = nullptr; 14754 14755 uint64_t MagicValue; 14756 14757 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated)) 14758 return false; 14759 14760 if (VD) { 14761 if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) { 14762 if (I->getArgumentKind() != ArgumentKind) { 14763 FoundWrongKind = true; 14764 return false; 14765 } 14766 TypeInfo.Type = I->getMatchingCType(); 14767 TypeInfo.LayoutCompatible = I->getLayoutCompatible(); 14768 TypeInfo.MustBeNull = I->getMustBeNull(); 14769 return true; 14770 } 14771 return false; 14772 } 14773 14774 if (!MagicValues) 14775 return false; 14776 14777 llvm::DenseMap<Sema::TypeTagMagicValue, 14778 Sema::TypeTagData>::const_iterator I = 14779 MagicValues->find(std::make_pair(ArgumentKind, MagicValue)); 14780 if (I == MagicValues->end()) 14781 return false; 14782 14783 TypeInfo = I->second; 14784 return true; 14785 } 14786 14787 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, 14788 uint64_t MagicValue, QualType Type, 14789 bool LayoutCompatible, 14790 bool MustBeNull) { 14791 if (!TypeTagForDatatypeMagicValues) 14792 TypeTagForDatatypeMagicValues.reset( 14793 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>); 14794 14795 TypeTagMagicValue Magic(ArgumentKind, MagicValue); 14796 (*TypeTagForDatatypeMagicValues)[Magic] = 14797 TypeTagData(Type, LayoutCompatible, MustBeNull); 14798 } 14799 14800 static bool IsSameCharType(QualType T1, QualType T2) { 14801 const BuiltinType *BT1 = T1->getAs<BuiltinType>(); 14802 if (!BT1) 14803 return false; 14804 14805 const BuiltinType *BT2 = T2->getAs<BuiltinType>(); 14806 if (!BT2) 14807 return false; 14808 14809 BuiltinType::Kind T1Kind = BT1->getKind(); 14810 BuiltinType::Kind T2Kind = BT2->getKind(); 14811 14812 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) || 14813 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) || 14814 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) || 14815 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar); 14816 } 14817 14818 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, 14819 const ArrayRef<const Expr *> ExprArgs, 14820 SourceLocation CallSiteLoc) { 14821 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind(); 14822 bool IsPointerAttr = Attr->getIsPointer(); 14823 14824 // Retrieve the argument representing the 'type_tag'. 14825 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex(); 14826 if (TypeTagIdxAST >= ExprArgs.size()) { 14827 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14828 << 0 << Attr->getTypeTagIdx().getSourceIndex(); 14829 return; 14830 } 14831 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST]; 14832 bool FoundWrongKind; 14833 TypeTagData TypeInfo; 14834 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context, 14835 TypeTagForDatatypeMagicValues.get(), FoundWrongKind, 14836 TypeInfo, isConstantEvaluated())) { 14837 if (FoundWrongKind) 14838 Diag(TypeTagExpr->getExprLoc(), 14839 diag::warn_type_tag_for_datatype_wrong_kind) 14840 << TypeTagExpr->getSourceRange(); 14841 return; 14842 } 14843 14844 // Retrieve the argument representing the 'arg_idx'. 14845 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex(); 14846 if (ArgumentIdxAST >= ExprArgs.size()) { 14847 Diag(CallSiteLoc, diag::err_tag_index_out_of_range) 14848 << 1 << Attr->getArgumentIdx().getSourceIndex(); 14849 return; 14850 } 14851 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST]; 14852 if (IsPointerAttr) { 14853 // Skip implicit cast of pointer to `void *' (as a function argument). 14854 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr)) 14855 if (ICE->getType()->isVoidPointerType() && 14856 ICE->getCastKind() == CK_BitCast) 14857 ArgumentExpr = ICE->getSubExpr(); 14858 } 14859 QualType ArgumentType = ArgumentExpr->getType(); 14860 14861 // Passing a `void*' pointer shouldn't trigger a warning. 14862 if (IsPointerAttr && ArgumentType->isVoidPointerType()) 14863 return; 14864 14865 if (TypeInfo.MustBeNull) { 14866 // Type tag with matching void type requires a null pointer. 14867 if (!ArgumentExpr->isNullPointerConstant(Context, 14868 Expr::NPC_ValueDependentIsNotNull)) { 14869 Diag(ArgumentExpr->getExprLoc(), 14870 diag::warn_type_safety_null_pointer_required) 14871 << ArgumentKind->getName() 14872 << ArgumentExpr->getSourceRange() 14873 << TypeTagExpr->getSourceRange(); 14874 } 14875 return; 14876 } 14877 14878 QualType RequiredType = TypeInfo.Type; 14879 if (IsPointerAttr) 14880 RequiredType = Context.getPointerType(RequiredType); 14881 14882 bool mismatch = false; 14883 if (!TypeInfo.LayoutCompatible) { 14884 mismatch = !Context.hasSameType(ArgumentType, RequiredType); 14885 14886 // C++11 [basic.fundamental] p1: 14887 // Plain char, signed char, and unsigned char are three distinct types. 14888 // 14889 // But we treat plain `char' as equivalent to `signed char' or `unsigned 14890 // char' depending on the current char signedness mode. 14891 if (mismatch) 14892 if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(), 14893 RequiredType->getPointeeType())) || 14894 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType))) 14895 mismatch = false; 14896 } else 14897 if (IsPointerAttr) 14898 mismatch = !isLayoutCompatible(Context, 14899 ArgumentType->getPointeeType(), 14900 RequiredType->getPointeeType()); 14901 else 14902 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType); 14903 14904 if (mismatch) 14905 Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch) 14906 << ArgumentType << ArgumentKind 14907 << TypeInfo.LayoutCompatible << RequiredType 14908 << ArgumentExpr->getSourceRange() 14909 << TypeTagExpr->getSourceRange(); 14910 } 14911 14912 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, 14913 CharUnits Alignment) { 14914 MisalignedMembers.emplace_back(E, RD, MD, Alignment); 14915 } 14916 14917 void Sema::DiagnoseMisalignedMembers() { 14918 for (MisalignedMember &m : MisalignedMembers) { 14919 const NamedDecl *ND = m.RD; 14920 if (ND->getName().empty()) { 14921 if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl()) 14922 ND = TD; 14923 } 14924 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member) 14925 << m.MD << ND << m.E->getSourceRange(); 14926 } 14927 MisalignedMembers.clear(); 14928 } 14929 14930 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) { 14931 E = E->IgnoreParens(); 14932 if (!T->isPointerType() && !T->isIntegerType()) 14933 return; 14934 if (isa<UnaryOperator>(E) && 14935 cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) { 14936 auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens(); 14937 if (isa<MemberExpr>(Op)) { 14938 auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op)); 14939 if (MA != MisalignedMembers.end() && 14940 (T->isIntegerType() || 14941 (T->isPointerType() && (T->getPointeeType()->isIncompleteType() || 14942 Context.getTypeAlignInChars( 14943 T->getPointeeType()) <= MA->Alignment)))) 14944 MisalignedMembers.erase(MA); 14945 } 14946 } 14947 } 14948 14949 void Sema::RefersToMemberWithReducedAlignment( 14950 Expr *E, 14951 llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> 14952 Action) { 14953 const auto *ME = dyn_cast<MemberExpr>(E); 14954 if (!ME) 14955 return; 14956 14957 // No need to check expressions with an __unaligned-qualified type. 14958 if (E->getType().getQualifiers().hasUnaligned()) 14959 return; 14960 14961 // For a chain of MemberExpr like "a.b.c.d" this list 14962 // will keep FieldDecl's like [d, c, b]. 14963 SmallVector<FieldDecl *, 4> ReverseMemberChain; 14964 const MemberExpr *TopME = nullptr; 14965 bool AnyIsPacked = false; 14966 do { 14967 QualType BaseType = ME->getBase()->getType(); 14968 if (BaseType->isDependentType()) 14969 return; 14970 if (ME->isArrow()) 14971 BaseType = BaseType->getPointeeType(); 14972 RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl(); 14973 if (RD->isInvalidDecl()) 14974 return; 14975 14976 ValueDecl *MD = ME->getMemberDecl(); 14977 auto *FD = dyn_cast<FieldDecl>(MD); 14978 // We do not care about non-data members. 14979 if (!FD || FD->isInvalidDecl()) 14980 return; 14981 14982 AnyIsPacked = 14983 AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>()); 14984 ReverseMemberChain.push_back(FD); 14985 14986 TopME = ME; 14987 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens()); 14988 } while (ME); 14989 assert(TopME && "We did not compute a topmost MemberExpr!"); 14990 14991 // Not the scope of this diagnostic. 14992 if (!AnyIsPacked) 14993 return; 14994 14995 const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts(); 14996 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase); 14997 // TODO: The innermost base of the member expression may be too complicated. 14998 // For now, just disregard these cases. This is left for future 14999 // improvement. 15000 if (!DRE && !isa<CXXThisExpr>(TopBase)) 15001 return; 15002 15003 // Alignment expected by the whole expression. 15004 CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType()); 15005 15006 // No need to do anything else with this case. 15007 if (ExpectedAlignment.isOne()) 15008 return; 15009 15010 // Synthesize offset of the whole access. 15011 CharUnits Offset; 15012 for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend(); 15013 I++) { 15014 Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I)); 15015 } 15016 15017 // Compute the CompleteObjectAlignment as the alignment of the whole chain. 15018 CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars( 15019 ReverseMemberChain.back()->getParent()->getTypeForDecl()); 15020 15021 // The base expression of the innermost MemberExpr may give 15022 // stronger guarantees than the class containing the member. 15023 if (DRE && !TopME->isArrow()) { 15024 const ValueDecl *VD = DRE->getDecl(); 15025 if (!VD->getType()->isReferenceType()) 15026 CompleteObjectAlignment = 15027 std::max(CompleteObjectAlignment, Context.getDeclAlign(VD)); 15028 } 15029 15030 // Check if the synthesized offset fulfills the alignment. 15031 if (Offset % ExpectedAlignment != 0 || 15032 // It may fulfill the offset it but the effective alignment may still be 15033 // lower than the expected expression alignment. 15034 CompleteObjectAlignment < ExpectedAlignment) { 15035 // If this happens, we want to determine a sensible culprit of this. 15036 // Intuitively, watching the chain of member expressions from right to 15037 // left, we start with the required alignment (as required by the field 15038 // type) but some packed attribute in that chain has reduced the alignment. 15039 // It may happen that another packed structure increases it again. But if 15040 // we are here such increase has not been enough. So pointing the first 15041 // FieldDecl that either is packed or else its RecordDecl is, 15042 // seems reasonable. 15043 FieldDecl *FD = nullptr; 15044 CharUnits Alignment; 15045 for (FieldDecl *FDI : ReverseMemberChain) { 15046 if (FDI->hasAttr<PackedAttr>() || 15047 FDI->getParent()->hasAttr<PackedAttr>()) { 15048 FD = FDI; 15049 Alignment = std::min( 15050 Context.getTypeAlignInChars(FD->getType()), 15051 Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl())); 15052 break; 15053 } 15054 } 15055 assert(FD && "We did not find a packed FieldDecl!"); 15056 Action(E, FD->getParent(), FD, Alignment); 15057 } 15058 } 15059 15060 void Sema::CheckAddressOfPackedMember(Expr *rhs) { 15061 using namespace std::placeholders; 15062 15063 RefersToMemberWithReducedAlignment( 15064 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1, 15065 _2, _3, _4)); 15066 } 15067 15068 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall, 15069 ExprResult CallResult) { 15070 if (checkArgCount(*this, TheCall, 1)) 15071 return ExprError(); 15072 15073 ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0)); 15074 if (MatrixArg.isInvalid()) 15075 return MatrixArg; 15076 Expr *Matrix = MatrixArg.get(); 15077 15078 auto *MType = Matrix->getType()->getAs<ConstantMatrixType>(); 15079 if (!MType) { 15080 Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg) << 0; 15081 return ExprError(); 15082 } 15083 15084 // Create returned matrix type by swapping rows and columns of the argument 15085 // matrix type. 15086 QualType ResultType = Context.getConstantMatrixType( 15087 MType->getElementType(), MType->getNumColumns(), MType->getNumRows()); 15088 15089 // Change the return type to the type of the returned matrix. 15090 TheCall->setType(ResultType); 15091 15092 // Update call argument to use the possibly converted matrix argument. 15093 TheCall->setArg(0, Matrix); 15094 return CallResult; 15095 } 15096